问:
Bootstrap Column Empty spaces when using a transition
I have a rails application that uses a model to populate the index page. The index page is displayed using bootstrap columns and rows. I added a transition to make the boxes taller on hover. I like how they look when the first one in a row is hovered over but when the middle or last box becomes tall, it leaves empty spaces to the left. I have googled extensively but I am either searching the wrong things or missing something.

My question is: How can I make it so that the empty spaces to the left of the tall box are filled with small boxes so that it looks the same to the right and left.
I am open to javascript/jQuery solutions if necessary.

Thank you in advance!

This is what I want

This is what I am getting Empty space to the left of the box

答:
Try this:

```<code><div class="masonry">
  <div class="box" id="a">A</div>
  [...]
</div>
</code>```

And css:

```<code>.box {
  height: 25px;
  border: 1px solid black;
  border-radius: 15px;
  transition:height 0.5s; /* Animation time */
  -webkit-transition:height 0.5s; /* For Safari */
  &:hover {
    height: 50px;
  }

  -webkit-column-break-inside: avoid;
          page-break-inside: avoid;
               break-inside: avoid;
    position: static;
}
.masonry {
    column-count: 4;
}
</code>```

Its currently fixed to 4 columns per row, but you can change that by changing column-count dynamically using @media (min-width: ...px) {} to suite your need!

Body:
Try this:

<div class="masonry">
  <div class="box" id="a">A</div>
  [...]
</div>

And css:

.box {
  height: 25px;
  border: 1px solid black;
  border-radius: 15px;
  transition:height 0.5s; /* Animation time */
  -webkit-transition:height 0.5s; /* For Safari */
  &:hover {
    height: 50px;
  }

  -webkit-column-break-inside: avoid;
          page-break-inside: avoid;
               break-inside: avoid;
    position: static;
}
.masonry {
    column-count: 4;
}

Its currently fixed to 4 columns per row, but you can change that by changing column-count dynamically using @media (min-width: ...px) {} to suite your need!


来源: stackexchange

问:
How to hide CTRL+U View source & disable right click and text copy?
Can anyone having solution for hide CTRL+U and right click in Firefox also?</p>

答:
I have finally find solution for the above query. Try the below code in Firefox also it's working..</p>

```<code><script type='text/javascript'>
        var isCtrl = false;
        document.onkeyup=function(e)
        {
            if(e.which == 17)
            isCtrl=false;
        }
        document.onkeydown=function(e)
        {
            if(e.which == 17)
            isCtrl=true;
            if((e.which == 85) || (e.which == 80) || (e.which == 123) || (e.which == 67) && (isCtrl == true))
            {
                return false;
            }
        }
        var isNS = (navigator.appName == "Netscape") ? 1 : 0;
        if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
        function mischandler(){
            return false;
        }
        function mousehandler(e){
            var myevent = (isNS) ? e : event;
            var eventbutton = (isNS) ? myevent.which : myevent.button;
            if((eventbutton==2)||(eventbutton==3)) return false;
        }
        document.oncontextmenu = mischandler;
        document.onmousedown = mousehandler;
        document.onmouseup = mousehandler;
</script>

<body oncontextmenu="return false;">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have finally find solution for the above query. Try the below code in Firefox also it's working..

<script type='text/javascript'>
        var isCtrl = false;
        document.onkeyup=function(e)
        {
            if(e.which == 17)
            isCtrl=false;
        }
        document.onkeydown=function(e)
        {
            if(e.which == 17)
            isCtrl=true;
            if((e.which == 85) || (e.which == 80) || (e.which == 123) || (e.which == 67) && (isCtrl == true))
            {
                return false;
            }
        }
        var isNS = (navigator.appName == "Netscape") ? 1 : 0;
        if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
        function mischandler(){
            return false;
        }
        function mousehandler(e){
            var myevent = (isNS) ? e : event;
            var eventbutton = (isNS) ? myevent.which : myevent.button;
            if((eventbutton==2)||(eventbutton==3)) return false;
        }
        document.oncontextmenu = mischandler;
        document.onmousedown = mousehandler;
        document.onmouseup = mousehandler;
</script>

<body oncontextmenu="return false;">


问:
scheme for object-oriented programmers
I'm thoroughly intrigued by Scheme, and have started with some toy programming examples, and am reading through Paul Graham's On Lisp.

One thing I haven't been able to find is a book or website intended to teach Scheme to "OO people", i.e. people like myself who've done 99 % of their coding in c++/Java/Python.

I see that closures are sort of object-y, in the sense that they have local state, and offer one or more functions that have access to that state. But I don't want to learn Scheme only to port my existing habits on to it. This is why I'm learning Scheme rather than Common Lisp at the moment; I fear that CLOS might just serve as a crutch to my existing OO habits.

What would be ideal is a book or website that offers case studies of problems solved in both an OO language, and also in Scheme in a Schemey way. I suppose I would most appreciate scientific computing and/or computer graphics problems, but anything would do.

Any pedagogical leads would be much appreciated.

答:
Congrat you, my friend ! Love cs, love functional programming.

If you are python developer it takes 3-4 days to think in scheme

Here is the best simple tutorial I have ever met http://www.shido.info/lisp/idx_scm_e.html

I found this course http://cs.gettysburg.edu/~tneller/cs341/scheme-intro/index.html and it may be useful for you

ContentLicense: CC BY-SA 2.5

Title: scheme for object-oriented programmers


问:
xargs with export is not working
I have a file which looks as below.

```<code>HOST=localhost
PORT=8080
</code>```

I want to export the above into environment. I am executing the following command to export the variables in file to environment.

cat <FileName> | xargs export

I am getting the following exception when trying to run the above command.

xargs: export: No such file or directory

答:
Why use xargs? When you can just source the file in the current shell

You can use the set builtin, along with the export instead of using a non-shell built-in like xargs. Just do below

```<code>set -o allexport
. ./file_containing_variables
set +o allexport
</code>```

The usage of allexport flag with you set(-o)/unset(+o) allows you to export variables directly from the command-line. The second line is the POSIX source (dot followed by variable name) command to reflect all variables to the current shell and within the allexport flag, it is made available permanently.

Refer GNU set built-in page for more details.

Another way in bash using input re-direction on the file

```<code>while IFS= read -r line; do
    export "$line"
done <file_containing_variables
</code>```

Title: xargs with export is not working

Body:
I have a file which looks as below.

HOST=localhost
PORT=8080

I want to export the above into environment. I am executing the following command to export the variables in file to environment.

cat <FileName> | xargs export

I am getting the following exception when trying to run the above command.

xargs: export: No such file or directory

Body:
Why use xargs? When you can just source the file in the current shell

You can use the set builtin, along with the export instead of using a non-shell built-in like xargs. Just do below

set -o allexport
. ./file_containing_variables
set +o allexport

The usage of allexport flag with you set(-o)/unset(+o) allows you to export variables directly from the command-line. The second line is the POSIX source (dot followed by variable name) command to reflect all variables to the current shell and within the allexport flag, it is made available permanently.

Refer GNU set built-in page for more details.

Another way in bash using input re-direction on the file

while IFS= read -r line; do
    export "$line"
done <file_containing_variables


问:
How to make checkbox value non editable from inspect element
I have two checkbox's  where 2 different value set to the checkbox.when a user checked the boxes value will be set. But before save it if he inspects the element and edit the value set a new value  and save into database instead of default value new value save into database.How do i stop doing that to the user..any possible suggestion?</p>

```<code><input name="installation" value="{{$product->installation}}" type="checkbox">

