问:
hibernate loading very long ( i think hibernate load all items)
i want to pagination and sorting the movies. but the loading very long.
if they show 5 or 100 movies all the same time to load. any one have an idea to do it faster ?
i have more then 100k entries in the DB.

```<code>@RequestMapping( value = "/movies/page/{pageNumber}", method = org.springframework.web.bind.annotation.RequestMethod.GET )
    public String showPagedMoviePage( HttpServletRequest request, @PathVariable Integer pageNumber, Model model,
                                      @RequestHeader( value = "X-Requested-With", required = false ) String requestedWith ) {
        PagedListHolder<?> pagedListHolder = (PagedListHolder<?>) request.getSession().getAttribute( "movie" );

        int MOVIE_LIST_PAGE_SIZE = 10;

        List<Movie> movies = movieDao.getMovies();

        if ( pagedListHolder == null ) {
            pagedListHolder = new PagedListHolder<>( movies );
            pagedListHolder.setPageSize( MOVIE_LIST_PAGE_SIZE );
        }
        else {
            final int goToPage = pageNumber - 1;
            if ( goToPage <= pagedListHolder.getPageCount() && goToPage >= 0 ) {
                pagedListHolder.setPage( goToPage );
            }
        }

        request.getSession().setAttribute( "movie", pagedListHolder );

        pagedListHolder.setSort( new MutableSortDefinition( "release_date", true, false ) );
        pagedListHolder.resort();

        int current = pagedListHolder.getPage() + 1;
        int begin = Math.max( 1, current - MOVIE_LIST_PAGE_SIZE );
        int end = Math.min( begin + 5, pagedListHolder.getPageCount() );
        int totalPageCount = pagedListHolder.getPageCount();
        String baseUrl = "/movies/page/";

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = userDao.findOneByUsername( auth.getName() );

        List<UserMovie> UserWatched = currentUser.getUserMovies();

        List<Movie> movieUserWatched = new ArrayList<Movie>();

        for ( UserMovie u : UserWatched ) {
            movieUserWatched.add( u.getMovie() );
        }

        String genreName = "";
        for ( Movie s : movieDao.findAll() ) {
            for ( Genres g : s.getGenres() ) {
                genreName += "" + g.getName() + ", ";
            }
        }
        genreName = genreName.substring( 0, genreName.length() - 1 );

        model.addAttribute( "genre", genreName );
        model.addAttribute( "movieUserWatched", movieUserWatched );

        model.addAttribute( "beginIndex", begin );
        model.addAttribute( "endIndex", end );
        model.addAttribute( "currentIndex", current );
        model.addAttribute( "totalPageCount", totalPageCount );
        model.addAttribute( "baseUrl", baseUrl );
        model.addAttribute( "movies", pagedListHolder );

        return "/home/movies";
    }
</code>```

