问:
Jenkins error with plugin bitbucket branch source plugin
Since the last plugin update, all my builds are failing, but I did'nt change any configuration.
I tried to rollback to last version of plugin but the problem persists.

It seems like BitbucketStatusNotificationPlugin is trying to access some Mercurial class...

The project is a multibranch pipeline.
The issue is also referenced on the official JIRA of Jenkins project JENKINS-46296

Any help would be much appreciated.

Thanks!

Here is the output :

```<code> Started by user Olivier
 Checking out git REPO_URL
 into /var/jenkins_home/workspace/TaaS_API_TaaS_develop-HDR4FYYRLEPSYBGEYT6L5UEWPW5HVQDT5PW7ZBCJ6VTGPTYLU6OQ@script to read Jenkinsfile
 > git rev-parse --is-inside-work-tree # timeout=10
 Fetching changes from the remote Git repository
 > git config remote.origin.url
timeout=10
 Fetching without tags
 Fetching upstream changes from REPO_URL
 > git --version # timeout=10
 using GIT_ASKPASS to set credentials Bitbucket pass
 > git fetch --no-tags --progress
 +refs/heads/develop:refs/remotes/origin/develop
 Checking out Revision 5fa34124eb6be5ab7242633a97cced7de4e7af5e (develop)
 Commit message: "Finish team"
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 5fa34124eb6be5ab7242633a97cced7de4e7af5e
 > git rev-list 5fa34124eb6be5ab7242633a97cced7de4e7af5e # timeout=10
 java.lang.IllegalAccessError: tried to access class hudson.plugins.mercurial.MercurialSCMSource$MercurialRevision from class com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.getHash(BitbucketBuildStatusNotifications.java:124)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.sendNotifications(BitbucketBuildStatusNotifications.java:104)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.access$000(BitbucketBuildStatusNotifications.java:54)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications$JobCheckOutListener.onCheckout(BitbucketBuildStatusNotifications.java:14
 at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:127)
 at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:130)
 at org.jenkinsci.plugins.workflow.multibranch.SCMBinder.create(SCMBinder.java:120)
 at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:263)
 at hudson.model.ResourceController.execute(ResourceController.java:97)
 at hudson.model.Executor.run(Executor.java:405)
 Finished: FAILURE
</code>```

答:
This is most likely caused by a version incompatibility between your plugins.

Make sure you update all of the required dependencies to at least the required versions. The minimum required versions of dependencies for the latest version of the plugin can be located on the plugin page.

For older versions, the easiest place to get this information I've found so far is probably the pom file e.g. version 2.2.4.

Before version 2.0 of the mercurial plugin, the type MercurialSCMSource.MercurialRevision was package private (not visible to other packages/plugins).

The latest version of the Bitbucket Branch Source Plugin (2.2.6) declares a dependency on at least version 2.0 of the mercurial plugin. I'm not sure which versions are declared for the versions you are using, but it seems that mercurial 2.0 has been required since at least version 2.2.0 of the Bitbucket Branch Source Plugin.

Even if you aren't using mercurial, the code/classes are still required.

Body:
Since the last plugin update, all my builds are failing, but I did'nt change any configuration.
I tried to rollback to last version of plugin but the problem persists.

It seems like BitbucketStatusNotificationPlugin is trying to access some Mercurial class...

The project is a multibranch pipeline.
The issue is also referenced on the official JIRA of Jenkins project JENKINS-46296

Any help would be much appreciated.

Thanks!

Here is the output :

 Started by user Olivier
 Checking out git REPO_URL
 into /var/jenkins_home/workspace/TaaS_API_TaaS_develop-HDR4FYYRLEPSYBGEYT6L5UEWPW5HVQDT5PW7ZBCJ6VTGPTYLU6OQ@script to read Jenkinsfile
 > git rev-parse --is-inside-work-tree # timeout=10
 Fetching changes from the remote Git repository
 > git config remote.origin.url
timeout=10
 Fetching without tags
 Fetching upstream changes from REPO_URL
 > git --version # timeout=10
 using GIT_ASKPASS to set credentials Bitbucket pass
 > git fetch --no-tags --progress
 +refs/heads/develop:refs/remotes/origin/develop
 Checking out Revision 5fa34124eb6be5ab7242633a97cced7de4e7af5e (develop)
 Commit message: "Finish team"
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 5fa34124eb6be5ab7242633a97cced7de4e7af5e
 > git rev-list 5fa34124eb6be5ab7242633a97cced7de4e7af5e # timeout=10
 java.lang.IllegalAccessError: tried to access class hudson.plugins.mercurial.MercurialSCMSource$MercurialRevision from class com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.getHash(BitbucketBuildStatusNotifications.java:124)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.sendNotifications(BitbucketBuildStatusNotifications.java:104)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications.access$000(BitbucketBuildStatusNotifications.java:54)
 at com.cloudbees.jenkins.plugins.bitbucket.BitbucketBuildStatusNotifications$JobCheckOutListener.onCheckout(BitbucketBuildStatusNotifications.java:14
 at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:127)
 at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:130)
 at org.jenkinsci.plugins.workflow.multibranch.SCMBinder.create(SCMBinder.java:120)
 at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:263)
 at hudson.model.ResourceController.execute(ResourceController.java:97)
 at hudson.model.Executor.run(Executor.java:405)
 Finished: FAILURE


来源: stackexchange

问:
DataJPATest Junit method naming and NullPointerExceptions
I'm using SpringBoot/Kotlin/JPA/Hibernate/Junit and have JpaServiceTest class that exercises the repository methods pertaining to a single Entity. The method names of JpaService Class follow the convention findByXXXXId, findAll, updateXXXX, addXXXX and deleteXXXX.

To maintain consistency I named the methods in the JpaTest Class using the same convention. My JpaTest Class has two findById scenarios, one where the 'Null' is expected an another where the mapped entity is returned. My application works as expected however my test class fails on the findById scenario that is expected to return a valid Entity.

```<code>The service class

@Service("MyService")
@Transactional
internal class JpaMyService(val MyRepo: MyRepository) : MyService {

val log = LoggerFactory.getLogger("MyService")

override fun findByMyId(MyId: Long): MyDto? {
    log.debug("Retrieving My: {}", MyId)
    return MyRepo.findOne(MyId)?.toDto()
}

override fun findAllMys(): List<MyDto> {
    log.debug("Retrieving Mys")
    return MyRepo.findAll().map { it.toDto() }
}

override fun updateMy(id: Long?, My: UpdateMyDto): MyDto? {
    log.debug("Updating My: {} with data: {}", id, My)
    val currentMy = MyRepo.findOne(id)
    return if (currentMy != null) MyRepo.save(MyEntity.fromDto(My, currentMy)).toDto()
    else null
}

override fun addMy(My: CreateMyDto): MyDto {
    log.debug("Adding My: {}", My)
    return MyRepo.save(MyEntity.fromDto(My)).toDto()
}

override fun deleteMy(id: Long?) {
    log.debug("Deleting My: {}", id)
    MyRepo.delete(id)
}
</code>```

The offending method

```<code>@Test
fun `'findMyById' should map existing entity from repository`() {
    repository.save(MyEntity(1, "name", "description"))
    val result = service.findByMyId(1)
    softly.assertThat(result?.id).isEqualTo(1)
    softly.assertThat(result?.name).isEqualTo("name")
    softly.assertThat(result?.description).isEqualTo("description")
}

Test failure

org.junit.ComparisonFailure:
Expected :"name"
Actual   :null
</code>```

Changing the name of the failing findByMyId method to either getByMyId or retrieveByMyId allows the test case to pass successfully from both command line and IDE. The test would always work from the IDE if run as a single test, irrespective of the name, but when the test class is run as a whole it would fail.

I'd like to know what the problem is with using findByXXId to return and Entity and this works when I change the name of the test method to start with either get or retrieve. If I use any other method name it also fails and what is more, even when I change the method name in other Services and Test classes I'm seeing a failure, due to a NPE.

Apologies in advance if this doesn't make sense, but I'm new to this stack and its taken three days to identify why these tests fail when the application works perfectly well.

答:
Since my first suggestions in the comments didn't seem to fix it here is a list of things to do in order to isolate the problem.

First just to make sure I've got the facts straight:

Your test works in the IDE