<input name="support" value="{{$product->support}}" type="checkbox">
</code>```

答: Well you can add a client side or server side check that ensures that the value of the checkbox has not been tampered with</p>

Body:
I have two checkbox's  where 2 different value set to the checkbox.when a user checked the boxes value will be set. But before save it if he inspects the element and edit the value set a new value  and save into database instead of default value new value save into database.How do i stop doing that to the user..any possible suggestion?

<input name="installation" value="{{$product->installation}}" type="checkbox">

<input name="support" value="{{$product->support}}" type="checkbox">


问:
Cloudconnect CSV buffer size
When I try to load a big CSV from a zip file, the execution log give me the following error:

```<code>----------------------------------------- Error details ------------------------------------------
  Component [Clientes:CLIENTES1] finished with status ERROR.
   The size of data buffer is only 100663296. Set appropriate parameter in defaultProperties file.
--------------------------------------------------------------------------------------------------
</code>```

How can I set the appropriate parameter in defaultProperties file?

I tried this link, but my cloudconnect run configurations page is different from the link:

I've created the parameters file and filled the additional parameters with the right values like said the tutorial (code bellow) and the same error appear in the screen.

```<code>Name: -config; Value: new_buffer_size.txt
</code>```

The new_buffer_size.txt content have just this line:DEFAULT_INTERNAL_IO_BUFFER_SIZE = 200000000

How can I solve this problem? I need to solve this before the world explodes.

答:
CloudConnect is designed to develop ETL(s), which can be run on GoodData cloud workers and therefore some lower level settings are surpassed as in this case. The only legitimate way is to modify the ETL the way it can process the data with current settings. Regarding to docs, the referenced article is outdated. GoodData docs team is aware if it and they are preparing docs refactoring.

Note: As you have probably noticed, CloudConnect is being powered by Javlin's Clover ETL, therefore feel free to check their forums, as you would find there how to overcome the issue on lower level (no UI), but it would work only for data processing on the local machine.

Title: Cloudconnect CSV buffer size

Body:
When I try to load a big CSV from a zip file, the execution log give me the following error:

----------------------------------------- Error details ------------------------------------------
  Component [Clientes:CLIENTES1] finished with status ERROR.
   The size of data buffer is only 100663296. Set appropriate parameter in defaultProperties file.
--------------------------------------------------------------------------------------------------

How can I set the appropriate parameter in defaultProperties file?

I tried this link, but my cloudconnect run configurations page is different from the link:

I've created the parameters file and filled the additional parameters with the right values like said the tutorial (code bellow) and the same error appear in the screen.

Name: -config; Value: new_buffer_size.txt

The new_buffer_size.txt content have just this line:DEFAULT_INTERNAL_IO_BUFFER_SIZE = 200000000

How can I solve this problem? I need to solve this before the world explodes.


问:
Spring boot Controller is not able to find the bean class

I am new at Spring and i am tring to built a simple registration form using spring boot and storing user information in mysql database using jpa.

This is my error stack.

```<code>----------

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2017-06-05 12:34:53.392  INFO 9128 --- [           main] com.mohit.LoanapimainApplication         : Starting LoanapimainApplication on MOHIT with PID 9128 (C:\Users\admin\Documents\workspace-sts-3.8.4.RELEASE\loanapimain\target\classes started by admin in C:\Users\admin\Documents\workspace-sts-3.8.4.RELEASE\loanapimain)
2017-06-05 12:34:53.407  INFO 9128 --- [           main] com.mohit.LoanapimainApplication         : No active profile set, falling back to default profiles: default
2017-06-05 12:34:53.815  INFO 9128 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@396c1e: startup date [Mon Jun 05 12:34:53 IST 2017]; root of context hierarchy
2017-06-05 12:34:55.754  INFO 9128 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-05 12:34:55.772  INFO 9128 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-06-05 12:34:55.772  INFO 9128 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-06-05 12:34:56.006  INFO 9128 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-06-05 12:34:56.006  INFO 9128 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2207 ms
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-05 12:34:56.756  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:56.771  INFO 9128 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-06-05 12:34:56.927  INFO 9128 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-06-05 12:34:57.052  INFO 9128 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-06-05 12:34:57.615  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:57.631  WARN 9128 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'user'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mohit.beans.User' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-06-05 12:34:57.631  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:57.631  INFO 9128 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-06-05 12:34:57.646  INFO 9128 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-05 12:34:57.740 ERROR 9128 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field user in com.mohit.Controllers.UserController required a bean of type 'com.mohit.beans.User' that could not be found.
</code>```

Action:

Consider defining a bean of type 'com.mohit.beans.User' in your configuration.

Contoller`

```<code>package com.mohit.Controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mohit.beans.User;

import com.mohit.Services.createuser;

@Controller
public class UserController {

    @Autowired(required=true)
    private User user;
    @Autowired(required=true)
    private createuser create;

    @RequestMapping("/")
    public String sayhi(){

        return "index";

    }

    @RequestMapping("/index")
    public String Createuser(@RequestParam(value="uname") String name,@RequestParam(value="pass") String pass, Model model){
        user.setUname(name);
        user.setPass(pass);
        create.adduser(user);
        return "result";

    }

    public String AuthUser(@RequestParam(value="name") String name,@RequestParam(value="pass") String pass, Model model){

        return "mainpage";

    }

}

----------
</code>```

bean class

```<code> --------------

----------

    package com.mohit.beans;

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

@Entity
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String uname;
    private String pass;
    public User(String uname, String pass) {
        super();

        this.uname = uname;
        this.pass = pass;
    }

    public User() {
        super();
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", uname=" + uname + ", pass=" + pass + "]";
    }

}

----------
</code>```

Service class

```<code>----------
package com.mohit.Services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mohit.Repo.userrepo;
import com.mohit.beans.User;

@Service
public class createuser {

    @Autowired
    private userrepo Userrepo;

    public void adduser(User user)
    {
        Userrepo.save(user);
    }

}

----------
</code>```

Repository

```<code>--------------

----------

    package com.mohit.Repo;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.mohit.beans.User;

public interface userrepo extends PagingAndSortingRepository<User,String> {

}

----------
</code>```

pom.xml`

```<code>----------

?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>com.mohit</groupId>
    <artifactId>loanapimain</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>loanapimain</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

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

</project>

----------
</code>```

Application.config

```<code>    spring.datasource.url=jdbc:mysql://localhost/project
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

----------
</code>```

LoanapiApplication.java`

```<code>package com.mohit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LoanapimainApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoanapimainApplication.class, args);
    }
}
</code>```

答:
User is not a bean but Entity - simple POJO class. It can't be autowired.

Change the logic to