the MovieDao() class:
 @Service
    public class MovieDao
        extends CrudDao {

```<code>    @Autowired
    public MovieDao( MovieRepository repository ) {
        super( repository );
    }

    @Override
    public boolean validateOnSaveOrUpdate( Optional<Movie> oldEntity, Movie entity, Errors errors ) {
        if ( entity == null ) {
            return false;
        }

        if ( Strings.isNullOrEmpty( entity.getTitle() ) ) {
            errors.rejectValue( "movie", "movie.messages.movie_empty" );
            return false;
        }

        // Movie are used?
        Movie tmpMovie = findOneByTitle( entity.getTitle() );
        if ( tmpMovie != null && !tmpMovie.getId().equals( entity.getId() ) ) {
            // errors.rejectValue( "movie", "movie.messages.id_already_exists", new Object[] { entity.getTitle() }, null
            // );
            return false;
        }

        return true;
    }

    @Override
    public boolean validateOnDelete( Movie entity, Errors errors ) {
        if ( entity != null ) {
            return true;
        }
        return false;
    }

    public Movie findOneByTitle( String title ) {
        return repository.findOneByTitle( title );
    }

    public Iterable<Movie> findAll() {
        return repository.findAll();
    }

    public ArrayList<Movie> getMovies() {
        Iterable<Movie> source = repository.findAll();
        ArrayList<Movie> target = new ArrayList<Movie>();
        source.forEach( target::add );
        return target;
    }

}
</code>```

Movie model:

    @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" )
    @Entity
    public class Movie
        extends AuditedEntity
        implements com.miyava.common.Entity {

```<code>    @Column( name = "movie_id" )
    @Id
    @GeneratedValue( strategy = GenerationType.AUTO )
    @JsonView( DataTablesOutput.View.class )
    private Long id;

    @Column( name = "theMovieDbId" )
    private Long theMovieDbId;

    @NotEmpty( message = "movie.messages.title_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String title;

    @NotEmpty( message = "movie.messages.description_empty" )
    @Column( nullable = false, unique = false )
    @Lob
    @JsonView( DataTablesOutput.View.class )
    private String overview;

    @Column( nullable = true, unique = false )
    @JsonView( DataTablesOutput.View.class )
    private String short_Overview;

    @NotEmpty( message = "movie.messages.poster_Path_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String poster_path;

    @NotEmpty( message = "movie.messages.runtime_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String runtime;

    @NotEmpty( message = "movie.messages.status_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String status;

    @Column( unique = false, columnDefinition = "DATETIME", name = "release_date" )
    @JsonView( DataTablesOutput.View.class )
    private Date release_date;

    @ManyToMany( cascade = CascadeType.ALL, targetEntity = Genres.class )
    @JoinTable( name = "movie_genres", joinColumns = @JoinColumn( name = "movie_id", referencedColumnName = "movie_id" ), inverseJoinColumns = @JoinColumn( name = "genres_id", referencedColumnName = "genres_id" ) )
    @JsonView( DataTablesOutput.View.class )
    private List<Genres> genres;

    @OneToMany( mappedBy = "movie" )
    private List<UserMovie> userMovie = new ArrayList<UserMovie>();

    public Movie() {}

    public Movie( String title, String overview, String short_Overview, String status, Date release_date, List<Genres> genres ) {
        super();
        this.title = title;
        this.overview = overview;
        this.short_Overview = short_Overview;
        this.status = status;
        this.release_date = release_date;
        this.genres = genres;
    }

    public Long getId() {
        return id;
    }

    public void setId( Long id ) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle( String title ) {
        this.title = title;
    }

    public String getOverview() {
        return overview;
    }

    public void setOverview( String overview ) {
        this.overview = overview;
    }

    public String getPoster_path() {
        return poster_path;
    }

    public void setPoster_path( String poster_path ) {
        this.poster_path = poster_path;
    }

    public String getRuntime() {
        return runtime;
    }

    public void setRuntime( String runtime ) {
        this.runtime = runtime;
    }

    public String getStatus() {
        return status;
    }

    public Long getTheMovieDbId() {
        return theMovieDbId;
    }

    public void setTheMovieDbId( Long theMovieDbId ) {
        this.theMovieDbId = theMovieDbId;
    }

    public String getShort_Overview() {
        return short_Overview;
    }

    public void setShort_Overview( String short_Overview ) {
        this.short_Overview = short_Overview;
    }

    public void setStatus( String status ) {
        this.status = status;
    }

    public Date getRelease_date() {
        return release_date;
    }

    public void setRelease_date( Date release_date ) {
        this.release_date = release_date;
    }

    public List<Genres> getGenres() {
        return genres;
    }

    public void setGenres( List<Genres> genres ) {
        this.genres = genres;
    }

    public List<UserMovie> getUserMovie() {
        return userMovie;
    }

    public void setUserMovie( List<UserMovie> userMovie ) {
        this.userMovie = userMovie;
    }
}
</code>```

Hibernate queries:here

MovieDao

```<code>package com.miyava.movie.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.*;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.miyava.common.CrudDao;
import com.miyava.movie.model.Movie;
import com.miyava.movie.repository.MovieRepository;

@Service
public class MovieDao
    extends CrudDao<Movie, Long, MovieRepository> {

    @Autowired
    public MovieDao( MovieRepository repository ) {
        super( repository );
    }

    @Override
    public boolean validateOnSaveOrUpdate( Optional<Movie> oldEntity, Movie entity, Errors errors ) {
        if ( entity == null ) {
            return false;
        }

        if ( Strings.isNullOrEmpty( entity.getTitle() ) ) {
            errors.rejectValue( "movie", "movie.messages.movie_empty" );
            return false;
        }

        // Movie are used?
        Movie tmpMovie = findOneByTitle( entity.getTitle() );
        if ( tmpMovie != null && !tmpMovie.getId().equals( entity.getId() ) ) {
            // errors.rejectValue( "movie", "movie.messages.id_already_exists", new Object[] { entity.getTitle() }, null
            // );
            return false;
        }

        return true;
    }

    @Override
    public boolean validateOnDelete( Movie entity, Errors errors ) {
        if ( entity != null ) {
            return true;
        }
        return false;
    }

    public Movie findOneByTitle( String title ) {
        return repository.findOneByTitle( title );
    }

    public Iterable<Movie> findAll() {
        return repository.findAll();
    }

    public ArrayList<Movie> getMovies() {
        Iterable<Movie> source = repository.findAll();
        ArrayList<Movie> target = new ArrayList<Movie>();
        source.forEach( target::add );
        return target;
    }

    private <E> List<E> findListPage( final String hql, final int offset,
                                      final int limit, final Object... args ) {
        return (List<E>) getHibernateTemplate().execute( new HibernateCallback() {
            public Object doInHibernate( Session session )
                throws HibernateException,
                SQLException {
                Query query = createQueryAndPopulateParameters( session, hql,
                    args );
                if ( offset >= 0 ) {
                    query.setFirstResult( offset );
                }
                if ( limit >= 0 ) {
                    query.setMaxResults( limit );
                }
                return query.list();
            }
        } );
    }

    private Query createQueryAndPopulateParameters( Session session,
                                                    final String hql, final Object... args ) {
        Query query = session.createQuery( hql );
        for ( int i = 0; i < args.length; i++ ) {
            query.setParameter( i, args[i] );
        }
        return query;
    }

    public List<Movie> listMoviesPaged( int offset, int limit ) {
        return findListPage( "from Movie m order by m.id", offset, limit );
    }

}
</code>```

MovieRepository:

```<code>    package com.miyava.movie.repository;

import org.springframework.data.jpa.datatables.repository.DataTablesRepository;

import com.miyava.movie.model.Movie;

public interface MovieRepository
    extends DataTablesRepository<Movie, Long> {

    Movie findOneByTitle( String title );
}
</code>```

答:
Yes, you are right, your code fetches all the Movie records from database and only then applies paging to them. This is far from optimal if you have at least thousands of records (as in your case).

A standard way to solve this is to pass page number (or offset/limit pair) to your code that makes a query to the database.

You did not provide full code (MovieRepository, which seems to actually execute a Hibernate Query, is missing), so I will give you an abstract example.

```<code>private <E> List<E> findListPage(final String hql, final int offset,
        final int limit, final Object... args) {
    return (List<E>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException,
                SQLException {
            Query query = createQueryAndPopulateParameters(session, hql,
                    args);
            if (offset >= 0) {
                query.setFirstResult(offset);
            }
            if (limit >= 0) {
                query.setMaxResults(limit);
            }
            return query.list();
        }
    });
}

private Query createQueryAndPopulateParameters(Session session,
        final String hql, final Object... args) {
    Query query = session.createQuery(hql);
    for (int i = 0; i < args.length; i++) {
        query.setParameter(i, args[i]);
    }
    return query;
}

public List<Movie> listMoviesPaged(int offset, int limit) {
    return findListPage("from Movie m order by m.id", offset, limit);
}
</code>```

The idea is that we set offset and limit on Hibernate's Query instance and allowing the database to make that paging work instead of fetch all 100k records into memory and throwing most of them away.

Of course, when having an order by clause, you need to make sure that there is an index on column(s) by which you sort, otherwise the performance will be killed.

Update

Now that we have more code we can find some concrete solution. You use DataTablesRepository which extends PagingAndSortingRepository https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html which has findAll(Pageable) method. This seems to be what is needed here.

Try replacing

```<code>public Iterable<Movie> findAll() {
    return repository.findAll();
}
</code>```

with

```<code>public Iterable<Movie> findAll(int pageNumber, int pageSize) {
    return repository.findAll(new PageRequest(pageNumber, pageSize));
}
</code>```

in your MovieDao (and remove the methods I shown you as an abstract example earlier).

Then pass pageNumber and pageSize to your MovieDao#findAll(int, int) method.

Body:
i want to pagination and sorting the movies. but the loading very long.
if they show 5 or 100 movies all the same time to load. any one have an idea to do it faster ?
i have more then 100k entries in the DB.

@RequestMapping( value = "/movies/page/{pageNumber}", method = org.springframework.web.bind.annotation.RequestMethod.GET )
    public String showPagedMoviePage( HttpServletRequest request, @PathVariable Integer pageNumber, Model model,
                                      @RequestHeader( value = "X-Requested-With", required = false ) String requestedWith ) {
        PagedListHolder<?> pagedListHolder = (PagedListHolder<?>) request.getSession().getAttribute( "movie" );

        int MOVIE_LIST_PAGE_SIZE = 10;

        List<Movie> movies = movieDao.getMovies();

        if ( pagedListHolder == null ) {
            pagedListHolder = new PagedListHolder<>( movies );
            pagedListHolder.setPageSize( MOVIE_LIST_PAGE_SIZE );
        }
        else {
            final int goToPage = pageNumber - 1;
            if ( goToPage <= pagedListHolder.getPageCount() && goToPage >= 0 ) {
                pagedListHolder.setPage( goToPage );
            }
        }

        request.getSession().setAttribute( "movie", pagedListHolder );

        pagedListHolder.setSort( new MutableSortDefinition( "release_date", true, false ) );
        pagedListHolder.resort();

        int current = pagedListHolder.getPage() + 1;
        int begin = Math.max( 1, current - MOVIE_LIST_PAGE_SIZE );
        int end = Math.min( begin + 5, pagedListHolder.getPageCount() );
        int totalPageCount = pagedListHolder.getPageCount();
        String baseUrl = "/movies/page/";

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = userDao.findOneByUsername( auth.getName() );

        List<UserMovie> UserWatched = currentUser.getUserMovies();

        List<Movie> movieUserWatched = new ArrayList<Movie>();

        for ( UserMovie u : UserWatched ) {
            movieUserWatched.add( u.getMovie() );
        }

        String genreName = "";
        for ( Movie s : movieDao.findAll() ) {
            for ( Genres g : s.getGenres() ) {
                genreName += "" + g.getName() + ", ";
            }
        }
        genreName = genreName.substring( 0, genreName.length() - 1 );

        model.addAttribute( "genre", genreName );
        model.addAttribute( "movieUserWatched", movieUserWatched );

        model.addAttribute( "beginIndex", begin );
        model.addAttribute( "endIndex", end );
        model.addAttribute( "currentIndex", current );
        model.addAttribute( "totalPageCount", totalPageCount );
        model.addAttribute( "baseUrl", baseUrl );
        model.addAttribute( "movies", pagedListHolder );

        return "/home/movies";
    }

the MovieDao() class:
 @Service
    public class MovieDao
        extends CrudDao {

    @Autowired
    public MovieDao( MovieRepository repository ) {
        super( repository );
    }

    @Override
    public boolean validateOnSaveOrUpdate( Optional<Movie> oldEntity, Movie entity, Errors errors ) {
        if ( entity == null ) {
            return false;
        }

        if ( Strings.isNullOrEmpty( entity.getTitle() ) ) {
            errors.rejectValue( "movie", "movie.messages.movie_empty" );
            return false;
        }

        // Movie are used?
        Movie tmpMovie = findOneByTitle( entity.getTitle() );
        if ( tmpMovie != null && !tmpMovie.getId().equals( entity.getId() ) ) {
            // errors.rejectValue( "movie", "movie.messages.id_already_exists", new Object[] { entity.getTitle() }, null
            // );
            return false;
        }

        return true;
    }

    @Override
    public boolean validateOnDelete( Movie entity, Errors errors ) {
        if ( entity != null ) {
            return true;
        }
        return false;
    }

    public Movie findOneByTitle( String title ) {
        return repository.findOneByTitle( title );
    }

    public Iterable<Movie> findAll() {
        return repository.findAll();
    }

    public ArrayList<Movie> getMovies() {
        Iterable<Movie> source = repository.findAll();
        ArrayList<Movie> target = new ArrayList<Movie>();
        source.forEach( target::add );
        return target;
    }

}

Movie model:

    @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" )
    @Entity
    public class Movie
        extends AuditedEntity
        implements com.miyava.common.Entity {

    @Column( name = "movie_id" )
    @Id
    @GeneratedValue( strategy = GenerationType.AUTO )
    @JsonView( DataTablesOutput.View.class )
    private Long id;

    @Column( name = "theMovieDbId" )
    private Long theMovieDbId;

    @NotEmpty( message = "movie.messages.title_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String title;

    @NotEmpty( message = "movie.messages.description_empty" )
    @Column( nullable = false, unique = false )
    @Lob
    @JsonView( DataTablesOutput.View.class )
    private String overview;

    @Column( nullable = true, unique = false )
    @JsonView( DataTablesOutput.View.class )
    private String short_Overview;

    @NotEmpty( message = "movie.messages.poster_Path_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String poster_path;

    @NotEmpty( message = "movie.messages.runtime_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String runtime;

    @NotEmpty( message = "movie.messages.status_empty" )
    @Column( nullable = false, unique = false, length = 255 )
    @Length( max = 255, message = "common.message.data_to_long" )
    @JsonView( DataTablesOutput.View.class )
    private String status;

    @Column( unique = false, columnDefinition = "DATETIME", name = "release_date" )
    @JsonView( DataTablesOutput.View.class )
    private Date release_date;

    @ManyToMany( cascade = CascadeType.ALL, targetEntity = Genres.class )
    @JoinTable( name = "movie_genres", joinColumns = @JoinColumn( name = "movie_id", referencedColumnName = "movie_id" ), inverseJoinColumns = @JoinColumn( name = "genres_id", referencedColumnName = "genres_id" ) )
    @JsonView( DataTablesOutput.View.class )
    private List<Genres> genres;

    @OneToMany( mappedBy = "movie" )
    private List<UserMovie> userMovie = new ArrayList<UserMovie>();

    public Movie() {}

    public Movie( String title, String overview, String short_Overview, String status, Date release_date, List<Genres> genres ) {
        super();
        this.title = title;
        this.overview = overview;
        this.short_Overview = short_Overview;
        this.status = status;
        this.release_date = release_date;
        this.genres = genres;
    }

    public Long getId() {
        return id;
    }

    public void setId( Long id ) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle( String title ) {
        this.title = title;
    }

    public String getOverview() {
        return overview;
    }

    public void setOverview( String overview ) {
        this.overview = overview;
    }

    public String getPoster_path() {
        return poster_path;
    }

    public void setPoster_path( String poster_path ) {
        this.poster_path = poster_path;
    }

    public String getRuntime() {
        return runtime;
    }

    public void setRuntime( String runtime ) {
        this.runtime = runtime;
    }

    public String getStatus() {
        return status;
    }

    public Long getTheMovieDbId() {
        return theMovieDbId;
    }

    public void setTheMovieDbId( Long theMovieDbId ) {
        this.theMovieDbId = theMovieDbId;
    }

    public String getShort_Overview() {
        return short_Overview;
    }

    public void setShort_Overview( String short_Overview ) {
        this.short_Overview = short_Overview;
    }

    public void setStatus( String status ) {
        this.status = status;
    }

    public Date getRelease_date() {
        return release_date;
    }

    public void setRelease_date( Date release_date ) {
        this.release_date = release_date;
    }

    public List<Genres> getGenres() {
        return genres;
    }

    public void setGenres( List<Genres> genres ) {
        this.genres = genres;
    }

    public List<UserMovie> getUserMovie() {
        return userMovie;
    }

    public void setUserMovie( List<UserMovie> userMovie ) {
        this.userMovie = userMovie;
    }
}

Hibernate queries:here

MovieDao

package com.miyava.movie.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.*;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.miyava.common.CrudDao;
import com.miyava.movie.model.Movie;
import com.miyava.movie.repository.MovieRepository;

@Service
public class MovieDao
    extends CrudDao<Movie, Long, MovieRepository> {

    @Autowired
    public MovieDao( MovieRepository repository ) {
        super( repository );
    }

    @Override
    public boolean validateOnSaveOrUpdate( Optional<Movie> oldEntity, Movie entity, Errors errors ) {
        if ( entity == null ) {
            return false;
        }

        if ( Strings.isNullOrEmpty( entity.getTitle() ) ) {
            errors.rejectValue( "movie", "movie.messages.movie_empty" );
            return false;
        }

        // Movie are used?
        Movie tmpMovie = findOneByTitle( entity.getTitle() );
        if ( tmpMovie != null && !tmpMovie.getId().equals( entity.getId() ) ) {
            // errors.rejectValue( "movie", "movie.messages.id_already_exists", new Object[] { entity.getTitle() }, null
            // );
            return false;
        }

        return true;
    }

    @Override
    public boolean validateOnDelete( Movie entity, Errors errors ) {
        if ( entity != null ) {
            return true;
        }
        return false;
    }

    public Movie findOneByTitle( String title ) {
        return repository.findOneByTitle( title );
    }

    public Iterable<Movie> findAll() {
        return repository.findAll();
    }

    public ArrayList<Movie> getMovies() {
        Iterable<Movie> source = repository.findAll();
        ArrayList<Movie> target = new ArrayList<Movie>();
        source.forEach( target::add );
        return target;
    }

    private <E> List<E> findListPage( final String hql, final int offset,
                                      final int limit, final Object... args ) {
        return (List<E>) getHibernateTemplate().execute( new HibernateCallback() {
            public Object doInHibernate( Session session )
                throws HibernateException,
                SQLException {
                Query query = createQueryAndPopulateParameters( session, hql,
                    args );
                if ( offset >= 0 ) {
                    query.setFirstResult( offset );
                }
                if ( limit >= 0 ) {
                    query.setMaxResults( limit );
                }
                return query.list();
            }
        } );
    }

    private Query createQueryAndPopulateParameters( Session session,
                                                    final String hql, final Object... args ) {
        Query query = session.createQuery( hql );
        for ( int i = 0; i < args.length; i++ ) {
            query.setParameter( i, args[i] );
        }
        return query;
    }

    public List<Movie> listMoviesPaged( int offset, int limit ) {
        return findListPage( "from Movie m order by m.id", offset, limit );
    }

}

MovieRepository:

    package com.miyava.movie.repository;

import org.springframework.data.jpa.datatables.repository.DataTablesRepository;

import com.miyava.movie.model.Movie;

public interface MovieRepository
    extends DataTablesRepository<Movie, Long> {

    Movie findOneByTitle( String title );
}

Body:
Yes, you are right, your code fetches all the Movie records from database and only then applies paging to them. This is far from optimal if you have at least thousands of records (as in your case).

A standard way to solve this is to pass page number (or offset/limit pair) to your code that makes a query to the database.

You did not provide full code (MovieRepository, which seems to actually execute a Hibernate Query, is missing), so I will give you an abstract example.

private <E> List<E> findListPage(final String hql, final int offset,
        final int limit, final Object... args) {
    return (List<E>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException,
                SQLException {
            Query query = createQueryAndPopulateParameters(session, hql,
                    args);
            if (offset >= 0) {
                query.setFirstResult(offset);
            }
            if (limit >= 0) {
                query.setMaxResults(limit);
            }
            return query.list();
        }
    });
}

private Query createQueryAndPopulateParameters(Session session,
        final String hql, final Object... args) {
    Query query = session.createQuery(hql);
    for (int i = 0; i < args.length; i++) {
        query.setParameter(i, args[i]);
    }
    return query;
}

public List<Movie> listMoviesPaged(int offset, int limit) {
    return findListPage("from Movie m order by m.id", offset, limit);
}

The idea is that we set offset and limit on Hibernate's Query instance and allowing the database to make that paging work instead of fetch all 100k records into memory and throwing most of them away.

Of course, when having an order by clause, you need to make sure that there is an index on column(s) by which you sort, otherwise the performance will be killed.

Update

Now that we have more code we can find some concrete solution. You use DataTablesRepository which extends PagingAndSortingRepository https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html which has findAll(Pageable) method. This seems to be what is needed here.

Try replacing

public Iterable<Movie> findAll() {
    return repository.findAll();
}

with

public Iterable<Movie> findAll(int pageNumber, int pageSize) {
    return repository.findAll(new PageRequest(pageNumber, pageSize));
}

in your MovieDao (and remove the methods I shown you as an abstract example earlier).

Then pass pageNumber and pageSize to your MovieDao#findAll(int, int) method.


来源: stackexchange

问:
Connection Time Out in Android
There are several ways of making HTTP call using Android application. If any one wants to bring a image from http server he/she could use one method to bring the image. On the other hand if a person wants to read JSON or XML for http server response he could use another way to do that. Above two scenarios are just the examples other scenarios might occur. My question is that Is there any standard way through which I can keep check of HttpConnection Timeout. In a particular scenario you can have WIFI or GPRS Connection avaialable but because of its high turnaround time, user experience of my application is getting hampered. How can I keep a check on this issue.

Thanks

Below is code example

```<code>public boolean readAndSaveFileFromWeb(String url) {
    byte[] fileRead = null;
    FileOutputStream fos;
    try {
        InputStream is = (InputStream) this.fetch(url);
        if(is!=null){
            fileRead = readBytes(is);
        }else{
            return false;
        }
    } catch (MalformedURLException e) {
        Log.v(TAG, "readAndSaveFileFromWeb Exception: Malformed URL "
                + e.getMessage());
        return false;
    } catch (IOException e) {
        Log.v(TAG, " readAndSaveFileFromWeb Exception:   IOException"
                + e.getMessage());
        return false;
    } catch (Exception e) {
        Log.v(TAG, " readAndSaveFileFromWeb Exception: " + e.getClass());
        return false;
    }
}

public Object fetch(String address) throws MalformedURLException,
        IOException {
    URL url = new URL(address);
    Object content = url.getContent();

    return content;
}
</code>```

Now the above code gets the content / response from the address url. In a particular scenario WIFI or GPRS connection is available but the time taken to get data is more if the connection is slow. During this delay .. the application looks hanged though I 'm performing network intensive tasks in different thread than UI thread. This is hampering  user experience a bit.

答: Make a check for Network connection before executing your HTTP request or catch the time out exception</p>

ContentLicense: CC BY-SA 2.5

Title: Connection Time Out in Android

Body:
There are several ways of making HTTP call using Android application. If any one wants to bring a image from http server he/she could use one method to bring the image. On the other hand if a person wants to read JSON or XML for http server response he could use another way to do that. Above two scenarios are just the examples other scenarios might occur. My question is that Is there any standard way through which I can keep check of HttpConnection Timeout. In a particular scenario you can have WIFI or GPRS Connection avaialable but because of its high turnaround time, user experience of my application is getting hampered. How can I keep a check on this issue.

Thanks

Below is code example

public boolean readAndSaveFileFromWeb(String url) {
    byte[] fileRead = null;
    FileOutputStream fos;
    try {
        InputStream is = (InputStream) this.fetch(url);
        if(is!=null){
            fileRead = readBytes(is);
        }else{
            return false;
        }
    } catch (MalformedURLException e) {
        Log.v(TAG, "readAndSaveFileFromWeb Exception: Malformed URL "
                + e.getMessage());
        return false;
    } catch (IOException e) {
        Log.v(TAG, " readAndSaveFileFromWeb Exception:   IOException"
                + e.getMessage());
        return false;
    } catch (Exception e) {
        Log.v(TAG, " readAndSaveFileFromWeb Exception: " + e.getClass());
        return false;
    }
}

public Object fetch(String address) throws MalformedURLException,
        IOException {
    URL url = new URL(address);
    Object content = url.getContent();

    return content;
}

Now the above code gets the content / response from the address url. In a particular scenario WIFI or GPRS connection is available but the time taken to get data is more if the connection is slow. During this delay .. the application looks hanged though I 'm performing network intensive tasks in different thread than UI thread. This is hampering  user experience a bit.


问:
ASP MVC - many request at one Ajax.BeginForm click
I have question about requests - their count.
Im using Ajax.BeginForm and onSuccess option.
But when I click that form my JS handler for OnSuccess option fires up many times.
I looked up for my request and its looks like this:
Image with number of request

So my question is: why if I click on AjaxForm it makes many request?
Thanks

View with Ajax action link:

```<code>@foreach (var item in Model)
{
    if (item.Accepted == false)
    {
        <text>
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Accepted)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.IsOrganizer)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.PlayerRating)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstName)
                </td>

                <td>
                    @Ajax.ActionLink("Akceptuj", // <-- Text to display
                     "AcceptPlayer", // <-- Action Method Name
                     new { id = item.PlayerId },
                     new AjaxOptions
                     {
                         HttpMethod = "POST",

                     })
                </td>
            </tr>
        </text>
    }
}
</code>```

Controller action:

```<code>[Authorize]
public ActionResult AcceptPlayer(long id)
{
    using (var Players = new DbMigrationExample2Entities())
    {
        Player playerToAccept = Players.Player.Find(id);
        if (playerToAccept == null)
        {
            return HttpNotFound();
        }
        playerToAccept.Accepted = true;
        Players.SaveChanges(); return View();
    }
</code>```

答:
If you have included jquery.unobtrusive-ajax.min.js twice once in the layout once in the partial. So your browser executes the js inside twice which will subscribe twice on the form click event that is why doing two POST instead of one.
So you need to remove the jquery.unobtrusive-ajax.min.js from the partial.

Note: If your are using a partial with a layout you don't need to duplicate the js included in the partial because it's already done by the layout. There are some good articles about layouts and partials.

Second think if problem persist then the solution here :
First ajax request is sent multiple times

If nigher this all solution is not working in your case then definitely you need to change your Ajax.ActionLink into Html.ActionLink  Like :

@Html.ActionLink(article.Title, new { controller = "Akceptuj", action = "AcceptPlayer", id = item.PlayerId }, new AjaxOptions { HttpMethod = "POST" })
```

Cheers !!

ContentLicense: CC BY-SA 3.0

Body:
I have question about requests - their count.
Im using Ajax.BeginForm and onSuccess option.
But when I click that form my JS handler for OnSuccess option fires up many times.
I looked up for my request and its looks like this:
Image with number of request

So my question is: why if I click on AjaxForm it makes many request?
Thanks

View with Ajax action link:

@foreach (var item in Model)
{
    if (item.Accepted == false)
    {
        <text>

                    @Html.DisplayFor(modelItem => item.Accepted)

                    @Html.DisplayFor(modelItem => item.IsOrganizer)

                    @Html.DisplayFor(modelItem => item.PlayerRating)

                    @Html.DisplayFor(modelItem => item.FirstName)

                    @Ajax.ActionLink("Akceptuj", // <-- Text to display
                     "AcceptPlayer", // <-- Action Method Name
                     new { id = item.PlayerId },
                     new AjaxOptions
                     {
                         HttpMethod = "POST",

                     })

        </text>
    }
}

Controller action:

[Authorize]
public ActionResult AcceptPlayer(long id)
{
    using (var Players = new DbMigrationExample2Entities())
    {
        Player playerToAccept = Players.Player.Find(id);
        if (playerToAccept == null)
        {
            return HttpNotFound();
        }
        playerToAccept.Accepted = true;
        Players.SaveChanges(); return View();
    }

Body:
If you have included jquery.unobtrusive-ajax.min.js twice once in the layout once in the partial. So your browser executes the js inside twice which will subscribe twice on the form click event that is why doing two POST instead of one.
So you need to remove the jquery.unobtrusive-ajax.min.js from the partial.

Note: If your are using a partial with a layout you don't need to duplicate the js included in the partial because it's already done by the layout. There are some good articles about layouts and partials.

Second think if problem persist then the solution here :
First ajax request is sent multiple times

If nigher this all solution is not working in your case then definitely you need to change your Ajax.ActionLink into Html.ActionLink  Like :

@Html.ActionLink(article.Title, new { controller = "Akceptuj", action = "AcceptPlayer", id = item.PlayerId }, new AjaxOptions { HttpMethod = "POST" })

Cheers !!


问:
ManyToOne and OneToMany
I use Hibernate and I have entities:

```<code>@Data
@Entity
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "country_nm")
    private String countryName;
}

@Data
@Entity
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "city_nm")
    private String cityName;
}
</code>```

Country can have many cities, city has only one country.
What is the best way to associate these entities?

1) add City city field in City class and add @ManyToOne and @JoinColumn anotations above it? As a result we will have two tables: country and city, city table will have country_id column.

2) add Country country field in Country class and @OneToMany(mappedBy='country')above it and add City city field in City class and add @ManyToOne anotations above it? In this case there will be three tables: country, city and combining table country_city

答:
1) add City city field in City class and add @ManyToOne and
  @JoinColumn anotations above it? As a result we will have two tables:
  country and city, city table will have country_id column.

I suppose you mean  add Country country field in City class, yes this would be right about it if you are aiming for unidirectional relations,  but the joinColumn should not be in the owning entity, it should be in the none owning entity so you would have to go to the Country class and add a list of cities there and annotate them with @OneToMany with join column.

2) add Country country field in Country class and
  @OneToMany(mappedBy='country')above it and add City city field in City
  class and add @ManyToOne anotations above it? In this case there will
  be three tables: country, city and combining table country_city

there are many wrong things about this solution, first you cannot have "@oneToMany(mappedBy='country)" like this, you can use it only if you applied the first solution and you want to make the relation bidirectional and even though this will not generate a third class, if you want to generate a third class it you will need @JoinTable in your owning class instead of @JoinColumn

Title: ManyToOne and OneToMany

Body:
I use Hibernate and I have entities:

@Data
@Entity
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "country_nm")
    private String countryName;
}

@Data
@Entity
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "city_nm")
    private String cityName;
}

Country can have many cities, city has only one country.
What is the best way to associate these entities?

1) add City city field in City class and add @ManyToOne and @JoinColumn anotations above it? As a result we will have two tables: country and city, city table will have country_id column.

2) add Country country field in Country class and @OneToMany(mappedBy='country')above it and add City city field in City class and add @ManyToOne anotations above it? In this case there will be three tables: country, city and combining table country_city


问:
cakephp - create new directory inside webroot
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

```<code>$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}
</code>```

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

答:
```<code>$path = WWW_ROOT . 'webroot' . DS . 'FolderNameYouWantToSet' . DS;
                if (!file_exists($path)) {
                    $oldMask = umask(0);
                    mkdir($path, 0777, true);
                    chmod($path, 0777);
                    umask($oldMask);
                }