Your test fails when run with all the other tests (presumably using Maven or similar)

Your test works when run with all the other tests, but renamed.

My hunch from the comments still holds: This is not directly related to the name but to interdependencies between tests.

Create a minimal scenario that reproduces the problem in the IDE.

a) run all the tests in the IDE (should be possible by selecting the test sources folder and selecting "Run tests" or something.

b) assuming the test fails reduce the test scope by selecting smaller and smaller parts of the tree.

c) if the test doesn't fail at all in the IDE you can do the same using include/exclude in Maven or any other respectable build tool.

d) another variation of this is to create a dedicated TestSuite including all the tests.

In general, by removing about half the tests in each step you should be able to end up with a test suite of two test in reasonable time: the problematic test and one more test triggering the first one to fail.

Activate logging for SQL and Transaction handling.

You should see a rollback after the first test. Followed by the inserts of the second test. You should not see any commit.

If you don't see the rollback your test is either not annotated with @Transactional or the transaction isn't picked up for some reason.

If you don't see the inserts, your changes seem not to get flushed.

Using the JDBC template issue select statements to see the content of your database. Use trivial statements like select * from x. No where clause, no join. Log the results.

Chances are with this information the problem became obvious for you. If not update the question and comment on this answer. I'll take another look.

ContentLicense: CC BY-SA 3.0

Body:
I'm using SpringBoot/Kotlin/JPA/Hibernate/Junit and have JpaServiceTest class that exercises the repository methods pertaining to a single Entity. The method names of JpaService Class follow the convention findByXXXXId, findAll, updateXXXX, addXXXX and deleteXXXX.

To maintain consistency I named the methods in the JpaTest Class using the same convention. My JpaTest Class has two findById scenarios, one where the 'Null' is expected an another where the mapped entity is returned. My application works as expected however my test class fails on the findById scenario that is expected to return a valid Entity.

The service class

@Service("MyService")
@Transactional
internal class JpaMyService(val MyRepo: MyRepository) : MyService {

val log = LoggerFactory.getLogger("MyService")

override fun findByMyId(MyId: Long): MyDto? {
    log.debug("Retrieving My: {}", MyId)
    return MyRepo.findOne(MyId)?.toDto()
}

override fun findAllMys(): List<MyDto> {
    log.debug("Retrieving Mys")
    return MyRepo.findAll().map { it.toDto() }
}

override fun updateMy(id: Long?, My: UpdateMyDto): MyDto? {
    log.debug("Updating My: {} with data: {}", id, My)
    val currentMy = MyRepo.findOne(id)
    return if (currentMy != null) MyRepo.save(MyEntity.fromDto(My, currentMy)).toDto()
    else null
}

override fun addMy(My: CreateMyDto): MyDto {
    log.debug("Adding My: {}", My)
    return MyRepo.save(MyEntity.fromDto(My)).toDto()
}

override fun deleteMy(id: Long?) {
    log.debug("Deleting My: {}", id)
    MyRepo.delete(id)
}

The offending method

@Test
fun `'findMyById' should map existing entity from repository`() {
    repository.save(MyEntity(1, "name", "description"))
    val result = service.findByMyId(1)
    softly.assertThat(result?.id).isEqualTo(1)
    softly.assertThat(result?.name).isEqualTo("name")
    softly.assertThat(result?.description).isEqualTo("description")
}

Test failure

org.junit.ComparisonFailure:
Expected :"name"
Actual   :null

Changing the name of the failing findByMyId method to either getByMyId or retrieveByMyId allows the test case to pass successfully from both command line and IDE. The test would always work from the IDE if run as a single test, irrespective of the name, but when the test class is run as a whole it would fail.

I'd like to know what the problem is with using findByXXId to return and Entity and this works when I change the name of the test method to start with either get or retrieve. If I use any other method name it also fails and what is more, even when I change the method name in other Services and Test classes I'm seeing a failure, due to a NPE.

Apologies in advance if this doesn't make sense, but I'm new to this stack and its taken three days to identify why these tests fail when the application works perfectly well.


问:
Installing pfx SSL certificate in tomcat 8.5 on windows
I have wild card pfx certificate with its Intermediate certificate in p7b/crt format. Those certificate are installed on IIS 8.0. How to install those certificates in tomcat 8.0? Tomcat is installed on windows</p>

答:
Please convert the PFX file into a Tomcat compatible format . The command is given below

```<code>Keytool -importkeystore -srckeystore server.pfx -srcstoretype pkcs12 -destkeystore tomcat.jks -deststoretype jks
</code>```

The tomcat.jks file directives can be provided in the server.xml file of tomcat.

Body:
Please convert the PFX file into a Tomcat compatible format . The command is given below

Keytool -importkeystore -srckeystore server.pfx -srcstoretype pkcs12 -destkeystore tomcat.jks -deststoretype jks

The tomcat.jks file directives can be provided in the server.xml file of tomcat.

ContentLicense: CC BY-SA 4.0


问:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in "package name"
I am new to spring and hibernate  as well as to stackoverflow
A developing ecommerce project using spring hibernate maven
creating two file one for frontend and 2nd for backend after creating two file i am adding dependency of backend into frontend pom.ml file

I am using java to create sessionfactory ,datasource and transaction manager
here is the code I dont understand what mistake i am doing

```<code>package com.ecom.Config;

import java.util.Properties;

import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;

import com.ecom.Model.CustomerRegistration;

 @Configuration
 @ComponentScan("com.ecom")
 @EnableTransactionManagement
 public class AnnotationConfigApplicationContext {

@Bean(name = "dataSource")
public DataSource getH2DataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    dataSource.setUrl("jdbc:h2:tcp://localhost/~/Ecommerce");

    dataSource.setDriverClassName("org.h2.Driver");

    dataSource.setUsername("sa");

    dataSource.setPassword("");

    return dataSource;
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.put("hibernate.show_sql", "true");
    properties.put("hibernate.hbm2ddl.auto", "create");
    return properties;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {

    LocalSessionFactoryBuilder sessionBuilder = new
LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.addProperties(getHibernateProperties());
    sessionBuilder.addAnnotatedClass(CustomerRegistration.class);

    return sessionBuilder.buildSessionFactory();
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
    HibernateTransactionManager transactionManager = new
 HibernateTransactionManager(sessionFactory);

    return transactionManager;
}

}
</code>```

Contoller

```<code> package com.ecom.Controller;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;

 import org.springframework.web.bind.annotation.ModelAttribute;

 import org.springframework.web.bind.annotation.RequestMapping;

 import com.ecom.DAO.CustomerRegDAO;
 import com.ecom.Model.CustomerRegistration;

@Controller
public class CustomerRegController
{
 @Autowired
 private CustomerRegDAO  customerRegDAO ;

 @RequestMapping("/registrationForm")
 public String Registration(Model theModel)
 {
     CustomerRegistration theCustomerRegistration = new
CustomerRegistration();

     theModel.addAttribute("customer", theCustomerRegistration);

     return "registration-form";
 }

 @RequestMapping("/saveCustomer")
 public String saveCustomer(@ModelAttribute("customer")
CustomerRegistration theCustomerRegistration)
 {

     customerRegDAO.saveCustomer(theCustomerRegistration);

     return "index";
 }

 }
</code>```

DAO

```<code>      package com.ecom.DAOImplementation;

     import javax.transaction.Transactional;

     import org.hibernate.Session;
     import org.hibernate.SessionFactory;
     import org.springframework.stereotype.Repository;

     import com.ecom.DAO.CustomerRegDAO;
    import com.ecom.Model.CustomerRegistration;

  @Repository("CustomerRegDAO")
  @Transactional
  public class CustomerRegDAOImpl implements CustomerRegDAO {

    private SessionFactory sessionFactory;

  @Transactional
  public void saveCustomer(CustomerRegistration theCustomerRegistration) {

    Session currentsession = sessionFactory.getCurrentSession();

    currentsession.saveOrUpdate(theCustomerRegistration);

   }

  }
</code>```

Error:

```<code>  Type Exception Report

  Message Servlet.init() for servlet [spring] threw exception

  Description The server encountered an unexpected condition that prevented
 it from fulfilling the request.

 Exception

 javax.servlet.ServletException: Servlet.init() for servlet [spring] threw
 exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:475)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:651)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)

 Root cause
 org.springframework.beans.factory.BeanCreationException: Error creating
 bean
 with name 'sessionFactory' defined in
 com.ecom.Config.AnnotationConfigApplicationContext: Bean instantiation via
 factory method failed; nested exception is
 org.springframework.beans.BeanInstantiationException: Failed to instantiate
 [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw
 exception; nested exception is java.lang.NoClassDefFoundError: Could not
 initialize class
 org.hibernate.annotations.common.reflection.java.JavaReflectionManager

 java.lang.NoClassDefFoundError: Could not initialize class
 org.hibernate.annotations.common.reflection.java.JavaReflectionManager
</code>```

答:
The exception is indicating that the class JavaReflectionManager is not found. This class is present in hibernate-commons-annotations jar file. Can you add this in your pom.xml and try running it again?

```<code><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-commons-annotations</artifactId>
    <version>4.0.2.Final</version>
</dependency>
</code>```

Body:
I am new to spring and hibernate  as well as to stackoverflow
A developing ecommerce project using spring hibernate maven
creating two file one for frontend and 2nd for backend after creating two file i am adding dependency of backend into frontend pom.ml file

I am using java to create sessionfactory ,datasource and transaction manager
here is the code I dont understand what mistake i am doing

package com.ecom.Config;

import java.util.Properties;

import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;

import com.ecom.Model.CustomerRegistration;