```<code>@RequestMapping("/index")
public String Createuser(@RequestParam(value="uname") String name,@RequestParam(value="pass") String pass, Model model){
    User user = new User();
    user.setUname(name);
    user.setPass(pass);
    create.adduser(user);
    return "result";

}
</code>```

and remove the User field from the controller

Body:
I am new at Spring and i am tring to built a simple registration form using spring boot and storing user information in mysql database using jpa.

This is my error stack.

----------

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2017-06-05 12:34:53.392  INFO 9128 --- [           main] com.mohit.LoanapimainApplication         : Starting LoanapimainApplication on MOHIT with PID 9128 (C:\Users\admin\Documents\workspace-sts-3.8.4.RELEASE\loanapimain\target\classes started by admin in C:\Users\admin\Documents\workspace-sts-3.8.4.RELEASE\loanapimain)
2017-06-05 12:34:53.407  INFO 9128 --- [           main] com.mohit.LoanapimainApplication         : No active profile set, falling back to default profiles: default
2017-06-05 12:34:53.815  INFO 9128 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@396c1e: startup date [Mon Jun 05 12:34:53 IST 2017]; root of context hierarchy
2017-06-05 12:34:55.754  INFO 9128 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-05 12:34:55.772  INFO 9128 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-06-05 12:34:55.772  INFO 9128 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-06-05 12:34:56.006  INFO 9128 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-06-05 12:34:56.006  INFO 9128 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2207 ms
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-05 12:34:56.163  INFO 9128 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-05 12:34:56.756  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:56.771  INFO 9128 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-06-05 12:34:56.881  INFO 9128 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-06-05 12:34:56.927  INFO 9128 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-06-05 12:34:57.052  INFO 9128 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-06-05 12:34:57.615  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:57.631  WARN 9128 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'user'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mohit.beans.User' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-06-05 12:34:57.631  INFO 9128 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-06-05 12:34:57.631  INFO 9128 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-06-05 12:34:57.646  INFO 9128 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-05 12:34:57.740 ERROR 9128 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field user in com.mohit.Controllers.UserController required a bean of type 'com.mohit.beans.User' that could not be found.

Action:

Consider defining a bean of type 'com.mohit.beans.User' in your configuration.

Contoller`

package com.mohit.Controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mohit.beans.User;

import com.mohit.Services.createuser;

@Controller
public class UserController {

    @Autowired(required=true)
    private User user;
    @Autowired(required=true)
    private createuser create;

    @RequestMapping("/")
    public String sayhi(){

        return "index";

    }

    @RequestMapping("/index")
    public String Createuser(@RequestParam(value="uname") String name,@RequestParam(value="pass") String pass, Model model){
        user.setUname(name);
        user.setPass(pass);
        create.adduser(user);
        return "result";

    }

    public String AuthUser(@RequestParam(value="name") String name,@RequestParam(value="pass") String pass, Model model){

        return "mainpage";

    }

}

----------

bean class

 --------------

----------

    package com.mohit.beans;

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

@Entity
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String uname;
    private String pass;
    public User(String uname, String pass) {
        super();

        this.uname = uname;
        this.pass = pass;
    }

    public User() {
        super();
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", uname=" + uname + ", pass=" + pass + "]";
    }

}

----------

Service class

----------
package com.mohit.Services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mohit.Repo.userrepo;
import com.mohit.beans.User;

@Service
public class createuser {

    @Autowired
    private userrepo Userrepo;

    public void adduser(User user)
    {
        Userrepo.save(user);
    }

}

----------

Repository

--------------

----------

    package com.mohit.Repo;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.mohit.beans.User;

public interface userrepo extends PagingAndSortingRepository<User,String> {

}

----------

pom.xml`

----------

?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>com.mohit</groupId>
    <artifactId>loanapimain</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>loanapimain</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

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

</project>

----------

Application.config

    spring.datasource.url=jdbc:mysql://localhost/project
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

----------

LoanapiApplication.java`

package com.mohit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LoanapimainApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoanapimainApplication.class, args);
    }
}

Body:
User is not a bean but Entity - simple POJO class. It can't be autowired.

Change the logic to

@RequestMapping("/index")
public String Createuser(@RequestParam(value="uname") String name,@RequestParam(value="pass") String pass, Model model){
    User user = new User();
    user.setUname(name);
    user.setPass(pass);
    create.adduser(user);
    return "result";

}

and remove the User field from the controller


问:
Confirm User to Change Route without saving details while editing Angular 2
If the user is editing something and try to change the route without saving details.

in this condition I want to alter the user that 'your changes are not saved do you want to go away'. according to the user can we prevent component to destroy the component.

I try a guard but guard run before ngOnDestroy method run.
So what should I do?

答:
trigger NavigationStart of Router to do jobs before leaving current route.

```<code>constructor(private router: Router) {
  ..
  this.router.events.forEach((e: any) => {
    if (e instanceof NavigationStart) {
      // do confirm here.
    }
  });
}
</code>```

Body:
trigger NavigationStart of Router to do jobs before leaving current route.

constructor(private router: Router) {
  ..
  this.router.events.forEach((e: any) => {
    if (e instanceof NavigationStart) {
      // do confirm here.
    }
  });
}


问:
How to make this code to loop 10 times per page?
```<code><?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbsql", $con);