</code>```

This will create a folder with 777 permission, you can set the folder permission as per your requirement.

WWW_ROOT is the global cake variable which stores the path up to the project.

Body:
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

Body:
$path = WWW_ROOT . 'webroot' . DS . 'FolderNameYouWantToSet' . DS;
                if (!file_exists($path)) {
                    $oldMask = umask(0);
                    mkdir($path, 0777, true);
                    chmod($path, 0777);
                    umask($oldMask);
                }

This will create a folder with 777 permission, you can set the folder permission as per your requirement.

WWW_ROOT is the global cake variable which stores the path up to the project.


问:
ArrayList Database MySQL
Have very limited experience with databases and trying to figure out the best method for creating a growing database of users and keeping track of their growing information when added.

For instance, I have 3 users - Apple, Banana, Cherry. And they all have a list of information associated with them.

```<code>  Apple: [1/1/17, green, 3], [2/4/17, red, 5], [4/19/17, blue, 2]
  Banana: [2/18/17, yellow, 6], [5/14/17, yellow, 5]
  Cherry: [5/21/17, green, 12], [8/2/17, red, 5], [9/29/17, blue, 42],
  [1/1/17, green, 3]
</code>```

Before even getting into working with a growing list, how does this get applied to a database?

Do I create a main database, something like FruitDatabase, and then inside those databases have Apple, Banana, and Cherry as their own tables?

Or does each user get their own database and then their associated information get applied to their own table (that doesn't seem efficient)?

What if I later want to add up all of Apple's number (3+5+2), what's the best method of doing that? It doesn't seem like I can put an ArrayList into a database, do I just convert it into a string and separate the number with a comma? And if I want to add a new user, DragonFruit, is it more efficient to add it as a column or row?

答:
You can create tables like the following to represent your data.

```<code>create table fruit_type (
  fruit_type_id int,
  name varchar(20),
  color varchar(10),
  primary key(fruit_type_id)
);