 @Configuration
 @ComponentScan("com.ecom")
 @EnableTransactionManagement
 public class AnnotationConfigApplicationContext {

@Bean(name = "dataSource")
public DataSource getH2DataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    dataSource.setUrl("jdbc:h2:tcp://localhost/~/Ecommerce");

    dataSource.setDriverClassName("org.h2.Driver");

    dataSource.setUsername("sa");

    dataSource.setPassword("");

    return dataSource;
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.put("hibernate.show_sql", "true");
    properties.put("hibernate.hbm2ddl.auto", "create");
    return properties;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {

    LocalSessionFactoryBuilder sessionBuilder = new
LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.addProperties(getHibernateProperties());
    sessionBuilder.addAnnotatedClass(CustomerRegistration.class);

    return sessionBuilder.buildSessionFactory();
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
    HibernateTransactionManager transactionManager = new
 HibernateTransactionManager(sessionFactory);

    return transactionManager;
}

}

Contoller

 package com.ecom.Controller;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;

 import org.springframework.web.bind.annotation.ModelAttribute;

 import org.springframework.web.bind.annotation.RequestMapping;

 import com.ecom.DAO.CustomerRegDAO;
 import com.ecom.Model.CustomerRegistration;

@Controller
public class CustomerRegController
{
 @Autowired
 private CustomerRegDAO  customerRegDAO ;

 @RequestMapping("/registrationForm")
 public String Registration(Model theModel)
 {
     CustomerRegistration theCustomerRegistration = new
CustomerRegistration();

     theModel.addAttribute("customer", theCustomerRegistration);

     return "registration-form";
 }

 @RequestMapping("/saveCustomer")
 public String saveCustomer(@ModelAttribute("customer")
CustomerRegistration theCustomerRegistration)
 {

     customerRegDAO.saveCustomer(theCustomerRegistration);

     return "index";
 }

 }

DAO

      package com.ecom.DAOImplementation;

     import javax.transaction.Transactional;

     import org.hibernate.Session;
     import org.hibernate.SessionFactory;
     import org.springframework.stereotype.Repository;

     import com.ecom.DAO.CustomerRegDAO;
    import com.ecom.Model.CustomerRegistration;

  @Repository("CustomerRegDAO")
  @Transactional
  public class CustomerRegDAOImpl implements CustomerRegDAO {

    private SessionFactory sessionFactory;

  @Transactional
  public void saveCustomer(CustomerRegistration theCustomerRegistration) {

    Session currentsession = sessionFactory.getCurrentSession();

    currentsession.saveOrUpdate(theCustomerRegistration);

   }

  }

Error:

  Type Exception Report

  Message Servlet.init() for servlet [spring] threw exception

  Description The server encountered an unexpected condition that prevented
 it from fulfilling the request.

 Exception