$result = mysql_query("SELECT * FROM testimonial where approved='Yes'");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Review</th>
<th>Date</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['full_name'] . "</td>";
  echo "<td>" . $row['review'] . "</td>";
    echo "<td>" . $row['date'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
</code>```

答:
replace

```<code>SELECT * FROM testimonial where approved='Yes'
</code>```

with

```<code>$offset = 0; //calculate your offset here as per page;

SELECT * FROM testimonial where approved='Yes' limit $offset, 10
</code>```

Body:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbsql", $con);

$result = mysql_query("SELECT * FROM testimonial where approved='Yes'");

echo "

Firstname
Review
Date

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['full_name'] . "	";
  echo "" . $row['review'] . "	";
    echo "" . $row['date'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);
?>

Body:
replace

SELECT * FROM testimonial where approved='Yes'

with

$offset = 0; //calculate your offset here as per page;

SELECT * FROM testimonial where approved='Yes' limit $offset, 10


问:
Is there a way to execute a scala class using eclipse?
Im very new to Scala programming and learning it. One of the interesting thing for me in Scala is most of the times the topics are explain by writing Scala Objects.
I tried to write a small scala class in eclipse in two separate classes and created an object like below.

```<code>package com.scala.programs

class DisplayStatement {
  def hello(name:String):String = {
    return "Hello " + name
  }
}
</code>```

My Main class is in another packacge and in another class:

```<code>package com.scala.mainclasses

import com.scala.programs.DisplayStatement

class Display {
  def main(args: Array[String]) {
    DisplayStatement ds = new DisplayStatement();
    ds.hello("scala");
  }
}
</code>```

I tried to do it just like it is Java. But Im getting error in these two statements.

```<code>DisplayStatement ds = new DisplayStatement();
ds.hello("scala");
</code>```

Below are the error messages:

```<code>Error Messages: not found: value DisplayStatement
not found: value ds
</code>```

I understood it when a scala object is written and executed.
I know that Im making some mistake here but can anyone tell me how to create an object of a class and execute it in Scala programming or is it possible and why is it most of the times the programs are written in the form of Object directly rather class.

答:
Scala is not Java, the syntax for defining variables is:

```<code> var/val name : type
</code>```

so you should do:

```<code>val ds: DisplayStatement = new DisplayStatement()
</code>```

but you don't even need the type here:

```<code>val ds = new DisplayStatement()
</code>```

and you do not need to use the return keyword:

```<code>def hello(name:String):String = "Hello " + name
</code>```

I would first read some tutorials

Body:
Im very new to Scala programming and learning it. One of the interesting thing for me in Scala is most of the times the topics are explain by writing Scala Objects.
I tried to write a small scala class in eclipse in two separate classes and created an object like below.

package com.scala.programs

class DisplayStatement {
  def hello(name:String):String = {
    return "Hello " + name
  }
}

My Main class is in another packacge and in another class:

package com.scala.mainclasses

import com.scala.programs.DisplayStatement

class Display {
  def main(args: Array[String]) {
    DisplayStatement ds = new DisplayStatement();
    ds.hello("scala");
  }
}

I tried to do it just like it is Java. But Im getting error in these two statements.

DisplayStatement ds = new DisplayStatement();
ds.hello("scala");

Below are the error messages:

Error Messages: not found: value DisplayStatement
not found: value ds

I understood it when a scala object is written and executed.
I know that Im making some mistake here but can anyone tell me how to create an object of a class and execute it in Scala programming or is it possible and why is it most of the times the programs are written in the form of Object directly rather class.

Body:
Scala is not Java, the syntax for defining variables is:

 var/val name : type

so you should do:

val ds: DisplayStatement = new DisplayStatement()

but you don't even need the type here:

val ds = new DisplayStatement()

and you do not need to use the return keyword:

def hello(name:String):String = "Hello " + name

I would first read some tutorials


问:
Setting a CSV filename as a variable in jmeter, based on date modified
I'm trying to set a variable from a CSV filename, specifically the file with the last date modified. The CSV files are based on data from my tests, so that file will be constantly changing. I've tried this code but I can't seem to get it to save as a variable.

```<code>public static File getLatestFilefromDir(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
       lastModifiedFile = files[i];
   }
}
return lastModifiedFile;
}

   String fileName = lastModifiedFile;

    vars.put("FILENAME", fileName);
</code>```

Thank you for your help.

答:
The fix for your code is converting File to its name</p>

```<code>String fileName = getLatestFilefromDir("...").getName();
</code>```

Body:
I'm trying to set a variable from a CSV filename, specifically the file with the last date modified. The CSV files are based on data from my tests, so that file will be constantly changing. I've tried this code but I can't seem to get it to save as a variable.

public static File getLatestFilefromDir(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
       lastModifiedFile = files[i];
   }
}
return lastModifiedFile;
}

   String fileName = lastModifiedFile;

    vars.put("FILENAME", fileName);

Thank you for your help.

Body:
The fix for your code is converting File to its name

String fileName = getLatestFilefromDir("...").getName();


问:
js use async as default in import
Is it possible to have an import automatically be async.

Right now I have to do this:

main.js

```<code>import './import.js'
</code>```

import.js

```<code>(async() => {
    const result = await fetch(...);
    console.log(result);
})();
</code>```

But I would rather have it without the self invoking function:

import.js

```<code>    const result = await fetch(...);
    console.log(result);
</code>```

答:
No you can't. await must always be inside of an async block.

See https://tc39.github.io/ecma262/#sec-async-function-definitions

Title: js use async as default in import

Body:
Is it possible to have an import automatically be async.

Right now I have to do this:

main.js

import './import.js'

import.js

(async() => {
    const result = await fetch(...);
    console.log(result);
})();

But I would rather have it without the self invoking function:

import.js

    const result = await fetch(...);
    console.log(result);


问:
How can i change div contenteditable = "false" to "true"?
I am playing around with angular2. I want to change the value of a div-
Need to change all contenteditable="false" to contenteditable="true" which are there on my HTML page.

Please note sometimes the contenteditable="false" will be added to a DIV tag and sometimes to P, h1 tag or some other.

The html looks as following:

```<code><button (click)="selectDiv()">select div</button>
<section>
      <div class="content">
        <h1 contenteditable="false" >Resize your browser and see how they adapt.</h1>
        <h1 contenteditable="false" >text2.</h1>
      </div>
      <div class="content" contenteditable="false">
        <p>Content 2.</p>
        <h1>text2.</h1>
      </div>
</section>
</code>```

Please guide me what should i write in explore.ts so that when i click the button, selectDiv() is called and the function is executed and all the contenteditable="false" becomes "true"

Please note there can be any number of contenteditable="false" in my code.

```<code>selectDiv(){
//what should i write here
}
</code>```

答:
For an Angular way of doing it:

HTML

```<code><button (click)="selectDiv()">select div</button>
<section>
  <div class="content">
    <h1 [contentEditable]="contentEditable">Resize your browser and see how they adapt.</h1>
    <h1 [contentEditable]="contentEditable">text2.</h1>
  </div>

  <div class="content" [contentEditable]="contentEditable">
    <p>Content 2.</p>
    <h1>text2.</h1>
  </div>
</section>
</code>```

TypeScript Controller

```<code>...
private contentEditable: boolean = false;
...
selectDiv(): void {
    this.contentEditable = true;
}
...
</code>```

Body:
I am playing around with angular2. I want to change the value of a div-
Need to change all contenteditable="false" to contenteditable="true" which are there on my HTML page.

Please note sometimes the contenteditable="false" will be added to a DIV tag and sometimes to P, h1 tag or some other.

The html looks as following:

<button (click)="selectDiv()">select div</button>

Resize your browser and see how they adapt.

text2.

Content 2.

text2.

Please guide me what should i write in explore.ts so that when i click the button, selectDiv() is called and the function is executed and all the contenteditable="false" becomes "true"

Please note there can be any number of contenteditable="false" in my code.

selectDiv(){
//what should i write here
}

Body:
For an Angular way of doing it:

HTML

<button (click)="selectDiv()">select div</button>
<section>
  <div class="content">
    <h1 [contentEditable]="contentEditable">Resize your browser and see how they adapt.</h1>
    <h1 [contentEditable]="contentEditable">text2.</h1>
  </div>

  <div class="content" [contentEditable]="contentEditable">
    <p>Content 2.</p>
    <h1>text2.</h1>
  </div>
</section>

TypeScript Controller

...
private contentEditable: boolean = false;
...
selectDiv(): void {
    this.contentEditable = true;
}
...


问:
getting stuck at saving a string
i get a encoded string when saving a string
When i save:

```<code>'FFFA
</code>```

i get:

```<code>'FFFA
</code>```

how can i save them using the ff curl request:

```<code>curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
      "custom_html": "",
      "expand_horizontal_direction": "left",
      "expand_vertical_direction": "down",
      "height": 250,
      "html_content_below": "Hello 'world",
      "location": "http://www.google.ca",
      "name": "Demo Custom HTML' Banner",
      "tracking_pixel": "url",
      "width": 300
    }'