create table fruits (
 fruit_id int,
 date_added date,
 count int,
 foreign key (fruit_id) references fruit_type(fruit_type_id)
)
</code>```

Before inserting data into fruits table, you need to have a row for each fruit type in fruit_type table.

Title: ArrayList Database MySQL

Body:
Have very limited experience with databases and trying to figure out the best method for creating a growing database of users and keeping track of their growing information when added.

For instance, I have 3 users - Apple, Banana, Cherry. And they all have a list of information associated with them.

  Apple: [1/1/17, green, 3], [2/4/17, red, 5], [4/19/17, blue, 2]
  Banana: [2/18/17, yellow, 6], [5/14/17, yellow, 5]
  Cherry: [5/21/17, green, 12], [8/2/17, red, 5], [9/29/17, blue, 42],
  [1/1/17, green, 3]

Before even getting into working with a growing list, how does this get applied to a database?

Do I create a main database, something like FruitDatabase, and then inside those databases have Apple, Banana, and Cherry as their own tables?

Or does each user get their own database and then their associated information get applied to their own table (that doesn't seem efficient)?

What if I later want to add up all of Apple's number (3+5+2), what's the best method of doing that? It doesn't seem like I can put an ArrayList into a database, do I just convert it into a string and separate the number with a comma? And if I want to add a new user, DragonFruit, is it more efficient to add it as a column or row?

Body:
You can create tables like the following to represent your data.

create table fruit_type (
  fruit_type_id int,
  name varchar(20),
  color varchar(10),
  primary key(fruit_type_id)
);

create table fruits (
 fruit_id int,
 date_added date,
 count int,
 foreign key (fruit_id) references fruit_type(fruit_type_id)
)

Before inserting data into fruits table, you need to have a row for each fruit type in fruit_type table.


问:
React code not compiling with webpack
My code wont compile for some reason. The weird thing is that is will work when I use the in browser interpreter.

```<code><script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
</code>```

React code:

```<code>var Cookies = require('cookies');