 javax.servlet.ServletException: Servlet.init() for servlet [spring] threw
 exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:475)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:651)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)

 Root cause
 org.springframework.beans.factory.BeanCreationException: Error creating
 bean
 with name 'sessionFactory' defined in
 com.ecom.Config.AnnotationConfigApplicationContext: Bean instantiation via
 factory method failed; nested exception is
 org.springframework.beans.BeanInstantiationException: Failed to instantiate
 [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw
 exception; nested exception is java.lang.NoClassDefFoundError: Could not
 initialize class
 org.hibernate.annotations.common.reflection.java.JavaReflectionManager

 java.lang.NoClassDefFoundError: Could not initialize class
 org.hibernate.annotations.common.reflection.java.JavaReflectionManager

Body:
The exception is indicating that the class JavaReflectionManager is not found. This class is present in hibernate-commons-annotations jar file. Can you add this in your pom.xml and try running it again?

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-commons-annotations</artifactId>
    <version>4.0.2.Final</version>
</dependency>


问:
How to make this javascript script work?
i'm quite new to javascript and coding. I was wondering if someone could put this random name generator from jsfiddle together into a single working file?
I just cant work out how to make it run, do i have to import some libraries or something?
I have a feeling if i get this working i might learn something, somehow.

Heres where i got the code:
https://jsfiddle.net/katowulf/3gtDf/

Heres the script:

```<code>$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() *   . list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();
</code>```

And the html:

```<code><button>new name</button>
    <h2></h2>
</code>```

答:
You need jQuery because you're using it to select elements and you need to make sure your DOM is ready when the code first runs because it will be looking for the h2 element.

Also, you have a typo in this line:

```<code>var i = Math.floor(Math.random() *   . list.length);
               (that extra dot)     ^^^
</code>```

Let's fix it and try it here:

$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() * list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>new name</button>
<h2></h2></code>```

All good.

Body:
i'm quite new to javascript and coding. I was wondering if someone could put this random name generator from jsfiddle together into a single working file?
I just cant work out how to make it run, do i have to import some libraries or something?
I have a feeling if i get this working i might learn something, somehow.

Heres where i got the code:
https://jsfiddle.net/katowulf/3gtDf/

Heres the script:

$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() *   . list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();

And the html:

<button>new name</button>

Body:
You need jQuery because you're using it to select elements and you need to make sure your DOM is ready when the code first runs because it will be looking for the h2 element.

Also, you have a typo in this line:

var i = Math.floor(Math.random() *   . list.length);
               (that extra dot)     ^^^

Let's fix it and try it here:

$('button').click(function() {
    $('h2').text(randomEl(adjectives)+' '+randomEl(nouns));
    selectElementContents($('h2')[0]);
});

function randomEl(list) {
    var i = Math.floor(Math.random() * list.length);
    return list[i];
}

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var adjectives = ["adamant", "adroit", "amatory", "animistic", "antic", "arcadian", "baleful", "bellicose", "bilious", "boorish", "calamitous", "caustic", "cerulean", "comely", "concomitant", "contumacious", "corpulent", "crapulous", "defamatory", "didactic", "dilatory", "dowdy", "efficacious", "effulgent", "egregious", "endemic", "equanimous", "execrable", "fastidious", "feckless", "fecund", "friable", "fulsome", "garrulous", "guileless", "gustatory", "heuristic", "histrionic", "hubristic", "incendiary", "insidious", "insolent", "intransigent", "inveterate", "invidious", "irksome", "jejune", "jocular", "judicious", "lachrymose", "limpid", "loquacious", "luminous", "mannered", "mendacious", "meretricious", "minatory", "mordant", "munificent", "nefarious", "noxious", "obtuse", "parsimonious", "pendulous", "pernicious", "pervasive", "petulant", "platitudinous", "precipitate", "propitious", "puckish", "querulous", "quiescent", "rebarbative", "recalcitant", "redolent", "rhadamanthine", "risible", "ruminative", "sagacious", "salubrious", "sartorial", "sclerotic", "serpentine", "spasmodic", "strident", "taciturn", "tenacious", "tremulous", "trenchant", "turbulent", "turgid", "ubiquitous", "uxorious", "verdant", "voluble", "voracious", "wheedling", "withering", "zealous"];
var nouns = ["ninja", "chair", "pancake", "statue", "unicorn", "rainbows", "laser", "senor", "bunny", "captain", "nibblets", "cupcake", "carrot", "gnomes", "glitter", "potato", "salad", "toejam", "curtains", "beets", "toilet", "exorcism", "stick figures", "mermaid eggs", "sea barnacles", "dragons", "jellybeans", "snakes", "dolls", "bushes", "cookies", "apples", "ice cream", "ukulele", "kazoo", "banjo", "opera singer", "circus", "trampoline", "carousel", "carnival", "locomotive", "hot air balloon", "praying mantis", "animator", "artisan", "artist", "colorist", "inker", "coppersmith", "director", "designer", "flatter", "stylist", "leadman", "limner", "make-up artist", "model", "musician", "penciller", "producer", "scenographer", "set decorator", "silversmith", "teacher", "auto mechanic", "beader", "bobbin boy", "clerk of the chapel", "filling station attendant", "foreman", "maintenance engineering", "mechanic", "miller", "moldmaker", "panel beater", "patternmaker", "plant operator", "plumber", "sawfiler", "shop foreman", "soaper", "stationary engineer", "wheelwright", "woodworkers"];

$('button').click();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>new name</button>
<h2></h2>

All good.


问:
is unobstrusive javascript style slower than the usual?
At the moment I'm doing jquery like this

```<code><input id='aa' ... >
<script>
makeIt('aa', 2,'home/getitems',10)
</script>
</code>```

I can also do it like this

```<code><input class='theOne' ae-minLen='3' ae-url='home/getitems' ae-maxRes='10' ... >
</code>```

and the makeIt is called on document.ready for
$(document).find('.theOne').each ...

and it gets the values using

$(this).attr('ae-minLen') etc.

but, I'm wondering whether the unobtrusive way is slower than the usual ?

EDIT:
ppl say it's slower, how much slower is it, should I have a 5MB html to actually notice it ?

答:
Yes the unobtrusive way is the slowest, and will always be.

The question is weather or not this is relevant.

If you way the pros and cons, you will see that in most cases, the unobtrusive way will give you a lot of benefits (for instance easier maintainability of your code) for a very little performance cost.

Read up on when to optimize

ContentLicense: CC BY-SA 2.5

Body:
At the moment I'm doing jquery like this

<input id='aa' ... >

I can also do it like this

<input class='theOne' ae-minLen='3' ae-url='home/getitems' ae-maxRes='10' ... >

and the makeIt is called on document.ready for
$(document).find('.theOne').each ...

and it gets the values using

$(this).attr('ae-minLen') etc.

but, I'm wondering whether the unobtrusive way is slower than the usual ?

EDIT:
ppl say it's slower, how much slower is it, should I have a 5MB html to actually notice it ?


答:
You have syntax error here, remove .

```<code>var i = Math.floor(Math.random() *   . list.length);
</code>```

Your demo : https://jsfiddle.net/3gtDf/409/

Title: How to make this javascript script work?

Body:
You have syntax error here, remove .

var i = Math.floor(Math.random() *   . list.length);

Your demo : https://jsfiddle.net/3gtDf/409/


问:
BroadcastReceiver: how to manage priority?
How is the priority setting for a BroadcastReceiver to be used?

How could my application possibly know the priorities of all other BroadcastReceivers in the apps that a phone user might have installed?

I have an app with a BroadcastReceiver to just intercept one number of interest. For all other numbers I immediately call setResultData with the original number and return.

The app worked fine, until a user with an Asus phone and automatic recording of phone calls (an Asus feature) enabled. For this user, my app is not called. I don't think Asus would be writing a rogue app. What could possibly explain the phenomena?

答:
Refer to the line "The value must be greater than -1000 and less than 1000." from below link, highest priority is 999 not 1000.

http://developer.android.com/guide/topics/manifest/intent-filter-element.html


问:
Print Html template in Angular 2 (ng-print in Angular 2)
I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1 </p>

<p>Any suggestion would be appreciated </p>

答:
Print service

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {
    let printContainer: HTMLElement = document.querySelector('#print-container');

    if (!printContainer) {
      printContainer = document.createElement('div');
      printContainer.id = 'print-container';
    }

    printContainer.innerHTML = '';

    let elementCopy = printEl.cloneNode(true);
    printContainer.appendChild(elementCopy);
    document.body.appendChild(printContainer);

    window.print();
  }
}
</code>```

Сomponent that I want to print

```<code>@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  @ViewChild('printEl') printEl: ElementRef;

  constructor(private printingService: PrintingService) {}

  public print(): void {
    this.printingService.print(this.printEl.nativeElement);
 }

}
</code>```

Not the best choice, but works.

Body:
I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1

Any suggestion would be appreciated

Body:
Print service

import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {
    let printContainer: HTMLElement = document.querySelector('#print-container');

    if (!printContainer) {
      printContainer = document.createElement('div');
      printContainer.id = 'print-container';
    }

    printContainer.innerHTML = '';

    let elementCopy = printEl.cloneNode(true);
    printContainer.appendChild(elementCopy);
    document.body.appendChild(printContainer);

    window.print();
  }
}

Сomponent that I want to print

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  @ViewChild('printEl') printEl: ElementRef;

  constructor(private printingService: PrintingService) {}

  public print(): void {
    this.printingService.print(this.printEl.nativeElement);
 }

}

Not the best choice, but works.


问:
How to display the workHr that comes as json data in table format using vue js?
My json data is

```<code>{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}
</code>```

Currently I am displaying data as

```<code> <p><i class="fa fa-map-marker" aria-hidden="true"></I>{{data.place}}, {{data.city}}, {{data.pincode}}</p><br>
</code>```

I need to display {{data.workHr}} in the form of a table

My table is as

```<code> <table class="table">
  <thead>
    <tr>
      <th>Sunday</th>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
      <th>Saturday</th>
    </tr>
  </thead>
  <tbody>
    <tr>

      <td></td>
       <td></td>
        <td></td>
         <td></td>
          <td></td>
           <td></td>
            <td></td>
    </tr>
  </tbody>
</table>
</code>```

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

答:
I think this is what you are asking for. Iterate over the weekTimings and display each value in your table.

    var data = {
       "status":true,
       "data":{
          "pid":10,
          "bussinessName":"Ey technology",
          "services":"1, 3, 4, 2",
          "inventory":[
             "specs",
             "Eye Testing",
             "Lens",
             "Doctors"
          ],
          "workHr":"Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM",
          "description":"Good technology company for software",
          "category":1,
          "sub_category":[
             "Homeo pathy",
             "Web development"
          ],
          "lat":9.5274336,
          "lon":76.8224309,
          "contactName":"simon",
          "contactEmail":"simon@gmail.com",
          "contactOfficeAddress":"college of Eng",
          "contactNumber":"1236547859",
          "contactOfficeNumber":"8947123658",
          "state":"Kerala",
          "city":"Koy",
          "place":"Kly",
          "pincode":686514,
          "referer":24,
          "link":24,
          "views":0,
          "package":1,
          "listing_pic":"default",
          "website":"www.ey.com"
       }
    }

    var weekTimings = data.data.workHr.split(",").map(day => {
        let arr = day.split(":")
        arr.splice(0,1);
        return arr.join(":");
    });

    var sundayTiming = weekTimings.pop();
    weekTimings.unshift(sundayTiming);
    console.log(weekTimings);

   // You can do like below using JS or you can use jQuery and shorten your code
   document.getElementById("sun").innerHTML = weekTimings[0];
   document.getElementById("mon").innerHTML = weekTimings[1];
   document.getElementById("tue").innerHTML = weekTimings[2];
   document.getElementById("wed").innerHTML = weekTimings[3];
   document.getElementById("thu").innerHTML = weekTimings[4];
   document.getElementById("fri").innerHTML = weekTimings[5];
   document.getElementById("sat").innerHTML = weekTimings[6];
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
  <thead>
    <tr>
      <th>Sunday</th>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
      <th>Saturday</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="sun"></td>
      <td id="mon"></td>
      <td id="tue"></td>
      <td id="wed"></td>
      <td id="thu"></td>
      <td id="fri"></td>
      <td id="sat"></td>
    </tr>
  </tbody>