</code>```

答:
set another curl option for  CURLOPT_ENCODING and set it to "" to ensure it will not return any garbage

```<code>     $location = 'https://api.adbutler.com/v1/banners/custom-html';
$ch = curl_init($location);
       curl_setopt($ch, CURLOPT_ENCODING ,"");
</code>```

Title: getting stuck at saving a string

Body:
i get a encoded string when saving a string
When i save:

'FFFA

i get:

'FFFA

how can i save them using the ff curl request:

curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
      "custom_html": "",
      "expand_horizontal_direction": "left",
      "expand_vertical_direction": "down",
      "height": 250,
      "html_content_below": "Hello 'world",
      "location": "http://www.google.ca",
      "name": "Demo Custom HTML' Banner",
      "tracking_pixel": "url",
      "width": 300
    }'

Body:
set another curl option for  CURLOPT_ENCODING and set it to "" to ensure it will not return any garbage

     $location = 'https://api.adbutler.com/v1/banners/custom-html';
$ch = curl_init($location);
       curl_setopt($ch, CURLOPT_ENCODING ,"");


问:
detach all packages while working in R
While working to solve another problem I got this problem:

I can remove all  R objects by:

```<code>rm(list = ls(all = TRUE))
</code>```

Is there equivalent command that can detach installed packages during working session?

```<code>> sessionInfo()
R version 2.12.2 (2011-02-25)
Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
</code>```

require(ggplot2)

```<code>Loading required package: ggplot2
Loading required package: reshape
Loading required package: plyr

Attaching package: 'reshape'

The following object(s) are masked from 'package:plyr':

    round_any

Loading required package: grid
Loading required package: proto
</code>```

sessionInfo()

```<code>R version 2.12.2 (2011-02-25)
Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
[1] ggplot2_0.8.9 proto_0.3-9.1 reshape_0.8.4 plyr_1.4
</code>```

I tried this way, although even it worked in not a global solution :

```<code>pkg <- c("package:ggplot2_0.8.9", "package:proto_0.3-9.1", "package:reshape_0.8.4",  "package:plyr_1.4")

 detach(pkg, character.only = TRUE)

Error in detach(pkg, character.only = TRUE) : invalid 'name' argument
In addition: Warning message:
In if (is.na(pos)) stop("invalid 'name' argument") :
  the condition has length > 1 and only the first element will be used
</code>```

What I am loking for is something global like:

```<code>  rm(list = ls(all = TRUE))
</code>```

for objects, expect it would not remove attached base packages

thanks;

答: or if you have RStudio, simply uncheck all the checked boxes in Packages Tab to detach</p>

Title: detach all packages while working in R

Body:
While working to solve another problem I got this problem:

I can remove all  R objects by:

rm(list = ls(all = TRUE))

Is there equivalent command that can detach installed packages during working session?

> sessionInfo()
R version 2.12.2 (2011-02-25)
Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

require(ggplot2)

Loading required package: ggplot2
Loading required package: reshape
Loading required package: plyr

Attaching package: 'reshape'

The following object(s) are masked from 'package:plyr':

    round_any

Loading required package: grid
Loading required package: proto

sessionInfo()

R version 2.12.2 (2011-02-25)
Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
[1] ggplot2_0.8.9 proto_0.3-9.1 reshape_0.8.4 plyr_1.4

I tried this way, although even it worked in not a global solution :

pkg <- c("package:ggplot2_0.8.9", "package:proto_0.3-9.1", "package:reshape_0.8.4",  "package:plyr_1.4")

 detach(pkg, character.only = TRUE)

Error in detach(pkg, character.only = TRUE) : invalid 'name' argument
In addition: Warning message:
In if (is.na(pos)) stop("invalid 'name' argument") :
  the condition has length > 1 and only the first element will be used

What I am loking for is something global like:

  rm(list = ls(all = TRUE))

for objects, expect it would not remove attached base packages

thanks;


问:
R store the for loop output in vector
I am R beginner, the following is my code:

```<code>complete <- function(directory, id = 1:332) {

# Read through all the csv data file
for (i in id) {
    i <- sprintf("%03d", as.numeric(i))
    data <- read.csv(paste(directory, "/", i, ".csv", sep =""))
    good <- complete.cases(data)   # Eliminating the NA rows
    cases <- sum(good == TRUE)  # add complete value
}

data.frame(id = id, nobs = cases )
}
</code>```

when I print the output

```<code> id nobs
1  1  402
2  2  402
3  3  402
4  4  402
5  5  402          (incorrect)
</code>```

if I just print the cases

```<code>[1] 117
[1] 1041
[1] 243
[1] 474
[1] 402
</code>```

so the correct output should be

```<code>  id nobs
1  1  117
2  2 1041
3  3  243
4  4  474
5  5  402
</code>```

I realize it only take last value from the (cases).

My question is how can I store the (cases) output into a vector
so when I call the data.frame function it will return the correct output.

thanks

答:
```<code>complete <- function(directory ,id = 1:332){
  folder = directory
  df_total = data.frame()
  for (x in id){
    filenames <- sprintf("%03d.csv", x)
    filenames <- paste(folder,filenames,sep="\\")
    df <- do.call(rbind,lapply(filenames,read.csv, header=TRUE))
    my_vector <- sum(complete.cases(enter the column for which you want))
    df1 <- data.frame(id=x,nobs=my_vector)
    df_total <- rbind(df_total,df1)
  }
  df_total
}
</code>```

Title: R store the for loop output in vector

Body:
I am R beginner, the following is my code:

complete <- function(directory, id = 1:332) {

# Read through all the csv data file
for (i in id) {
    i <- sprintf("%03d", as.numeric(i))
    data <- read.csv(paste(directory, "/", i, ".csv", sep =""))
    good <- complete.cases(data)   # Eliminating the NA rows
    cases <- sum(good == TRUE)  # add complete value
}

data.frame(id = id, nobs = cases )
}

when I print the output

 id nobs
1  1  402
2  2  402
3  3  402
4  4  402
5  5  402          (incorrect)

if I just print the cases

[1] 117
[1] 1041
[1] 243
[1] 474
[1] 402

so the correct output should be

  id nobs
1  1  117
2  2 1041
3  3  243
4  4  474
5  5  402

I realize it only take last value from the (cases).

My question is how can I store the (cases) output into a vector
so when I call the data.frame function it will return the correct output.

thanks


问:
setTimeout for whole site, not just one page
How would I use setTimeout() - or any other javascript method - to call a function when the user had been on my website for 45 seconds.

I was using the below:

```<code>setTimeout(function(){ ....code.... }, 45000);
</code>```

But if the user navigated off the page and onto another page on the site before 45 seconds, the timer was reset.

I'd like the setTimeout to apply to the time the user landed on the first page, regardless of what page they are on now.

I will be including this javascript on every page on the site.

Thanks.

答:
Just add that javascript file to all the pages with the setTimeout function. It will reset automatically when the user goes to other pages:

setTimeout(() => { ... }, 45e3)

If I understood correctly you also want to save the time IF the user is more than 45 seconds on the page. Then use localStorage for that. First get the time he has been on the site with a date object:

```<code>let timer = new Date()
</code>```

Then save the difference on localStorage (in milliseconds):

```<code>localStorage.setItem("Time on site", new Date().getTime() - timer.getTime())
</code>```

Whenever you want to access that time use:

```<code>localStorage.getItem("Time on site")
</code>```

Execute the timer when the page loads inside:

```<code>let timer
window.addEventListener('load', () => {
    timer = new Date()
})
</code>```

Body:
How would I use setTimeout() - or any other javascript method - to call a function when the user had been on my website for 45 seconds.

I was using the below:

setTimeout(function(){ ....code.... }, 45000);

But if the user navigated off the page and onto another page on the site before 45 seconds, the timer was reset.

I'd like the setTimeout to apply to the time the user landed on the first page, regardless of what page they are on now.

I will be including this javascript on every page on the site.

Thanks.

Body:
Just add that javascript file to all the pages with the setTimeout function. It will reset automatically when the user goes to other pages:

setTimeout(() => { ... }, 45e3)

If I understood correctly you also want to save the time IF the user is more than 45 seconds on the page. Then use localStorage for that. First get the time he has been on the site with a date object:

let timer = new Date()

Then save the difference on localStorage (in milliseconds):

localStorage.setItem("Time on site", new Date().getTime() - timer.getTime())

Whenever you want to access that time use:

localStorage.getItem("Time on site")

Execute the timer when the page loads inside:

let timer
window.addEventListener('load', () => {
    timer = new Date()
})


问:
Aggregate by sub-category, then order by category in SQL
I am trying to aggregate (count) data by sub-category but I need them to be ordered based on overall category count in descending order?

For example, my column headers are:

```<code>tbl (table name)
singularity_id (key)
product_cat (category)
consumption_location (sub-category)
</code>```

My SQL query is:

```<code>SELECT
    product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
    tbl