var cookieParser = require('cookie-parser');

var name = document.getElementById('name').innerHTML;
//var name = req.user.name;

  var start = false;
  var Assets = React.createClass({
    getInitialState: function(){
      return({
        assets: [],
        secondsElapsed: 0
      });
    },
    tick: function() {
      //this.setState({secondsElapsed: this.state.secondsElapsed + 1});
      if(start === true){
        console.log(name);

        var myHeaders = new Headers();

        var token = new Cookies(req,res).get('access_token');

        myHeaders.append('acess_token', token);

        var myInit = { method: 'GET',
               headers: myHeaders};

        fetch('/api/user/all/?name='+name, myInit).then(function(data){
          return data.json();
        }).then( json => {
          this.setState({
              assets: json
            });
        });
    }
    },
    componentDidMount: function() {
      this.interval = setInterval(this.tick, 1000);
    },
    componentWillUnmount: function() {
      clearInterval(this.interval);
    },
    render: function(){
      var assets = this.state.assets;
      assets = assets.map(function(asseti,index){
        return(
          asseti.map(function(asset, index){
            return(
              <li key={index}>
                        <span className={asset.active}></span>
                        <span>{asset.name}</span>
                        <span >{asset.description}</span>
                        <span>{asset.location.coordinates[0]}{asset.location.coordinates[1]}</span>
              </li>
            )
          })
        )
      });
      return(
        <div>
          <form onSubmit={this.handleSubmit}>
            <input type="submit" value="Find assets" />
          </form>
          {assets}
        </div>
      );
    },
    handleSubmit: function(e){
      e.preventDefault();
      start = true;
    //  name = this.refs.name.value;

      fetch('/api/user/all/?name='+name).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
          assets: json
        });
      });
    }
  });