</table></code>```

Using Vue.js

You can iterate over the array using v-for and display the data

```<code><td v-for="day in weekTimings">{{ day }}</td>
</code>```

Hope this helps :)

Body:
My json data is

{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}

Currently I am displaying data as

{{data.place}}, {{data.city}}, {{data.pincode}}

I need to display {{data.workHr}} in the form of a table

My table is as

      Sunday
      Monday
      Tuesday
      Wednesday
      Thursday
      Friday
      Saturday

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

Body:
I think this is what you are asking for. Iterate over the weekTimings and display each value in your table.

    var data = {
       "status":true,
       "data":{
          "pid":10,
          "bussinessName":"Ey technology",
          "services":"1, 3, 4, 2",
          "inventory":[
             "specs",
             "Eye Testing",
             "Lens",
             "Doctors"
          ],
          "workHr":"Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM",
          "description":"Good technology company for software",
          "category":1,
          "sub_category":[
             "Homeo pathy",
             "Web development"
          ],
          "lat":9.5274336,
          "lon":76.8224309,
          "contactName":"simon",
          "contactEmail":"simon@gmail.com",
          "contactOfficeAddress":"college of Eng",
          "contactNumber":"1236547859",
          "contactOfficeNumber":"8947123658",
          "state":"Kerala",
          "city":"Koy",
          "place":"Kly",
          "pincode":686514,
          "referer":24,
          "link":24,
          "views":0,
          "package":1,
          "listing_pic":"default",
          "website":"www.ey.com"
       }
    }

    var weekTimings = data.data.workHr.split(",").map(day => {
        let arr = day.split(":")
        arr.splice(0,1);
        return arr.join(":");
    });

    var sundayTiming = weekTimings.pop();
    weekTimings.unshift(sundayTiming);
    console.log(weekTimings);

   // You can do like below using JS or you can use jQuery and shorten your code
   document.getElementById("sun").innerHTML = weekTimings[0];
   document.getElementById("mon").innerHTML = weekTimings[1];
   document.getElementById("tue").innerHTML = weekTimings[2];
   document.getElementById("wed").innerHTML = weekTimings[3];
   document.getElementById("thu").innerHTML = weekTimings[4];
   document.getElementById("fri").innerHTML = weekTimings[5];
   document.getElementById("sat").innerHTML = weekTimings[6];

<table class="table">
  <thead>
    <tr>
      <th>Sunday</th>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
      <th>Saturday</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="sun"></td>
      <td id="mon"></td>
      <td id="tue"></td>
      <td id="wed"></td>
      <td id="thu"></td>
      <td id="fri"></td>
      <td id="sat"></td>
    </tr>
  </tbody>
</table>

Using Vue.js

You can iterate over the array using v-for and display the data

<td v-for="day in weekTimings">{{ day }}</td>

Hope this helps :)


问:
Swift sort array of different classes
I have array that contain items of 2 possible classes, that are different, but each of them have object Date, that is contain object creation date.

What i want is, sort array using that date variable, with newest items first.
I have not found simply solution for that.

答:
Subclass your two classes to one protocol, for example

```<code>protocol HasName {
    var name: String { get set }
}

class Person: HasName {
    var name: String = ""

    init(name: String) { self.name = name }
}

class Car: HasName {
    var name: String = ""

    init(name: String) { self.name = name }
}
</code>```

Creating the array would look like this, in this case.

```<code>let someArray: [HasName] = [
    Car(name: "mercedes"),
    Person(name: "jason")
]

// you can then now use the `.sort()` array function.

someArray.sort(by: { $0.name > $1.name })
</code>```

Title: Swift sort array of different classes

Body:
Subclass your two classes to one protocol, for example

protocol HasName {
    var name: String { get set }
}

class Person: HasName {
    var name: String = ""

    init(name: String) { self.name = name }
}

class Car: HasName {
    var name: String = ""

    init(name: String) { self.name = name }
}

Creating the array would look like this, in this case.

let someArray: [HasName] = [
    Car(name: "mercedes"),
    Person(name: "jason")
]

// you can then now use the `.sort()` array function.

someArray.sort(by: { $0.name > $1.name })


问:
Error instantiating 'org.apache.spark.sql.hive.HiveSessionState': on Linux server
I have a Scala Spark application that I'm trying to run on a Linux server using a shell script. I am getting the error:

Exception in thread "main" java.lang.IllegalArgumentException: Error
  while instantiating 'org.apache.spark.sql.hive.HiveSessionState':

However, I don't understand what is wrong. I am doing this to instantiate Spark:

```<code>val sparkConf = new SparkConf().setAppName("HDFStoES").setMaster("local")

      val spark: SparkSession = SparkSession.builder.enableHiveSupport().config(sparkConf).getOrCreate()
</code>```

Am I doing this correctly, if so what could be the error?

答:
```<code>sparkSession = SparkSession.builder().appName("Test App").master("local[*])
                .config("hive.metastore.warehouse.dir", hiveWareHouseDir)
                .config("spark.sql.warehouse.dir", hiveWareHouseDir).enableHiveSupport().getOrCreate();
</code>```

Use above, you need to specify the "hive.metastore.warehouse.dir" directory to enable hive support in spark session.

Body:
I have a Scala Spark application that I'm trying to run on a Linux server using a shell script. I am getting the error:

Exception in thread "main" java.lang.IllegalArgumentException: Error
  while instantiating 'org.apache.spark.sql.hive.HiveSessionState':

However, I don't understand what is wrong. I am doing this to instantiate Spark:

val sparkConf = new SparkConf().setAppName("HDFStoES").setMaster("local")

      val spark: SparkSession = SparkSession.builder.enableHiveSupport().config(sparkConf).getOrCreate()

Am I doing this correctly, if so what could be the error?

Body:
sparkSession = SparkSession.builder().appName("Test App").master("local[*])
                .config("hive.metastore.warehouse.dir", hiveWareHouseDir)
                .config("spark.sql.warehouse.dir", hiveWareHouseDir).enableHiveSupport().getOrCreate();

Use above, you need to specify the "hive.metastore.warehouse.dir" directory to enable hive support in spark session.


问:
Symfony2 error Expected end of string
Trying to run a query with symfony and I get this error:

```<code>[Syntax Error] line 0, col 83: Error: Expected end of string, got 'username'
</code>```

This code throws that error:

```<code>$query = $em->createQuery(
            'SELECT username
            FROM BLOGBlogBundle:user
            WHERE username= :usrname'
        )->setParameter('usrname', $usr);
        $products = $query->getResult();
</code>```

What am I doing wrong?

答:
What worked for me is using Exp with ->set() like $qb->expr()

```<code>$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();
</code>```

Title: Symfony2 error Expected end of string

Body:
Trying to run a query with symfony and I get this error:

[Syntax Error] line 0, col 83: Error: Expected end of string, got 'username'

This code throws that error:

$query = $em->createQuery(
            'SELECT username
            FROM BLOGBlogBundle:user
            WHERE username= :usrname'
        )->setParameter('usrname', $usr);
        $products = $query->getResult();

What am I doing wrong?

Body:
What worked for me is using Exp with ->set() like $qb->expr()

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();


问:
Cannot read property 'location' of undefined
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

```<code>import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)
</code>```

This is my routes

```<code>import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )
</code>```

And also for server side express I set this get configuration

```<code>app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});
</code>```

答:
Check the version of react-router-dom in package.json

If its version is greater than 4 then in your file import BrowserRouter :-

```<code>import { BrowserRouter as Router, Route } from 'react-router-dom'
</code>```

else if its version is less than 4 then import Router :-

```<code>import { Router, Route } from 'react-router-dom'
</code>```

Body:
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)

This is my routes

import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )

And also for server side express I set this get configuration

app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});

Body:
Check the version of react-router-dom in package.json

If its version is greater than 4 then in your file import BrowserRouter :-

import { BrowserRouter as Router, Route } from 'react-router-dom'

else if its version is less than 4 then import Router :-

import { Router, Route } from 'react-router-dom'


问:
How to return to the main menu in a loop?
I'm wondering if this is the right approach to looping back to the main menu in python. After selecting a choice and completing a task, the script needs to return back to the main menu instead of exiting.

```<code>#!/usr/bin/python