GROUP BY
    product_cat, consumption_location
ORDER BY
    product_cat, consumption_location, count DESC;
</code>```

This groups product_cat and consumption_location but does not order by product_cat count desc.

So my data currently looks like this, based on my query:

```<code>product_cat | consumption_location | count
------------+----------------------+--------
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
</code>```

What I want is:

```<code>product_cat | consumption_location | count
------------+----------------------+--------
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
</code>```

Since Soft Drink has the most overall entries, followed by Water, then Fruit Juice.

答:
```<code>with temptbl as
    (select  distinct product_cat, consumption_location,
        count(SINGULARITY_ID) over (partition by product_cat) cntcat ,
        count(SINGULARITY_ID) over (partition by
        product_cat,consumption_location) as cntsub
     from t2  order by cntcat desc
    )
select product_cat ,consumption_location , cntsub from temptbl ;
</code>```

Body:
I am trying to aggregate (count) data by sub-category but I need them to be ordered based on overall category count in descending order?

For example, my column headers are:

tbl (table name)
singularity_id (key)
product_cat (category)
consumption_location (sub-category)

My SQL query is:

SELECT
    product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
    tbl
GROUP BY
    product_cat, consumption_location
ORDER BY
    product_cat, consumption_location, count DESC;

This groups product_cat and consumption_location but does not order by product_cat count desc.

So my data currently looks like this, based on my query:

product_cat | consumption_location | count
------------+----------------------+--------
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500

What I want is:

product_cat | consumption_location | count
------------+----------------------+--------
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600

Since Soft Drink has the most overall entries, followed by Water, then Fruit Juice.


问:
Why compiler don't prevent us, when we try to add duplicate object in Hashset?
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

```<code>public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}
</code>```

OUTPUT- [A]

答:
The Set interface allows you to attempt to add the same element again and again. It will simply add the element just the first time.

It is not an error to attempt to add the same element multiple times.

boolean java.util.Set.add(E e)

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

This allows you to check if an element belongs to the Set and add it to the Set if not with a single statement:

```<code>if (set.add(value)) {
    .... // will be executed only if the value was added
}
</code>```

instead of the longer

```<code>if (!set.contains(value)) {
    set.add(value);
    ....
}
</code>```

Body:
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}

OUTPUT- [A]

Body:
The Set interface allows you to attempt to add the same element again and again. It will simply add the element just the first time.

It is not an error to attempt to add the same element multiple times.

boolean java.util.Set.add(E e)

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

This allows you to check if an element belongs to the Set and add it to the Set if not with a single statement:

if (set.add(value)) {
    .... // will be executed only if the value was added
}

instead of the longer

if (!set.contains(value)) {
    set.add(value);
    ....
}


问:
c# Extend an Expression
I would like to extend an expression (Expression<Func<TModel, TProperty>>):

```<code>class CustomModel
{
    public BlobModel Blob { get; set; }

    public class BlobModel
    {
        public string SubBlob { get; set; }
    }
}

var expression = model => model.Blog;
var subBlobExpression = expression.???.SubBlob;
</code>```

It is possible?
The goal is to use the validation in a shared partialview (ASP.NET MVC project).

The htmlAttributes in the ValidationMessageFor method doesn't work and use the model without Expression either!

答:
Unclear what you exactly want and what limits you have, BUT:

```<code>// Taken (with some cuts) from https://stackoverflow.com/a/32007349/613130

// A simple expression visitor to replace some nodes of an expression
// with some other nodes. Can be used with anything, not only with
// ParameterExpression
public class SimpleExpressionReplacer : ExpressionVisitor
{
    public readonly Dictionary<Expression, Expression> Replaces;

    public SimpleExpressionReplacer(Expression from, Expression to)
    {
        Replaces = new Dictionary<Expression, Expression> { { from, to } };
    }

    public override Expression Visit(Expression node)
    {
        Expression to;

        if (node != null && Replaces.TryGetValue(node, out to))
        {
            return base.Visit(to);
        }

        return base.Visit(node);
    }
}