ReactDOM.render(<Assets />, document.getElementById('assets'));
</code>```

Webpack.config.js:

```<code>var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'puplic') + '\\js\\baseReact.js',
    output: {
        path: path.resolve(__dirname, 'dist') + '/app',
        filename: 'bundle.js',
        publicPath: '/app/'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                include: path.resolve(__dirname, 'public/js'),
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    },
    devServer: {
 historyApiFallback: true
}
};
</code>```

Error:

```<code>ERROR in ./puplic/js/baseReact.js
Module parse failed: C:\Users\test\Documents\GPSTracker\puplic\js\baseReact.js Unexpected token (
53:14)
You may need an appropriate loader to handle this file type.
|           asseti.map(function(asset, index){
|             return(
|               <li key={index}>
|                         <span className={asset.active}></span>
|                         <span>{asset.name}</span>
</code>```

I figure I must be doing something dumb like missing something as it runs in browser which is weird. Does that gloss over some errors as it is interpreted as opposed to been compiled before been run?

答:
Based on the comments, you may be missing the fetch import. Fetch is not readily available in all browsers.

The npm package whatwg-fetch mentions specifically how to get fetch working in a webpack-enabled environment.

Installation

npm install whatwg-fetch --save

or

bower install fetch.

You will also need a Promise polyfill for older browsers. We recommend
  taylorhakes/promise-polyfill for its small size and Promises/A+
  compatibility.

For use with webpack, add this package in the entry configuration
  option before your application entry point:

entry: ['whatwg-fetch', ...]

For Babel and ES2015+, make sure to
  import the file (in your react-components):

import 'whatwg-fetch'

Also, looking at your code, which is deviating a tad from regular javascript style guides in terms of spacings, I'd look into getting eslint up and running in your environment for better feedback for errors like these. If you had eslint enabled, you'd get fetch is undefined as soon as you tried something like this without importing fetch first.

Another personal note from me, try just importing whatwg-fetch in your file, before tampering with your webpack config. You may not need to add it as an entry.

Best of luck!

Title: React code not compiling with webpack

Body:
My code wont compile for some reason. The weird thing is that is will work when I use the in browser interpreter.

React code:

var Cookies = require('cookies');

var cookieParser = require('cookie-parser');

var name = document.getElementById('name').innerHTML;
//var name = req.user.name;

  var start = false;
  var Assets = React.createClass({
    getInitialState: function(){
      return({
        assets: [],
        secondsElapsed: 0
      });
    },
    tick: function() {
      //this.setState({secondsElapsed: this.state.secondsElapsed + 1});
      if(start === true){
        console.log(name);

        var myHeaders = new Headers();

        var token = new Cookies(req,res).get('access_token');

        myHeaders.append('acess_token', token);

        var myInit = { method: 'GET',
               headers: myHeaders};

        fetch('/api/user/all/?name='+name, myInit).then(function(data){
          return data.json();
        }).then( json => {
          this.setState({
              assets: json
            });
        });
    }
    },
    componentDidMount: function() {
      this.interval = setInterval(this.tick, 1000);
    },
    componentWillUnmount: function() {
      clearInterval(this.interval);
    },
    render: function(){
      var assets = this.state.assets;
      assets = assets.map(function(asseti,index){
        return(
          asseti.map(function(asset, index){
            return(

                        {asset.name}
                        {asset.description}
                        {asset.location.coordinates[0]}{asset.location.coordinates[1]}

            )
          })
        )
      });
      return(

          <form onSubmit={this.handleSubmit}>
            <input type="submit" value="Find assets" />
          </form>
          {assets}

      );
    },
    handleSubmit: function(e){
      e.preventDefault();
      start = true;
    //  name = this.refs.name.value;

      fetch('/api/user/all/?name='+name).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
          assets: json
        });
      });
    }
  });

ReactDOM.render(<Assets />, document.getElementById('assets'));

Webpack.config.js:

var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'puplic') + '\\js\\baseReact.js',
    output: {
        path: path.resolve(__dirname, 'dist') + '/app',
        filename: 'bundle.js',
        publicPath: '/app/'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                include: path.resolve(__dirname, 'public/js'),
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    },
    devServer: {
 historyApiFallback: true
}
};

Error:

ERROR in ./puplic/js/baseReact.js
Module parse failed: C:\Users\test\Documents\GPSTracker\puplic\js\baseReact.js Unexpected token (
53:14)
You may need an appropriate loader to handle this file type.
|           asseti.map(function(asset, index){
|             return(
|

|
|                         {asset.name}

I figure I must be doing something dumb like missing something as it runs in browser which is weird. Does that gloss over some errors as it is interpreted as opposed to been compiled before been run?


问:
Apple Mach-O Linker errors and I don't know what to do
I cannot compile my project for the device or simulator anymore. I get 13 Apple Mach-O-Linker errors. It all started after I failed attempt to use sharekit. Here is the log from the error:

```<code>ld: warning: directory not found for option '-F/Users/bbrandy95/Documents/Broken Brandsonic Web Projects/Brandsonic Web mobile/../../Downloads/0.2.1gm1/iphoneos4.0/System/Library/Frameworks'
Undefined symbols for architecture armv7:
  "_OBJC_CLASS_$_NSURLRequest", referenced from:
      objc-class-ref in Brandsonic_Web_mobileAppDelegate.o
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSAutoreleasePool", referenced from:
      objc-class-ref in main.o
  "_objc_msgSendSuper2", referenced from:
      -[Brandsonic_Web_mobileAppDelegate dealloc] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileViewController didReceiveMemoryWarning] in Brandsonic_Web_mobileViewController.o
      -[Brandsonic_Web_mobileViewController dealloc] in Brandsonic_Web_mobileViewController.o
  "_objc_setProperty", referenced from:
      -[Brandsonic_Web_mobileAppDelegate setWindow:] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate setViewController:] in Brandsonic_Web_mobileAppDelegate.o
  "__objc_empty_vtable", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_CLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
      _OBJC_CLASS_$_SecondView in SecondView.o
  "_objc_msgSend", referenced from:
      _main in main.o
      -[Brandsonic_Web_mobileAppDelegate application:didFinishLaunchingWithOptions:] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate dealloc] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate GOOGLE] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate YOUTUBE] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate WIKI] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileViewController webView:shouldStartLoadWithRequest:navigationType:] in Brandsonic_Web_mobileViewController.o
      ...
  "__objc_empty_cache", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_CLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
      _OBJC_CLASS_$_SecondView in SecondView.o
  "_OBJC_CLASS_$_NSObject", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
  "___CFConstantStringClassReference", referenced from:
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      ...
  "_OBJC_CLASS_$_NSKeyedUnarchiver", referenced from:
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSUserDefaults", referenced from:
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSURL", referenced from:
      objc-class-ref in Brandsonic_Web_mobileAppDelegate.o
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_METACLASS_$_NSObject", referenced from:
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
'
</code>```

How do I fix this? Please help.

答:
It's because the project inserted the core data's xcdatamodeld file in compile sources. Select your project -> Build Phases -> Compile Sources and delete projectName.xcdatamodeld file.
And also check if you have imported .m file instead of .h file, it also gives the same linker error. Check all the #import codes.
And check if you have added core data frame work in library and imported core data .h file. Check for creation of NSManagedObject and import it's file.
Just try it and reply me if still any error.

Body:
I cannot compile my project for the device or simulator anymore. I get 13 Apple Mach-O-Linker errors. It all started after I failed attempt to use sharekit. Here is the log from the error:

ld: warning: directory not found for option '-F/Users/bbrandy95/Documents/Broken Brandsonic Web Projects/Brandsonic Web mobile/../../Downloads/0.2.1gm1/iphoneos4.0/System/Library/Frameworks'
Undefined symbols for architecture armv7:
  "_OBJC_CLASS_$_NSURLRequest", referenced from:
      objc-class-ref in Brandsonic_Web_mobileAppDelegate.o
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSAutoreleasePool", referenced from:
      objc-class-ref in main.o
  "_objc_msgSendSuper2", referenced from:
      -[Brandsonic_Web_mobileAppDelegate dealloc] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileViewController didReceiveMemoryWarning] in Brandsonic_Web_mobileViewController.o
      -[Brandsonic_Web_mobileViewController dealloc] in Brandsonic_Web_mobileViewController.o
  "_objc_setProperty", referenced from:
      -[Brandsonic_Web_mobileAppDelegate setWindow:] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate setViewController:] in Brandsonic_Web_mobileAppDelegate.o
  "__objc_empty_vtable", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_CLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
      _OBJC_CLASS_$_SecondView in SecondView.o
  "_objc_msgSend", referenced from:
      _main in main.o
      -[Brandsonic_Web_mobileAppDelegate application:didFinishLaunchingWithOptions:] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate dealloc] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate GOOGLE] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate YOUTUBE] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileAppDelegate WIKI] in Brandsonic_Web_mobileAppDelegate.o
      -[Brandsonic_Web_mobileViewController webView:shouldStartLoadWithRequest:navigationType:] in Brandsonic_Web_mobileViewController.o
      ...
  "__objc_empty_cache", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_CLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
      _OBJC_CLASS_$_SecondView in SecondView.o
  "_OBJC_CLASS_$_NSObject", referenced from:
      _OBJC_CLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
  "___CFConstantStringClassReference", referenced from:
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileAppDelegate.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      CFString in Brandsonic_Web_mobileViewController.o
      ...
  "_OBJC_CLASS_$_NSKeyedUnarchiver", referenced from:
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSUserDefaults", referenced from:
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_CLASS_$_NSURL", referenced from:
      objc-class-ref in Brandsonic_Web_mobileAppDelegate.o
      objc-class-ref in Brandsonic_Web_mobileViewController.o
  "_OBJC_METACLASS_$_NSObject", referenced from:
      _OBJC_METACLASS_$_Brandsonic_Web_mobileAppDelegate in Brandsonic_Web_mobileAppDelegate.o
      _OBJC_METACLASS_$_Brandsonic_Web_mobileViewController in Brandsonic_Web_mobileViewController.o
      _OBJC_METACLASS_$_SecondView in SecondView.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
'

How do I fix this? Please help.


问:
modify the css for font awesome
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/></code>```

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}```

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

答:
You're applying the font family at wrong point. When you're changing the font family it loads that part of the family and all the relative character mappings. So in case you want to add icons, just use the icons as given in the official fontawesome docs. Also Since <input type="button"> is unable to have any html inside it, it's not possible to include text AND icons to it.

I would suggest using <button>.
Reference to my opinion <button> vs. <input type="button" />. Which to use?

HTML

```<code><button type=button class="submitter" onClick="location.href='../test.htm'"> Pre-payment <i class="required-icon-fontawesome"></i></button>
</code>```

CSS

```<code>button {
    font-family: tahoma, helvetica, sans-serif;;
}
</code>```

Title: modify the css for font awesome

Body:
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/>

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

Body:
You're applying the font family at wrong point. When you're changing the font family it loads that part of the family and all the relative character mappings. So in case you want to add icons, just use the icons as given in the official fontawesome docs. Also Since <input type="button"> is unable to have any html inside it, it's not possible to include text AND icons to it.

I would suggest using <button>.
Reference to my opinion <button> vs. <input type="button" />. Which to use?

HTML

<button type=button class="submitter" onClick="location.href='../test.htm'">&#xf09d; Pre-payment <i class="required-icon-fontawesome"></i></button>

CSS

button {
    font-family: tahoma, helvetica, sans-serif;;
}


问:
Applying padding to the head of table
Is there any way i can set padding to the thead alone of a table?</p>

答:
```<code><table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Savings</th>
    </tr>
    <tr>
        <td>Jhon</td>
        <td>Smith</td>
        <td>$200</td>
    </tr>
</table>

<style>
    table, td, th { border : 1px solid black; }
    th { padding : 13px; }
    td { padding : 15px; }