def mainmenu():
    print ('1. Scan')
    print ('2. Ping')
    print ('3. Exit')
    print

    choice = int(raw_input('> Enter your choice: '))

    if choice == 1:
       print ('Starting Scan\n')
       mainmenu()
    elif choice == 2:
       print ('Starting Ping\n')
       mainmenu()
    elif choice == 3:
       print ('Exiting\n')
       exit(0)
mainmenu()
</code>```

This kind of works, but don't think it's the right way.

答:
I would suggest putting the whole function in a while loop to repeat the process.

```<code>#!/usr/bin/python

def mainmenu():
    while(True):
        print ('1. Scan')
        print ('2. Ping')
        print ('3. Exit')
        print

        choice = int(input('> Enter your choice: '))

        if choice == 1:
            print ('Starting Scan\n')
        elif choice == 2:
            print ('Starting Ping\n')
        elif choice == 3:
            print ('Exiting\n')
            exit(0)
mainmenu()
</code>```

Using recursion is not recommended for such programs.

Body:
I'm wondering if this is the right approach to looping back to the main menu in python. After selecting a choice and completing a task, the script needs to return back to the main menu instead of exiting.

#!/usr/bin/python

def mainmenu():
    print ('1. Scan')
    print ('2. Ping')
    print ('3. Exit')
    print

    choice = int(raw_input('> Enter your choice: '))

    if choice == 1:
       print ('Starting Scan\n')
       mainmenu()
    elif choice == 2:
       print ('Starting Ping\n')
       mainmenu()
    elif choice == 3:
       print ('Exiting\n')
       exit(0)
mainmenu()

This kind of works, but don't think it's the right way.

Body:
I would suggest putting the whole function in a while loop to repeat the process.

#!/usr/bin/python

def mainmenu():
    while(True):
        print ('1. Scan')
        print ('2. Ping')
        print ('3. Exit')
        print

        choice = int(input('> Enter your choice: '))

        if choice == 1:
            print ('Starting Scan\n')
        elif choice == 2:
            print ('Starting Ping\n')
        elif choice == 3:
            print ('Exiting\n')
            exit(0)
mainmenu()

Using recursion is not recommended for such programs.


问:
Wait until button is clicked in Selenium WebDriver to click on next button?
I'm at the point in my program where it will click a button within the browser and within that page, another button should appear.  After that button appears, my program will immediately run the next action to click the next button.  I'm getting this error currently:

ElementNotVisibleException: Message: element not visible

Therefore, I'm assuming I'm calling the action to click the next button before that button appears.  My question is what would I do to make my program wait until I can click on the button, to click on the button?

```<code>driver.find_element_by_xpath('//*[@id="add-remove-buttons"]/input').click()
driver.find_element_by_xpath('//*[@id="cart"]/a[2]').click()
</code>```

This is what the code looks like at the bottom of my program.  I need to be able to wait until the second action is possible to complete the second action.  Thanks for all the help!

答:
As per your Question, we are trying to invoke click() method on both the buttons so we will induce ExplicitWait i.e. WebDriverWait with expected_conditions as element_to_be_clickable as follows :

```<code>firstButton = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH,"//*[@id='add-remove-buttons']/input"))
firstButton.click()
secondButton = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH,"//*[@id='cart']/a[2]"))
secondButton.click()
</code>```

Body:
I'm at the point in my program where it will click a button within the browser and within that page, another button should appear.  After that button appears, my program will immediately run the next action to click the next button.  I'm getting this error currently:

ElementNotVisibleException: Message: element not visible

Therefore, I'm assuming I'm calling the action to click the next button before that button appears.  My question is what would I do to make my program wait until I can click on the button, to click on the button?

driver.find_element_by_xpath('//*[@id="add-remove-buttons"]/input').click()
driver.find_element_by_xpath('//*[@id="cart"]/a[2]').click()

This is what the code looks like at the bottom of my program.  I need to be able to wait until the second action is possible to complete the second action.  Thanks for all the help!

Body:
As per your Question, we are trying to invoke click() method on both the buttons so we will induce ExplicitWait i.e. WebDriverWait with expected_conditions as element_to_be_clickable as follows :

firstButton = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH,"//*[@id='add-remove-buttons']/input"))
firstButton.click()
secondButton = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH,"//*[@id='cart']/a[2]"))
secondButton.click()


问:
Laravel get 500 internal server error
I had laravel project on share hosting, and my structure app is

```<code>/home/username

`->fontEndApps ( my laravel apps )`

`->backendApps ( my laravel apps )`

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

in public html I put the index.php, htaccess and admin folder, in admin folder there is index.php and htaccess

backend is working fine but the front end when I try to access www.domain.com/segment1 or www.domain.com/segment1/segment2 I always got 500 internal server error, and this is my htaccess file for front end and back end

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options +FollowSymLinks
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

please help me to figure out this problem

答: Make sure you have the Vendor folder uploaded in the server it can cause 500 error.

Title: Laravel get 500 internal server error

Body:
I had laravel project on share hosting, and my structure app is

/home/username

`->fontEndApps ( my laravel apps )`

`->backendApps ( my laravel apps )`

`->public_html`

in public html I put the index.php, htaccess and admin folder, in admin folder there is index.php and htaccess

backend is working fine but the front end when I try to access www.domain.com/segment1 or www.domain.com/segment1/segment2 I always got 500 internal server error, and this is my htaccess file for front end and back end

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options +FollowSymLinks
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

please help me to figure out this problem


问:
Way to have compiled python files in a separate folder?
Is it possible to have Python save the .pyc files to a separate folder location that is in sys.path?

```<code>/code
    foo.py
    foo.pyc
    bar.py
    bar.pyc
</code>```

To:

```<code>/code
   foo.py
   bar.py
/code_compiled
   foo.pyc
   bar.pyc
</code>```

I would like this because I feel it'd be more organized. Thanks for any help you can give me.

答:
"I feel it'd be more organized"  Why?  How?  What are you trying to accomplish?

The point of saving the compiler output is to save a tiny bit of load time when the module gets imported.  Why make this more complex?  If you don't like the .pyc's, then run a "delete all the .pyc's" script periodically.

They aren't essential; they're helpful.  Why turn off that help?

This isn't C, C++ or Java where the resulting objects are essential.  This is just a cache that Python happens to use.  We mark them as "ignored" in Subversion so they don't accidentally wind up getting checked in.

OwnerDisplayName: Evan Fosmark

Body:
Is it possible to have Python save the .pyc files to a separate folder location that is in sys.path?

/code
    foo.py
    foo.pyc
    bar.py
    bar.pyc

To:

/code
   foo.py
   bar.py
/code_compiled
   foo.pyc
   bar.pyc

I would like this because I feel it'd be more organized. Thanks for any help you can give me.


问:
What's the deal with Jaxer?
Remember Aptana Jaxer? It plugs into Apache and allows using JavaScript on the server-side as an alternative to languages such as PHP. It comes with a consistens and slick API for filesystem access, database connectivity, socket communication and whatever else you need.

I wonder why hasn't this been more widely adopted, why aren't more people using this? Javascript is a modern and clean programming language as opposed to PHP and the Jaxer API is just so much more consistent and neat. No offense, but the PHP API is just such a big mess with all its inconsistencies and its inconsequent function naming convention.

Jaxer also makes client/server communication really convenient with its runat="server-proxy" where you can directly call server-side function from within your client-side script and Jaxer takes care of all the XML HTTP request stuff.

So I would just really like to here what people think about it or why there's hardly anyone using it. Not wanting to start a flamewar here, I'm just curious.

Thanks

答:
Personally I liked Jaxer, because you easily could use the same code client and server-side without duplication (such as form validation), however I didn't like, that you had hardly any control over the generated pages, which where propped full of JavaScript even for the most trivial page and made the pages highly depended on JavaScript, which made unobtrusive JavaScript virtually impossible.

So I guess for purely JavaScript-based web apps it's ok, however now there is for example Google Web Toolkit, which is much more powerful, which basicly also allows you to use one language client and server-side.

Title: What's the deal with Jaxer?


问:
How to create single bundle of js files using webpack module bundler - Angular
I'm newbie to angularjs, In my project Ihave so many dependencies js files which is effecting my performance of project for each file there is separate request and hence with so many files i have end up with lot of requests..I'm looking to create single bundle of these files using webpack ...I'm looking for steps to create single using webpack? </p>