public static Expression<Func<T, TProp2>> ExtendExpression<T, TProp1, TProp2>(Expression<Func<T, TProp1>> exp1, Expression<Func<TProp1, TProp2>> exp2)
{
    Expression body3 = new SimpleExpressionReplacer(exp2.Parameters[0], exp1.Body).Visit(exp2.Body);
    Expression<Func<T, TProp2>> exp3 = Expression.Lambda<Func<T, TProp2>>(body3, exp1.Parameters);
    return exp3;
}
</code>```

Use it like:

```<code>Expression<Func<CustomModel, CustomModel.BlobModel>> expression = model => model.Blob;
var exp2 = ExtendExpression(expression, x => x.SubBlob);
</code>```

I use an expression replacer (SimpleExpressionReplacer) to "merge" together the two expresion (expression and x => x.SubBlob).

Title: c# Extend an Expression

Body:
I would like to extend an expression (Expression<Func<TModel, TProperty>>):

class CustomModel
{
    public BlobModel Blob { get; set; }

    public class BlobModel
    {
        public string SubBlob { get; set; }
    }
}

var expression = model => model.Blog;
var subBlobExpression = expression.???.SubBlob;

It is possible?
The goal is to use the validation in a shared partialview (ASP.NET MVC project).

The htmlAttributes in the ValidationMessageFor method doesn't work and use the model without Expression either!

Body:
Unclear what you exactly want and what limits you have, BUT:

// Taken (with some cuts) from https://stackoverflow.com/a/32007349/613130

// A simple expression visitor to replace some nodes of an expression
// with some other nodes. Can be used with anything, not only with
// ParameterExpression
public class SimpleExpressionReplacer : ExpressionVisitor
{
    public readonly Dictionary<Expression, Expression> Replaces;

    public SimpleExpressionReplacer(Expression from, Expression to)
    {
        Replaces = new Dictionary<Expression, Expression> { { from, to } };
    }

    public override Expression Visit(Expression node)
    {
        Expression to;

        if (node != null && Replaces.TryGetValue(node, out to))
        {
            return base.Visit(to);
        }

        return base.Visit(node);
    }
}

public static Expression<Func<T, TProp2>> ExtendExpression<T, TProp1, TProp2>(Expression<Func<T, TProp1>> exp1, Expression<Func<TProp1, TProp2>> exp2)
{
    Expression body3 = new SimpleExpressionReplacer(exp2.Parameters[0], exp1.Body).Visit(exp2.Body);
    Expression<Func<T, TProp2>> exp3 = Expression.Lambda<Func<T, TProp2>>(body3, exp1.Parameters);
    return exp3;
}

Use it like:

Expression<Func<CustomModel, CustomModel.BlobModel>> expression = model => model.Blob;
var exp2 = ExtendExpression(expression, x => x.SubBlob);

I use an expression replacer (SimpleExpressionReplacer) to "merge" together the two expresion (expression and x => x.SubBlob).


问:
React-native: margin not taken into account in a flex layout
I encountered a few times issues with margins when layouting views using flexbox.

I managed to reproduce the issue with a small code snippet:

Here is a custom component:

```<code>class MyView extends Component {
  render() {
    return (
      <View style={
        {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }
      }/>
    );
  }
}
</code>```

and here is how I use it:

```<code><View style={{ flexDirection: 'column' }}>
  <MyView />
  <MyView style={{ marginTop: 12 }}/>
</View>
</code>```

So I am expecting to see 2 green squares on top of each other, separated by 12px (due to the marginTop). Instead here is what I see:

The two squares touch each other. I have no idea why the margin is not taken into account.

I tried debugging the bottom view with the inspector tool, here is what's getting displayed:

You can actually see the margin on this image (light orange). Any idea why the margin is not taken into account?

答:
```<code>class MyView extends Component {
  render() {
    const { style } = this.props;
    return (
      <View style={
        [style, {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }]
      }/>
    );
  }
}

MyView.propTypes = {
  style: React.propTypes.shape({
    marginTop: React.propTypes.number
  })
}

MyView.defaultProps = {
  style: {
    marginTop: 0
  }
}
</code>```

You are passing style into MyView as a prop. I've added propTypes and defaultProps as you only pass the style prop on occasion.

From the React docs

All of the core components accept a prop named style.

Because your component is not a core component, style doesn't work as you expect it to.

Body:
I encountered a few times issues with margins when layouting views using flexbox.

I managed to reproduce the issue with a small code snippet:

Here is a custom component:

class MyView extends Component {
  render() {
    return (
      <View style={
        {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }
      }/>
    );
  }
}

and here is how I use it:

<View style={{ flexDirection: 'column' }}>
  <MyView />
  <MyView style={{ marginTop: 12 }}/>
</View>

So I am expecting to see 2 green squares on top of each other, separated by 12px (due to the marginTop). Instead here is what I see:

The two squares touch each other. I have no idea why the margin is not taken into account.

I tried debugging the bottom view with the inspector tool, here is what's getting displayed:

You can actually see the margin on this image (light orange). Any idea why the margin is not taken into account?

Body:
class MyView extends Component {
  render() {
    const { style } = this.props;
    return (
      <View style={
        [style, {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }]
      }/>
    );
  }
}

MyView.propTypes = {
  style: React.propTypes.shape({
    marginTop: React.propTypes.number
  })
}

MyView.defaultProps = {
  style: {
    marginTop: 0
  }
}

You are passing style into MyView as a prop. I've added propTypes and defaultProps as you only pass the style prop on occasion.

From the React docs

All of the core components accept a prop named style.

Because your component is not a core component, style doesn't work as you expect it to.


问:
Getting illegalargumentException: column 'data1' does not exist in Android
I am trying to put Name and phone numbers from contacts to my customized listView with help of Custom CursorAdapter, But I am getting the following error

Exception

```<code> 11-07 17:53:39.619: ERROR/AndroidRuntime(628): FATAL EXCEPTION: main
 11-07 17:53:39.619: ERROR/AndroidRuntime(628): java.lang.IllegalArgumentException: column      'data1' does not exist
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:99)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at org.com.apis.ContactListCustomCursorAdapter.bindView(ContactListCustomCursorAdapter.java:37)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.CursorAdapter.getView(CursorAdapter.java:186)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.AbsListView.obtainView(AbsListView.java:1315)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.ListView.onMeasure(ListView.java:1109)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.os.Handler.dispatchMessage(Handler.java:99)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.os.Looper.loop(Looper.java:123)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.app.ActivityThread.main(ActivityThread.java:4627)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at java.lang.reflect.Method.invokeNative(Native Method)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at java.lang.reflect.Method.invoke(Method.java:521)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at dalvik.system.NativeStart.main(Native Method)
</code>```

Here is the Code I am using

Main Activity Code

```<code> public class ManipulationActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.contacts_list_layout);

    Cursor cursor = getCursor();

    ListView contactList = (ListView)findViewById(R.id.contactList);
    contactList.setAdapter(new ContactListCustomCursorAdapter(this, cursor)); //ContactListCustomCursorAdapter is a customized CursorAdapter. I have put the code below this class

}

    //Get Cursor pointing Contacts
private Cursor getCursor() {

    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
    while (cursor.moveToNext()) {
       String contactId = cursor.getString(cursor.getColumnIndex(
       ContactsContract.Contacts._ID));
       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
       if (Boolean.parseBoolean(hasPhone)) {
          // You know it has a number so now query it like this
          Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
          while (phones.moveToNext()) {
             String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
          }
       phones.close();
       }
    }
    cursor.close();
    return cursor;
}

}
</code>```

ContactListCustomCursorAdapter Code

```<code>public class ContactListCustomCursorAdapter extends CursorAdapter {

private Context context;
private Cursor cursor;
private LayoutInflater inflater;
private int username;
private int phoneNumber;

public ContactListCustomCursorAdapter(Context context, Cursor c) {
    super(context, c);
    this.context = context;
    this.cursor = c;
    inflater = LayoutInflater.from(context);

    username = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView userName = (TextView)view.findViewById(R.id.userName);
    userName.setText(cursor.getString(username));

    TextView phoneNumber = (TextView)view.findViewById(R.id.userNumber);
    phoneNumber.setText(cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view = inflater.inflate(R.layout.custom_contact_list_item, parent, false);

    return view;
}

}
</code>```

I don't want to use the Contact Picker.

答:
I also got this error, after spending an couple of hours i got the answer.
There are CONSTANT COLUMN MISMATCH problem, the 'data1' or NUMBER is a constant belongs to Phone class.

The ContactsContract.Contacts.CONTENT_URI does not provide number, for that you have to mention the projection with query it will give you the result, with help of this you can get ._id, display_name.
But, if you want to get number from id then you have to something like this,

```<code>Cursor cursorPhone = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.Contacts._ID +" = " + item_ID,
                null,
                null);
</code>```

Thank you

Body:
I am trying to put Name and phone numbers from contacts to my customized listView with help of Custom CursorAdapter, But I am getting the following error

Exception

 11-07 17:53:39.619: ERROR/AndroidRuntime(628): FATAL EXCEPTION: main
 11-07 17:53:39.619: ERROR/AndroidRuntime(628): java.lang.IllegalArgumentException: column      'data1' does not exist
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:99)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at org.com.apis.ContactListCustomCursorAdapter.bindView(ContactListCustomCursorAdapter.java:37)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.CursorAdapter.getView(CursorAdapter.java:186)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.AbsListView.obtainView(AbsListView.java:1315)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.ListView.onMeasure(ListView.java:1109)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.View.measure(View.java:8171)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.os.Handler.dispatchMessage(Handler.java:99)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.os.Looper.loop(Looper.java:123)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at android.app.ActivityThread.main(ActivityThread.java:4627)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at java.lang.reflect.Method.invokeNative(Native Method)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at java.lang.reflect.Method.invoke(Method.java:521)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
 11-07 17:53:39.619: ERROR/AndroidRuntime(628):     at dalvik.system.NativeStart.main(Native Method)

Here is the Code I am using

Main Activity Code

 public class ManipulationActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.contacts_list_layout);

    Cursor cursor = getCursor();

    ListView contactList = (ListView)findViewById(R.id.contactList);
    contactList.setAdapter(new ContactListCustomCursorAdapter(this, cursor)); //ContactListCustomCursorAdapter is a customized CursorAdapter. I have put the code below this class

}

    //Get Cursor pointing Contacts
private Cursor getCursor() {

    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
    while (cursor.moveToNext()) {
       String contactId = cursor.getString(cursor.getColumnIndex(
       ContactsContract.Contacts._ID));
       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
       if (Boolean.parseBoolean(hasPhone)) {
          // You know it has a number so now query it like this
          Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
          while (phones.moveToNext()) {
             String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
          }
       phones.close();
       }
    }
    cursor.close();
    return cursor;
}

}

ContactListCustomCursorAdapter Code

public class ContactListCustomCursorAdapter extends CursorAdapter {

private Context context;
private Cursor cursor;
private LayoutInflater inflater;
private int username;
private int phoneNumber;

public ContactListCustomCursorAdapter(Context context, Cursor c) {
    super(context, c);
    this.context = context;
    this.cursor = c;
    inflater = LayoutInflater.from(context);

    username = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView userName = (TextView)view.findViewById(R.id.userName);
    userName.setText(cursor.getString(username));

    TextView phoneNumber = (TextView)view.findViewById(R.id.userNumber);
    phoneNumber.setText(cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view = inflater.inflate(R.layout.custom_contact_list_item, parent, false);

    return view;
}

}

I don't want to use the Contact Picker.

Body:
I also got this error, after spending an couple of hours i got the answer.
There are CONSTANT COLUMN MISMATCH problem, the 'data1' or NUMBER is a constant belongs to Phone class.

The ContactsContract.Contacts.CONTENT_URI does not provide number, for that you have to mention the projection with query it will give you the result, with help of this you can get ._id, display_name.
But, if you want to get number from id then you have to something like this,

Cursor cursorPhone = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.Contacts._ID +" = " + item_ID,
                null,
                null);

Thank you


问:
How to merge two models in tensorflow?
I am working on face recognition using tensorflow.
I have a graph that I am using to train two different model and each model have 10 classes.
Now my question is, can I create a single model of 20 classes with the help of these two models.
Please respond to this question. If you want more information, let me know.
Thanks in advance.</p>

答:
I don't recommend you to merge two graphs mainly because paramater trained with 20 categories are quite different from the merged one with each 10 categories, but if you still want to do it, here is some advice

first import you graph with meta_graph_def or graph_def

second extract "bottleneck" tensor in the graph, you can do it with bottleneck = graph.get_tensor_by_name("your_tensor_name")

third read your pretrained values from disk(checkpoint), the class tf.train.NewCheckpointReader can be help

last step, build a constant tensor upon bottleneck tensor with values read from the third step.

Title: How to merge two models in tensorflow?


问:
how to receive large data from a broadcast server using python sockets
I need to receive real time data from a broadcast server and when doing so,  some parts of the data is missing while processing it. Here is the code which I've tried:

```<code>import socket
import sys
from pymongo import MongoClient

def process():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Connect the socket
    server_address = ('ip', port)
    print('connecting to %s port %s' % server_address)
    sock.connect(server_address)

    try:
        # Look for the response

        while True:
              data = sock.recv(16384000)
              #print(data)
              if not data:
                 pass
              else:
                  print data
    except socket.error, ex:
        print('closing socket')
        sock.close()
        time.sleep(1)
        process()
        #def fun(data):
        #print data[0]
</code>```

I do not understand how to verify if I've received the complete data without any data loss. Please help me to solve this issue. I am very new to python socket programming.

答:
The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested. If you want to make sure you receive exactly 16384000 bytes of data, you have to implement it yourself. TCP doesn't preserve message boundaries. So you actually want something like this:

```<code>def recvall(sock, length):
    data = b''
    while length:
        recved = sock.recv(length)
        data += recved
        length -= len(recved)
    return data
</code>```

Please note that this code hasn't been tested; it is also not an option for nonblocking sockets.

Body:
I need to receive real time data from a broadcast server and when doing so,  some parts of the data is missing while processing it. Here is the code which I've tried:

import socket
import sys
from pymongo import MongoClient

def process():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Connect the socket
    server_address = ('ip', port)
    print('connecting to %s port %s' % server_address)
    sock.connect(server_address)

    try:
        # Look for the response

        while True:
              data = sock.recv(16384000)
              #print(data)
              if not data:
                 pass
              else:
                  print data
    except socket.error, ex:
        print('closing socket')
        sock.close()
        time.sleep(1)
        process()
        #def fun(data):
        #print data[0]

I do not understand how to verify if I've received the complete data without any data loss. Please help me to solve this issue. I am very new to python socket programming.

Body:
The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested. If you want to make sure you receive exactly 16384000 bytes of data, you have to implement it yourself. TCP doesn't preserve message boundaries. So you actually want something like this:

def recvall(sock, length):
    data = b''
    while length:
        recved = sock.recv(length)
        data += recved
        length -= len(recved)
    return data

Please note that this code hasn't been tested; it is also not an option for nonblocking sockets.