</style>
</code>```

Title: Applying padding to the head of table


问:
UIBarButtonItem clicked side menu not open
I am developing iOS App.Add UIBarButtonItem on Custom UIView.Button Added Successfully.But, when I click on button enter on selector action.But Side menu not open.
Please Help thanks in Advance.

Here is the Code:

```<code>- (void)sideButton{
    UIImage *menuButtonImage = [UIImage imageNamed:@"menu-icon.png"];// set your image Name here
    UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnToggle setImage:menuButtonImage forState:UIControlStateNormal];
    [btnToggle addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    btnToggle.frame = CGRectMake(10, 30, 25, 25);
    [_sideView addSubview:btnToggle]; //sideView is UIView

    _menuBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnToggle];
    self.navigationItem.leftBarButtonItem = _menuBarButton;
}
- (IBAction)checkButtonTapped:(id)sender{
    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController ){
        [_menuBarButton setTarget: self.revealViewController];
        [_menuBarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}
</code>```

答:
You need to add method for checkButtonTapped.

```<code>-(void) checkButtonTapped:(UIButton*)sender {
//write your button action here.
}
</code>```

If you want to use existing method you must mention it into the addTarget method.

Body:
I am developing iOS App.Add UIBarButtonItem on Custom UIView.Button Added Successfully.But, when I click on button enter on selector action.But Side menu not open.
Please Help thanks in Advance.

Here is the Code:

- (void)sideButton{
    UIImage *menuButtonImage = [UIImage imageNamed:@"menu-icon.png"];// set your image Name here
    UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnToggle setImage:menuButtonImage forState:UIControlStateNormal];
    [btnToggle addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    btnToggle.frame = CGRectMake(10, 30, 25, 25);
    [_sideView addSubview:btnToggle]; //sideView is UIView

    _menuBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnToggle];
    self.navigationItem.leftBarButtonItem = _menuBarButton;
}
- (IBAction)checkButtonTapped:(id)sender{
    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController ){
        [_menuBarButton setTarget: self.revealViewController];
        [_menuBarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}

Body:
You need to add method for checkButtonTapped.

-(void) checkButtonTapped:(UIButton*)sender {
//write your button action here.
}

If you want to use existing method you must mention it into the addTarget method.


问:
R - send two-line command to system
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

```<code>convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png
</code>```

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

```<code>convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png
</code>```

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

```<code>> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png
</code>```

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

```<code>system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected
</code>```

The question is: how can I use R to send that specific two-line command to the system?

答:
Using the magick package and making a reproducible example, it might look like

library(tidyverse)
library(magick)

# make and same sample images
seq(4) %>%
    map(~data_frame(x = seq(.x))) %>%
    walk(~{ggplot(.x, aes(x, x)) + geom_point(); ggsave(paste0('plot', max(.x), '.svg'))})

# read images
images <- image_read(paste0('plot', seq(4), '.svg'))

# join pairs of images horizontally, then join the pairs vertically
joined <- image_join(image_append(images[1:2]),
                     image_append(images[3:4])) %>%
    image_append(stack = TRUE)

# set margins
m <- par('mar')
par(mar = rep(0, 4))

# show plot
plot(joined)
```

<p><img src="https://i.imgur.com/WOyRIGT.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code># reset margins
par(mar = m)

# save plot
image_write(joined, 'plot1234.png', format = 'png')
</code>```

Title: R - send two-line command to system

Body:
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected

The question is: how can I use R to send that specific two-line command to the system?

Body:
Using the magick package and making a reproducible example, it might look like

library(tidyverse)
library(magick)

# make and same sample images
seq(4) %>%
    map(~data_frame(x = seq(.x))) %>%
    walk(~{ggplot(.x, aes(x, x)) + geom_point(); ggsave(paste0('plot', max(.x), '.svg'))})

# read images
images <- image_read(paste0('plot', seq(4), '.svg'))

# join pairs of images horizontally, then join the pairs vertically
joined <- image_join(image_append(images[1:2]),
                     image_append(images[3:4])) %>%
    image_append(stack = TRUE)

# set margins
m <- par('mar')
par(mar = rep(0, 4))

# show plot
plot(joined)

# reset margins
par(mar = m)

# save plot
image_write(joined, 'plot1234.png', format = 'png')


答:
You can use <button> tag, add a  or  inside where you'll use default font.

```<code><button type="button" name="button" class="submitter" onClick="location.href='../test.htm'">
  
  <strong>Pre-payment</strong>
</button>
</code>```

CSS

```<code>button {
  font-family: FontAwesome;
}

button strong {
  font-family: 'Your font';
}
</code>```

Title: modify the css for font awesome

Body:
You can use <button> tag, add a <strong> or <span> inside where you'll use default font.

<button type="button" name="button" class="submitter" onClick="location.href='../test.htm'">
  &#xf09d;
  <strong>Pre-payment</strong>
</button>

CSS

button {
  font-family: FontAwesome;
}

button strong {
  font-family: 'Your font';
}


问:
can't get all data from table in select query
this is my table in phpmyadmin name documents. In html form, dropdown of subject name in not compulsory to select. So it can be blank and get 0 that shown in table. But when I run select query to get all documents list, can't get data of sub_id which value is 0. I want all data from documents table. Plz solve this.

```<code>$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents join courses on documents.cour_id=courses.cour_id join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));

doc_id=primary key,
cour_id=index key,
sub_id=index kry

doc_id  cour_id  sub_id  doc_name
  1       1         0
  6       1         2     MB-C250D-AvantGarde-2012.JPG
  7       1         1     adview.sql
  8       1         2     crane.txt
  9       1         0     ui.txt