答:
If you are new to webpack please go through this webpack video tutorial.

Assuming you are using Angular 2/4/5 you can follow the below steps.

Step 1 :- install webpack by using node command.

```<code>npm install -g webpack
</code>```

Step 2 :- Create "webpack.config.js" and define how you want to bundle. This file is a webpack configuration file which defines the road map of your bundling. For example in the below config i am creating three bundles. "Startup" , "SupplierModule" and "CustomerModule". These bundles will be  compiled to the "dist" directory. In case you are new to webpack go through this webpack article

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

module.exports = {
    entry: {
        CustomerModule: "./Modules/CustomerModule.js",
        SupplierModule: "./Modules/SupplierModule.js",
        Startup: [ "./node_modules/core-js/client/shim.min.js",
                    "./node_modules/zone.js/dist/zone.js",
                    "./node_modules/reflect-metadata/Reflect.js",
                    "./Startup.js"
                   ]
    },
    output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/dist/",
        filename: "[name].bundle.js"
    }
};
</code>```

Step 3 :- Go the folder where you have made this file and execute webpack if you want to compress the file you can use "-p" option.

```<code>webpack -p
</code>```

If everything goes well you should see  something as shown below. You can see he has created three bundles as per the road map of the "webpack" config file defined in the previous step.

Step 4 :- In your angular index page , remove all JS files and add reference to the files from dist folder. Please note the main angular page only need the reference to startup.js and other modules will be loaded on demand.

In case you are using lazy loading using systemJS then the below three steps are also needed.

Step 1: – Get “es6-promise-loader” and replace Systemjs

Replace systemjs with es6 promise loader. So do a NPM and get it.

Step 2 :- Install node types

```<code>npm install -save @types/node
</code>```

Step 3 :- your dynamic module loader code will also change now. So the routing code becomes something as shown below

```<code>export const MainRoutes = [
    { path: 'Customer', loadChildren: () => require('es6-promise-
loader!../Modules/CustomerModule')('CustomerModule')},
    { path: 'Supplier', loadChildren: () => require('es6-promise-
loader!../Modules/SupplierModule')('SupplierModule') },
    { path: '', component: HomeComponent },
    { path: 'Shell.html', component: HomeComponent },
    { path: 'Help', component: HelpComponent, outlet: "helpoutlet" }

];
</code>```

Do webpack again to bundle the files.If you see the bundling output you can see 0.bundle.js , 1.bundlejs which is sign that your lazy loading bundling is working well.

Happy bundling...

Body:
If you are new to webpack please go through this webpack video tutorial.

Assuming you are using Angular 2/4/5 you can follow the below steps.

Step 1 :- install webpack by using node command.

npm install -g webpack

Step 2 :- Create "webpack.config.js" and define how you want to bundle. This file is a webpack configuration file which defines the road map of your bundling. For example in the below config i am creating three bundles. "Startup" , "SupplierModule" and "CustomerModule". These bundles will be  compiled to the "dist" directory. In case you are new to webpack go through this webpack article

var path = require('path');

module.exports = {
    entry: {
        CustomerModule: "./Modules/CustomerModule.js",
        SupplierModule: "./Modules/SupplierModule.js",
        Startup: [ "./node_modules/core-js/client/shim.min.js",
                    "./node_modules/zone.js/dist/zone.js",
                    "./node_modules/reflect-metadata/Reflect.js",
                    "./Startup.js"
                   ]
    },
    output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/dist/",
        filename: "[name].bundle.js"
    }
};

Step 3 :- Go the folder where you have made this file and execute webpack if you want to compress the file you can use "-p" option.

webpack -p

If everything goes well you should see  something as shown below. You can see he has created three bundles as per the road map of the "webpack" config file defined in the previous step.

Step 4 :- In your angular index page , remove all JS files and add reference to the files from dist folder. Please note the main angular page only need the reference to startup.js and other modules will be loaded on demand.

In case you are using lazy loading using systemJS then the below three steps are also needed.

Step 1: – Get “es6-promise-loader” and replace Systemjs

Replace systemjs with es6 promise loader. So do a NPM and get it.

Step 2 :- Install node types

npm install -save @types/node

Step 3 :- your dynamic module loader code will also change now. So the routing code becomes something as shown below

export const MainRoutes = [
    { path: 'Customer', loadChildren: () => require('es6-promise-
loader!../Modules/CustomerModule')('CustomerModule')},
    { path: 'Supplier', loadChildren: () => require('es6-promise-
loader!../Modules/SupplierModule')('SupplierModule') },
    { path: '', component: HomeComponent },
    { path: 'Shell.html', component: HomeComponent },
    { path: 'Help', component: HelpComponent, outlet: "helpoutlet" }

];

Do webpack again to bundle the files.If you see the bundling output you can see 0.bundle.js , 1.bundlejs which is sign that your lazy loading bundling is working well.

Happy bundling...


问:
Angular4: ERROR TypeError: Cannot read property 'length' of undefined while accessing length property
i'am working on a assignment of angular 4, i'am new to it, i'am applying pagination for mat-table,getting some problem in it,   while i'am printing data to console it is displaying as below

while i'am trying to apply dataSource.data.length, getting below error.

```<code>WellComponent.html:57 ERROR TypeError: Cannot read property 'length' of undefined
    at Object.View_WellComponent_0._co [as updateDirectives] (WellComponent.html:60)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
    at checkAndUpdateView (core.es5.js:12255)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)
</code>```

Can i get help in this aspect, how should i access that length property.

Component:

```<code>    import { MatPaginator } from '@angular/material';
    import { DataSource } from '@angular/cdk/collections';
    import { Component, OnInit,ViewChild,ChangeDetectorRef } from '@angular/core';
    import { WellService } from '../services/well.service';
    import { Well } from '../well/well';
    import {  Observable  } from 'rxjs/Rx';
    import { BehaviorSubject } from  'rxjs/BehaviorSubject';
    import 'rxjs/add/operator/startWith';
    import 'rxjs/add/observable/merge';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-well',
      templateUrl: './well.component.html',
      styleUrls: ['./well.component.css'],
      providers:[WellService]
    })

    export class WellComponent implements OnInit {
      title = 'Wells';
      header:string;
      displayedColumns = ['active', 'company', 'country', 'well','wellbore'];
      public dataSource: WellDataSource | any;
      obs:any;

      @ViewChild(MatPaginator) paginator : MatPaginator;

      constructor(private wellService:WellService) {

        this.header='assets/images/BHI_header_logo_bd.png'

       }

       ngOnInit() {
        this.obs = this.wellService.getWells();
        this.dataSource = new WellDataSource(this.obs, this.paginator);

      }

      }

      export class WellDataSource extends DataSource<any> {

      constructor(private _obs: any, private _paginator: MatPaginator) {
        super();
      }

      connect(): Observable<any[]> {
        const displayDataChanges = [
          this._obs,
          this._paginator.page,
        ];

        return this._obs.flatMap(x => {
          return Observable.merge(...displayDataChanges).map(() => {
            const data = x.slice();
            console.log(data);
            const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
            console.log(startIndex);
            console.log(this._paginator.pageSize)
            console.log(this._obs);
            console.log(x.slice());
            return data.splice(startIndex, this._paginator.pageSize);
          });
        })
      }

        disconnect() {}
      }

**HTML:**

<div>
  <div class="image"><img  [src]="header" ></div>

  <div class="w3-display-left">
  <nav>
     <li><a routerLink="/wells" routerLinkActive="active">My Wells</a></li>
      <li><a routerLink="/dev" routerLinkActive="active">Well Management</a></li>
      <li><a routerLink="/dev" routerLinkActive="active">Admin Tools</a></li>
  </nav>
  <div class="w3-display-right">
    <button mat-button>Reset</button>
    <button mat-button>Refresh</button>
    <button mat-button>View Wireline</button>
    <button mat-button>Chat</button>
    <button mat-button>View Seismic</button>
    <button mat-button>Alerts</button>

  </div>

  <br>
  <br>
   <div>
        <mat-table #table [dataSource]="dataSource">
    <!-- Active -->
    <ng-container matColumnDef="active">
      <mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.active}} </mat-cell>
    </ng-container>

    <!-- Company -->
    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.company}} </mat-cell>
    </ng-container>

    <!-- Country -->
    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef>Country</mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.country}} </mat-cell>
    </ng-container>

    <!-- Well -->
    <ng-container matColumnDef="well">
      <mat-header-cell *matHeaderCellDef> Well </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well}} </mat-cell>
    </ng-container>

        <!-- Wellbore -->
        <ng-container matColumnDef="wellbore">
          <mat-header-cell *matHeaderCellDef> Wellbore </mat-header-cell>
          <mat-cell *matCellDef="let row"> {{row.wellbore}} </mat-cell>
        </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
  <mat-paginator #paginator
  [length]="dataSource.data.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>
</div>
</div>
<div>
    <router-outlet></router-outlet>
    </div>
</code>```

答:
The error is because of you are trying to access data before it available

Try to use safe operator :

```<code>dataSource.data?.length
</code>```

OR

make some initialisation inside constructor

```<code>dataSource.data = [];
</code>```

As per your code change [length]="dataSource.data.length" to  [length]="obs.data?.length" , like this :

```<code><mat-paginator #paginator
  [length]="obs.data?.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>
</code>```

Body:
i'am working on a assignment of angular 4, i'am new to it, i'am applying pagination for mat-table,getting some problem in it,   while i'am printing data to console it is displaying as below

while i'am trying to apply dataSource.data.length, getting below error.

WellComponent.html:57 ERROR TypeError: Cannot read property 'length' of undefined
    at Object.View_WellComponent_0._co [as updateDirectives] (WellComponent.html:60)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
    at checkAndUpdateView (core.es5.js:12255)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)

Can i get help in this aspect, how should i access that length property.

Component:

    import { MatPaginator } from '@angular/material';
    import { DataSource } from '@angular/cdk/collections';
    import { Component, OnInit,ViewChild,ChangeDetectorRef } from '@angular/core';
    import { WellService } from '../services/well.service';
    import { Well } from '../well/well';
    import {  Observable  } from 'rxjs/Rx';
    import { BehaviorSubject } from  'rxjs/BehaviorSubject';
    import 'rxjs/add/operator/startWith';
    import 'rxjs/add/observable/merge';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-well',
      templateUrl: './well.component.html',
      styleUrls: ['./well.component.css'],
      providers:[WellService]
    })

    export class WellComponent implements OnInit {
      title = 'Wells';
      header:string;
      displayedColumns = ['active', 'company', 'country', 'well','wellbore'];
      public dataSource: WellDataSource | any;
      obs:any;

      @ViewChild(MatPaginator) paginator : MatPaginator;

      constructor(private wellService:WellService) {

        this.header='assets/images/BHI_header_logo_bd.png'

       }

       ngOnInit() {
        this.obs = this.wellService.getWells();
        this.dataSource = new WellDataSource(this.obs, this.paginator);

      }

      }

      export class WellDataSource extends DataSource<any> {

      constructor(private _obs: any, private _paginator: MatPaginator) {
        super();
      }

      connect(): Observable<any[]> {
        const displayDataChanges = [
          this._obs,
          this._paginator.page,
        ];

        return this._obs.flatMap(x => {
          return Observable.merge(...displayDataChanges).map(() => {
            const data = x.slice();
            console.log(data);
            const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
            console.log(startIndex);
            console.log(this._paginator.pageSize)
            console.log(this._obs);
            console.log(x.slice());
            return data.splice(startIndex, this._paginator.pageSize);
          });
        })
      }

        disconnect() {}
      }

**HTML:**

My Wells

Well Management

Admin Tools

    <button mat-button>Reset</button>
    <button mat-button>Refresh</button>
    <button mat-button>View Wireline</button>
    <button mat-button>Chat</button>
    <button mat-button>View Seismic</button>
    <button mat-button>Alerts</button>

        <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="active">
      <mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.active}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.company}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef>Country</mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.country}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="well">
      <mat-header-cell *matHeaderCellDef> Well </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well}} </mat-cell>
    </ng-container>

        <ng-container matColumnDef="wellbore">
          <mat-header-cell *matHeaderCellDef> Wellbore </mat-header-cell>
          <mat-cell *matCellDef="let row"> {{row.wellbore}} </mat-cell>
        </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
  <mat-paginator #paginator
  [length]="dataSource.data.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>

    <router-outlet></router-outlet>

Body:
The error is because of you are trying to access data before it available

Try to use safe operator :

dataSource.data?.length

OR

make some initialisation inside constructor

dataSource.data = [];

As per your code change [length]="dataSource.data.length" to  [length]="obs.data?.length" , like this :

<mat-paginator #paginator
  [length]="obs.data?.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>


问:
Adding user Authentication using Applescript
I want to add user authentication in my applescript to perform some task. If the username and password is correct then only the next task should happen. How to do this using applescript?</p>

答:
If you are wanting a username and password input then use this:  </p>

```<code>set a to the text returned of (display dialog "Please enter your username" default answer "")

set b to the text returned of (display dialog "Please enter your password" default answer "")

if a="username" then --set the username to your username

if b="password" then --set the password to your password

 --what ever is after your password protection

end if

end if
</code>```

Body:
If you are wanting a username and password input then use this:

set a to the text returned of (display dialog "Please enter your username" default answer "")

set b to the text returned of (display dialog "Please enter your password" default answer "")

if a="username" then --set the username to your username

if b="password" then --set the password to your password

 --what ever is after your password protection

end if

end if


问:
Convert specific number of rows to columns in R and repeat the process for a large dataset
I'm having a dataset of 15 million rows with single column. It looks like,

```<code>x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
</code>```

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

答:
Expand the length to the next block of 4 values, and put it in a matrix:</p>

```<code>matrix(`length<-`(dat$x_raw, (nrow(dat) %/% 4 + 1) * 4), ncol=4, byrow=TRUE)

#     [,1] [,2] [,3] [,4]
#[1,] "A1" "A2" "A3" "A4"
#[2,] "B1" "B2" "B3" "B4"
#[3,] "C1" "C2" NA   NA
</code>```

Body:
I'm having a dataset of 15 million rows with single column. It looks like,

x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

Body:
Expand the length to the next block of 4 values, and put it in a matrix:

matrix(`length<-`(dat$x_raw, (nrow(dat) %/% 4 + 1) * 4), ncol=4, byrow=TRUE)

#     [,1] [,2] [,3] [,4]
#[1,] "A1" "A2" "A3" "A4"
#[2,] "B1" "B2" "B3" "B4"
#[3,] "C1" "C2" NA   NA


问:
How to stretch header across the screen
I have banner image that stretches the screen. I was told that the best
way to stretch is to load an image at the appropriate width. So doesn't that
mean you need to use JavaScript to detect the screen resolution then load the appropriate image? However JS maybe disabled. Are there alternatives?</p>

答: Set the image width in percentage. Notice the actual percentage will relate to the img's parents container.</p>

Title: How to stretch header across the screen


问:
Database trigger, retrieving data from other nodes. Firebase Cloud functions
i have a function that will trigger when the 'location' is updated under 'users'. I want to be able to iterate through all the 'users' and be able to compare their 'location's.

Right now when i console.log event.data.val() i just get the 'location' data.
How do i go up a level and see the other 'users'

```<code>exports.getNearest = functions.database.ref('/users/{pushId}/location').onWrite(event =>{

console.log(event.data.val());
return;
}
);
</code>```

my database is structured like this:

https://gyazo.com/9d7a4ddba2cd311b21d78d7622b59c36

答: event.data.ref is a Reference where your function triggered.  This means event.data.ref.parent is a reference to the parent node of that location. You can reach the root of your database using event.data.ref.root.  If you need full read and write access regardless of the user who invoked the function, you may also want to use event.adminRef instead of ref.</p>

Body:
i have a function that will trigger when the 'location' is updated under 'users'. I want to be able to iterate through all the 'users' and be able to compare their 'location's.

Right now when i console.log event.data.val() i just get the 'location' data.
How do i go up a level and see the other 'users'

exports.getNearest = functions.database.ref('/users/{pushId}/location').onWrite(event =>{

console.log(event.data.val());
return;
}
);

my database is structured like this:

https://gyazo.com/9d7a4ddba2cd311b21d78d7622b59c36