</code>```

result after run select query

```<code>Document Id     Document Name                  Course    Subject
6               MB-C250D-AvantGarde-2012.JPG   B.com     Statistics
7               adview.sql                     B.com     Accounting
8               crane.txt                      B.com     Statistics
</code>```

答:
Use LEFT JOIN instead:

```<code>select documents.*,courses.cour_name,subjects.sub_name
from documents
LEFT join courses on documents.cour_id=courses.cour_id
LEFT join subjects on documents.sub_id=subjects.sub_id
</code>```

Simple JOIN re-validate existence of data in both tables

Body:
this is my table in phpmyadmin name documents. In html form, dropdown of subject name in not compulsory to select. So it can be blank and get 0 that shown in table. But when I run select query to get all documents list, can't get data of sub_id which value is 0. I want all data from documents table. Plz solve this.

$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents join courses on documents.cour_id=courses.cour_id join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));

doc_id=primary key,
cour_id=index key,
sub_id=index kry

doc_id  cour_id  sub_id  doc_name
  1       1         0
  6       1         2     MB-C250D-AvantGarde-2012.JPG
  7       1         1     adview.sql
  8       1         2     crane.txt
  9       1         0     ui.txt

result after run select query

Document Id     Document Name                  Course    Subject
6               MB-C250D-AvantGarde-2012.JPG   B.com     Statistics
7               adview.sql                     B.com     Accounting
8               crane.txt                      B.com     Statistics

Body:
Use LEFT JOIN instead:

select documents.*,courses.cour_name,subjects.sub_name
from documents
LEFT join courses on documents.cour_id=courses.cour_id
LEFT join subjects on documents.sub_id=subjects.sub_id

Simple JOIN re-validate existence of data in both tables


问:
Stripe:: Cannot charge a customer that has no active card in laravel
everyone I'm trying to implement stripe in my laravel application I have gone through Cartlyst docx and setup it was mentioned but there when I am requesting for testing payment I'm getting this error Cannot charge a customer that has no active card I have looked into google but nothing worked for me till now.

here is the code

```<code>public function payment(Request $request)
{
    $validator = Validator::make(
        array(
            'tokenId' => $request->tokenId,
        ),
        array(
            'tokenId' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('tokenId')) {
            $message = $errors->first('tokenId');
        } else {
            $message = __('apiMessages.parametersRequired');
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    try{

        $stripe = Stripe::make(env('STRIPE_SECRET'), Constant::STRIPE_VERSION);
        $tokenId= $request->tokenId;
        $customer = $stripe->customers()->create([
            'email' => 'patrick@gmail.com',
        ]);
        /*$customer = $stripe->customers()->find($tokenId);*/
        $stripeCustomerId= $customer['id'];
        $charge = $stripe->charges()->create([
            'customer' => $stripeCustomerId,
            'currency' => 'USD',
            'amount'   => Constant::AMOUNT,
        ]);
        $chargeId=$charge['id'];
        $payment= new Payment();
        $payment->userId=1;
        $payment->amount= Constant::AMOUNT;
        $payment->chargeId= $chargeId;
        $payment->paymentStatus= 1;
        $payment->save();
        $this->setMeta("200", __('apiMessages.paymentSuccess'));
        return response()->json($this->setResponse());
    }
    catch (StripeException $stripeException)
    {
        $this->setMeta("403", $stripeException->getMessage());
        return response()->json($this->setResponse());
    }
}
</code>```

Please enlighten me where I am wrong?

答:
yes thanks to jycr753 for enlighten me about my mistake. I have not created any card instant thats why got this error</p>

```<code>$stripeCustomerId= $customer['id'];
        $card = $stripe->cards()->create($stripeCustomerId, $request->tokenId); // add this to add a card.
        $charge = $stripe->charges()->create([
            'customer' => $stripeCustomerId,
            'currency' => 'USD',
            'amount'   => Constant::AMOUNT,
        ]);
</code>```

Body:
everyone I'm trying to implement stripe in my laravel application I have gone through Cartlyst docx and setup it was mentioned but there when I am requesting for testing payment I'm getting this error Cannot charge a customer that has no active card I have looked into google but nothing worked for me till now.

here is the code

public function payment(Request $request)
{
    $validator = Validator::make(
        array(
            'tokenId' => $request->tokenId,
        ),
        array(
            'tokenId' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('tokenId')) {
            $message = $errors->first('tokenId');
        } else {
            $message = __('apiMessages.parametersRequired');
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    try{

        $stripe = Stripe::make(env('STRIPE_SECRET'), Constant::STRIPE_VERSION);
        $tokenId= $request->tokenId;
        $customer = $stripe->customers()->create([
            'email' => 'patrick@gmail.com',
        ]);
        /*$customer = $stripe->customers()->find($tokenId);*/
        $stripeCustomerId= $customer['id'];
        $charge = $stripe->charges()->create([
            'customer' => $stripeCustomerId,
            'currency' => 'USD',
            'amount'   => Constant::AMOUNT,
        ]);
        $chargeId=$charge['id'];
        $payment= new Payment();
        $payment->userId=1;
        $payment->amount= Constant::AMOUNT;
        $payment->chargeId= $chargeId;
        $payment->paymentStatus= 1;
        $payment->save();
        $this->setMeta("200", __('apiMessages.paymentSuccess'));
        return response()->json($this->setResponse());
    }
    catch (StripeException $stripeException)
    {
        $this->setMeta("403", $stripeException->getMessage());
        return response()->json($this->setResponse());
    }
}

Please enlighten me where I am wrong?

Body:
yes thanks to jycr753 for enlighten me about my mistake. I have not created any card instant thats why got this error

$stripeCustomerId= $customer['id'];
        $card = $stripe->cards()->create($stripeCustomerId, $request->tokenId); // add this to add a card.
        $charge = $stripe->charges()->create([
            'customer' => $stripeCustomerId,
            'currency' => 'USD',
            'amount'   => Constant::AMOUNT,
        ]);


问:
Non HBase solution for storing Huge data and updating on real time
Hi i have developed an application where i have to store TB of data for the first time and then 20 GB monthly incremental like insert/update/delete in the form of xml that will be applied on top of this 5 TB of data .
And finally on request basis i have to generate full snapshot of all data and create 5K text files based on the logic so that respective data should be in the respective files .

I have done this project using HBase .
I have created 35 tables in the HBase having region from 10 to 500 .
I have my data in my HDFS and the using mapreduce i bulk load data into receptive Hbase tables .

After that i have SAX parser application written in java to parse all incoming xml incremental files and update HBase tables .The frequency of the xml files are approx 10 xml files per minutes and total of 2000 updates .
The incremental message are strictly in order .

Finally on request basis i run my last mapreduce application to scan all Hbase table and create 5K text files and deliver it to the client .

All 3 steps are working fine but when i went to deploy my application  on production server that is shared cluster ,the infrastructure team are not allowing us to run my application because i do full table scan on HBase .

I have used 94 node cluster and the biggest HBase table data that i have is approx 2 billions .All other tables has less than a millions of data .

Total time for mapreduce to scan and create text files  takes 2 hours.

Now i am looking for some other solution to implement this .

I can use HIVE because i have records level insert/update and delete that too in very precise manner.

I have also integrated HBase and HIVE table so that for incremental data HBase table will be used and for full table scan HIVE will be used .
But as HIVE uses Hbase storage handler i cant create partition in HIVE table and that is why HIVE full table scan becomes very very slow even 10 times slower that HBase Full table scan

I cant think of any solution right now kind of stuck .
Please help me with some other solution where HBase is not involved .

Can i use AVRO or perquet file in this use case .But i am not sure how AVRO will support record level update .

答:
I will answer my question .
My issue is that i dont want to perform full table scan on Hbase because it will impact performance of the region server and specially on the shared cluster it will hit the read wright performance on of the HBase .

So my solution using Hbase because it is very good for the update specially delta update that is columns update .

So in order to avoid that Full table scan take snapshot of HBase table export it to the HDFS and them run full table scan on the Hbase table snapshot.

Here is the detailed steps for the process

Create snapshot

```<code>snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'
</code>```

Export Snapshot to local hdfs

```<code>hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16
</code>```

Driver Job Configuration to rum mapreduce on Hbase snapshot

```<code>String snapshotName="FundamentalAnalyticSnapshot";
Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

 TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                        scan, // Scan instance to control CF and attribute selection
                        DefaultMapper.class, // mapper class
                        NullWritable.class, // mapper output key
                        Text.class, // mapper output value
                        job,
                        true,
                        restoreDir);
</code>```

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.

Body:
I will answer my question .
My issue is that i dont want to perform full table scan on Hbase because it will impact performance of the region server and specially on the shared cluster it will hit the read wright performance on of the HBase .

So my solution using Hbase because it is very good for the update specially delta update that is columns update .

So in order to avoid that Full table scan take snapshot of HBase table export it to the HDFS and them run full table scan on the Hbase table snapshot.

Here is the detailed steps for the process

Create snapshot

snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'

Export Snapshot to local hdfs

hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16

Driver Job Configuration to rum mapreduce on Hbase snapshot

String snapshotName="FundamentalAnalyticSnapshot";
Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

 TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                        scan, // Scan instance to control CF and attribute selection
                        DefaultMapper.class, // mapper class
                        NullWritable.class, // mapper output key
                        Text.class, // mapper output value
                        job,
                        true,
                        restoreDir);

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.


问:
Print the value of injected parameter in sqlmap
I using sqlmap for injection and URL look like
python sqlmap.py -u "http://localhost/utility/?site_name=30"
so i just want to know what are the values sqlmap try to give input for site_name for injection.</p>

答:
Sqlmap keeps the log at:
**/home/root/.sqlmap/output/**. root is the user(change user accordingly).
If you want custom output location you can specify it in **sqlmap.conf**.
If you want everything to be recorded you can do:

```<code>sqlmap.py -u "http://localhost/utility/?site_name=30" > file_name.txt.
</code>```

Body:
Sqlmap keeps the log at:
**/home/root/.sqlmap/output/**. root is the user(change user accordingly).
If you want custom output location you can specify it in **sqlmap.conf**.
If you want everything to be recorded you can do:

sqlmap.py -u "http://localhost/utility/?site_name=30" > file_name.txt.


问:
I want to include several ImageViews from xml file in Android Studio
I want to include several ImageViews from xml file in Android Studio into my java class to modify them later during runtime.
I have a way how it works but I am sure it is not the best.

```<code>List<ImageView> pictures= new ArrayList<>();
    pictures.add((ImageView) findViewById(R.id.picture0));
    pictures.add((ImageView) findViewById(R.id.picture1));
    ...
</code>```

There must be a more efficient way, right? I named the ID of the ImageViews in the xml like pictureX where X is the number of the picture. Thus - I thought - I could somehow iterate over these IDs like

```<code>    for (int i=0; i<24; i++){
        String s = "R.id.picture" + i;
        pictures.add((ImageView) findViewById(s));
    }
</code>```

but it does not work of course because the inconvertible types. The parameter of findViewById must be an int...

Is there a way to get those ImageViews in a loop or do I really have to get every ImageViewon its own?

I am grateful for every answer. :)

答:
You may use ViewGroup.getChildAt()

```<code>for(int i = 0; i < container.getChildCount(); i++){
    pictures.add((ImageView)container.getChildAt(i));
}
</code>```

You may also add cast checker for complex child views so that it doesn't throw ClassCastException

```<code>for(int i = 0; i < container.getChildCount(); i++){
   if(container.getChildAt(i) instanceof ImageView)
      pictures.add((ImageView)container.getChildAt(i));
}
</code>```

Body:
I want to include several ImageViews from xml file in Android Studio into my java class to modify them later during runtime.
I have a way how it works but I am sure it is not the best.

List<ImageView> pictures= new ArrayList<>();
    pictures.add((ImageView) findViewById(R.id.picture0));
    pictures.add((ImageView) findViewById(R.id.picture1));
    ...

There must be a more efficient way, right? I named the ID of the ImageViews in the xml like pictureX where X is the number of the picture. Thus - I thought - I could somehow iterate over these IDs like

    for (int i=0; i<24; i++){
        String s = "R.id.picture" + i;
        pictures.add((ImageView) findViewById(s));
    }

but it does not work of course because the inconvertible types. The parameter of findViewById must be an int...

Is there a way to get those ImageViews in a loop or do I really have to get every ImageViewon its own?

I am grateful for every answer. :)

Body:
You may use ViewGroup.getChildAt()

for(int i = 0; i < container.getChildCount(); i++){
    pictures.add((ImageView)container.getChildAt(i));
}

You may also add cast checker for complex child views so that it doesn't throw ClassCastException

for(int i = 0; i < container.getChildCount(); i++){
   if(container.getChildAt(i) instanceof ImageView)
      pictures.add((ImageView)container.getChildAt(i));
}


问:
Git branch is still on same line as master
I am getting something unexpected happening in the git tree. I have created a branch off of master, however while I am performing commits on the new branch it appears as though these are taking place in the same code line as master...

As you can see, on the very left hand side is the code line for master (dark blue) and right at the top we can see Sprint_15 which is a branch taken from master that appears to have commits on the same line... I am not sure why this is taking place. I would expect to see the code diverge into a new line since features are being merged into Sprint_15 and not master...

My thought is that by merging Sprint_14 and Sprint_15 together this has done something funky to the history but I am not sure why.

I am still fairly new to git so some of its underpinnings still confuse me.

答:
It seems that you are a bit mistaken on how git works (which is normal because you said you are new to git)

Each branch does not necessarily get it's own line. If your branch Sprint_15 has it's base as master and Sprint_15 is any number of commits ahead of master then they will share the same line. As soon as master gets a new commit then I think you will see what you expect.

You can test this in a separate git repo like this.

```<code>$ mkdir testing && cd testing
$ git init  # should put you on master branch by default
$ touch testFile.txt
$ git add -A
$ git commit -m "initial commit"
$ git branch newBranch
$ git checkout newBranch # switch from master to newBranch

### modify the testFile.txt in some way and then...
$ git add -A
$ git commit -m "first commit on newBranch"
</code>```

Now if you use the same tool to look at your repo, you should see only a single line, like this:

Now go back to the master branch and make another commit:

```<code>$ git checkout master
### make another change to testFile.txt
$ git add -A
$ git commit -m "second commit on master"
</code>```

Now you will see each branch having it's own line like you were expecting, like this:

Body:
It seems that you are a bit mistaken on how git works (which is normal because you said you are new to git)

Each branch does not necessarily get it's own line. If your branch Sprint_15 has it's base as master and Sprint_15 is any number of commits ahead of master then they will share the same line. As soon as master gets a new commit then I think you will see what you expect.

You can test this in a separate git repo like this.

$ mkdir testing && cd testing
$ git init  # should put you on master branch by default
$ touch testFile.txt
$ git add -A
$ git commit -m "initial commit"
$ git branch newBranch
$ git checkout newBranch # switch from master to newBranch

### modify the testFile.txt in some way and then...
$ git add -A
$ git commit -m "first commit on newBranch"

Now if you use the same tool to look at your repo, you should see only a single line, like this:

Now go back to the master branch and make another commit:

$ git checkout master
### make another change to testFile.txt
$ git add -A
$ git commit -m "second commit on master"

Now you will see each branch having it's own line like you were expecting, like this: