问:
Python script to parse first image of search engine from list of keywords in CSV
I have this code below that is supposed to save an image in my local directory from a search engine. It does, however it saves it as a hex file. I can mess with the code and get lucky, but I hope someone here can give me the best solution.

If I open the hex file in notepad++ I notice the first row of the hex file says "‰PNG". I manually changed the file extension and the correct image shows up.

That is my first issue with this code. I'm just trying to get a better understanding of it.

I also wanted to throw in a list of key words to parse and return whatever number of images, default is 1 according to the script. Is it possible to tell python to read through a column of search Queries and save the image files as the search query? If it's easier, I use mysql workbench to work on my database. I have a column that I want to execute this script on but maybe instead return the filename whilst saving it into a local directory.

For example, my first search was for "HP C9730A" which is a printer toner product. How can I send a list of part numbers may it be a csv or json array and return the parsed images saved exactly like the keywords used? So filename would be "HP C9730A.jpg"

I noticed the clause in the script states:

```<code><b>else</b> 'jpg'
</code>```

The first image on google using my example as mentioned before is a PNG file. Is this why my file isn't saving?

Either way, can you help? me not only to save jpg or png images, but also save them as the search keywords with possible batch processing using csv or json array with many different keywords.

```<code>import argparse
import json
import itertools
import logging
import re
import os
import uuid
import sys
from urllib2 import urlopen, Request

from bs4 import BeautifulSoup

def configure_logging():
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter('[%(asctime)s %(levelname)s %(module)s]: %(message)s'))
    logger.addHandler(handler)
    return logger

logger = configure_logging()

REQUEST_HEADER = {
    'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"}

def get_soup(url, header):
    response = urlopen(Request(url, headers=header))
    return BeautifulSoup(response, 'html.parser')

def get_query_url(query):
    return "https://www.google.co.in/search?q=%s&source=lnms&tbm=isch" % query

def extract_images_from_soup(soup):
    image_elements = soup.find_all("div", {"class": "rg_meta"})
    metadata_dicts = (json.loads(e.text) for e in image_elements)
    link_type_records = ((d["ou"], d["ity"]) for d in metadata_dicts)
    return link_type_records

def extract_images(query, num_images):
    url = get_query_url(query)
    logger.info("Souping")
    soup = get_soup(url, REQUEST_HEADER)
    logger.info("Extracting image urls")
    link_type_records = extract_images_from_soup(soup)
    return itertools.islice(link_type_records, num_images)

def get_raw_image(url):
    req = Request(url, headers=REQUEST_HEADER)
    resp = urlopen(req)
    return resp.read()

def save_image(raw_image, image_type, save_directory):
    extension = image_type if image_type else 'jpg'
    file_name = uuid.uuid4().hex
    save_path = os.path.join(save_directory, file_name)
    with open(save_path, 'wb') as image_file:
        image_file.write(raw_image)

def download_images_to_dir(images, save_directory, num_images):
    for i, (url, image_type) in enumerate(images):
        try:
            logger.info("Making request (%d/%d): %s", i, num_images, url)
            raw_image = get_raw_image(url)
            save_image(raw_image, image_type, save_directory)
        except Exception as e:
            logger.exception(e)

def run(query, save_directory, num_images=100):
    query = '+'.join(query.split())
    logger.info("Extracting image links")
    images = extract_images(query, num_images)
    logger.info("Downloading images")
    download_images_to_dir(images, save_directory, num_images)
    logger.info("Finished")

def main():
    parser = argparse.ArgumentParser(description='Scrape Google images')
    parser.add_argument('-s', '--search', default='bananas', type=str, help='search term')
    parser.add_argument('-n', '--num_images', default=1, type=int, help='num images to save')
    parser.add_argument('-d', '--directory', default='/Users/Images/', type=str, help='save directory')
    args = parser.parse_args()
    run(args.search, args.directory, args.num_images)

if __name__ == '__main__':
    main()
</code>```

答:
As for saving the images as actual jpg or png files, looks like adding this

" + "." + extension"

The full row now looks like this:

save_path = os.path.join(save_directory, file_name + "." + extension)

fixed the issue as to saving the image in the actual extension as promised by the script.

Second Update:

```<code>import sys
</code>```

this import was already included in the script I found. I found through this site that I can return

```<code>sys.argv[2]
</code>```

So according to sys which is -The list of command line arguments passed to a Python script. I included this to the script to return the uuid alongside the actual search terms like so:

```<code>file_name = uuid.uuid4().hex + "-" + sys.argv[2]
</code>```

But now, as for running this script through mysql workbench on a table that has a list of queries to parse- I'm not sure how long it will take me to figure this one out. Any help would be appreciated. I would like to run this script on a large list of queries, without getting kicked off the search engine.

Body:
I have this code below that is supposed to save an image in my local directory from a search engine. It does, however it saves it as a hex file. I can mess with the code and get lucky, but I hope someone here can give me the best solution.

If I open the hex file in notepad++ I notice the first row of the hex file says "‰PNG". I manually changed the file extension and the correct image shows up.

That is my first issue with this code. I'm just trying to get a better understanding of it.

I also wanted to throw in a list of key words to parse and return whatever number of images, default is 1 according to the script. Is it possible to tell python to read through a column of search Queries and save the image files as the search query? If it's easier, I use mysql workbench to work on my database. I have a column that I want to execute this script on but maybe instead return the filename whilst saving it into a local directory.

For example, my first search was for "HP C9730A" which is a printer toner product. How can I send a list of part numbers may it be a csv or json array and return the parsed images saved exactly like the keywords used? So filename would be "HP C9730A.jpg"

I noticed the clause in the script states:

else 'jpg'

The first image on google using my example as mentioned before is a PNG file. Is this why my file isn't saving?

Either way, can you help? me not only to save jpg or png images, but also save them as the search keywords with possible batch processing using csv or json array with many different keywords.

import argparse
import json
import itertools
import logging
import re
import os
import uuid
import sys
from urllib2 import urlopen, Request

from bs4 import BeautifulSoup

def configure_logging():
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter('[%(asctime)s %(levelname)s %(module)s]: %(message)s'))
    logger.addHandler(handler)
    return logger

logger = configure_logging()

REQUEST_HEADER = {
    'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"}

def get_soup(url, header):
    response = urlopen(Request(url, headers=header))
    return BeautifulSoup(response, 'html.parser')

def get_query_url(query):
    return "https://www.google.co.in/search?q=%s&source=lnms&tbm=isch" % query

def extract_images_from_soup(soup):
    image_elements = soup.find_all("div", {"class": "rg_meta"})
    metadata_dicts = (json.loads(e.text) for e in image_elements)
    link_type_records = ((d["ou"], d["ity"]) for d in metadata_dicts)
    return link_type_records

def extract_images(query, num_images):
    url = get_query_url(query)
    logger.info("Souping")
    soup = get_soup(url, REQUEST_HEADER)
    logger.info("Extracting image urls")
    link_type_records = extract_images_from_soup(soup)
    return itertools.islice(link_type_records, num_images)

def get_raw_image(url):
    req = Request(url, headers=REQUEST_HEADER)
    resp = urlopen(req)
    return resp.read()

def save_image(raw_image, image_type, save_directory):
    extension = image_type if image_type else 'jpg'
    file_name = uuid.uuid4().hex
    save_path = os.path.join(save_directory, file_name)
    with open(save_path, 'wb') as image_file:
        image_file.write(raw_image)

def download_images_to_dir(images, save_directory, num_images):
    for i, (url, image_type) in enumerate(images):
        try:
            logger.info("Making request (%d/%d): %s", i, num_images, url)
            raw_image = get_raw_image(url)
            save_image(raw_image, image_type, save_directory)
        except Exception as e:
            logger.exception(e)

def run(query, save_directory, num_images=100):
    query = '+'.join(query.split())
    logger.info("Extracting image links")
    images = extract_images(query, num_images)
    logger.info("Downloading images")
    download_images_to_dir(images, save_directory, num_images)
    logger.info("Finished")

def main():
    parser = argparse.ArgumentParser(description='Scrape Google images')
    parser.add_argument('-s', '--search', default='bananas', type=str, help='search term')
    parser.add_argument('-n', '--num_images', default=1, type=int, help='num images to save')
    parser.add_argument('-d', '--directory', default='/Users/Images/', type=str, help='save directory')
    args = parser.parse_args()
    run(args.search, args.directory, args.num_images)

if __name__ == '__main__':
    main()

Body:
As for saving the images as actual jpg or png files, looks like adding this

" + "." + extension"

The full row now looks like this:

save_path = os.path.join(save_directory, file_name + "." + extension)

fixed the issue as to saving the image in the actual extension as promised by the script.

Second Update:

import sys

this import was already included in the script I found. I found through this site that I can return

sys.argv[2]

So according to sys which is -The list of command line arguments passed to a Python script. I included this to the script to return the uuid alongside the actual search terms like so:

file_name = uuid.uuid4().hex + "-" + sys.argv[2]

But now, as for running this script through mysql workbench on a table that has a list of queries to parse- I'm not sure how long it will take me to figure this one out. Any help would be appreciated. I would like to run this script on a large list of queries, without getting kicked off the search engine.


来源: stackexchange

问:
Comparing a Set with a Big Collection of Sets

How to match a Set with a Big Collection of Sets stored in database.
[The collection may have millions of Sets].
Detailed Statement

[Prerequisite] A cluster has special property which is a set of attribute.

I will get an entity having a set of attribute.

If i have any existing cluster with exact same set of attribute (neither more nor less) then i will add the entity to that cluster. Else i will create a cluster having property as attribute set of new entity.

Above is the process of the clustering.
The problem is how i should store the data so that the system can run smoothly on very large dataset without performance issue.

What kind of database should i use for this? in SQL or NoSQL

What Possible Solution i thought of:

[MySQL]Store the attributes with cluster in a table so that clusterId to attributeId has m:n relation.[table cluster_attribute].
whenever an entity comes.
we run.

select clusterId,count(1) from cluster_attribute where attributeId in("comma separated IDs of attributes");

But this will not be good since we may find a long list of clusterId's which fullfills the above query.

In the same above table we perform query like.

```<code>select clusterId,count(1) cnt from cluster_attributes a
inner join cluster_attributes b on a.cluesterId=b.cluesterId
where b.attributeId in("comma separated IDs of attributes")
group by clusterId
having cnt = @sizeOfEntityAttributeSet;
</code>```

This will scan much rows resulting slow query.

We store attribute as sorted Concatenation of attribute by any character | and make this column indexed.This way we will be able to query faster.But when ever i need to know which clusters have a certain attribute (A1), my query will go slow since i will need to use regexp search in mysql.

Items in set is non-duplicate.that is [a1,b1,c1] is valid while [a1,b1,a1,c1] is not.

millions of sets, each will hundreds of items.

答:
Have 2 columns in the table for searching.  One is the exact, complete, list of the values, sorted.  It's a long string, probably TEXT.  The other is a hash of that string.  I might suggest MD5, then chop to 32 bits and put into INT UNSIGNED (or BINARY(4)).  INDEX this column, but not UNIQUE.

Now, to check for existence, do likewise with the incoming 'set' -- build the string, and compute the hash.  Look up the hashed value in the table.  It will give you only a few rows, including some duds.  Double check with the long string.

```<code>WHERE hash = $hash
  AND str = '$str'
</code>```

The lookup will be quite fast.  The prep work (building the sorted string and computing the hash) will not be too difficult.  It will be quite easy to code in, say, PHP.

Caveats:

This works only for an exact match of the set.

It scales quite well.  If you have more than, say, a billion sets, then a 32-bit hash won't be big adequate.  (But BIGINT and a longer BINARY would work.)

ContentLicense: CC BY-SA 4.0

Body:
How to match a Set with a Big Collection of Sets stored in database.
[The collection may have millions of Sets].
Detailed Statement

[Prerequisite] A cluster has special property which is a set of attribute.

I will get an entity having a set of attribute.

If i have any existing cluster with exact same set of attribute (neither more nor less) then i will add the entity to that cluster. Else i will create a cluster having property as attribute set of new entity.

Above is the process of the clustering.
The problem is how i should store the data so that the system can run smoothly on very large dataset without performance issue.

What kind of database should i use for this? in SQL or NoSQL

What Possible Solution i thought of:

[MySQL]Store the attributes with cluster in a table so that clusterId to attributeId has m:n relation.[table cluster_attribute].
whenever an entity comes.
we run.

select clusterId,count(1) from cluster_attribute where attributeId in("comma separated IDs of attributes");

But this will not be good since we may find a long list of clusterId's which fullfills the above query.

In the same above table we perform query like.

select clusterId,count(1) cnt from cluster_attributes a
inner join cluster_attributes b on a.cluesterId=b.cluesterId
where b.attributeId in("comma separated IDs of attributes")
group by clusterId
having cnt = @sizeOfEntityAttributeSet;

This will scan much rows resulting slow query.

We store attribute as sorted Concatenation of attribute by any character | and make this column indexed.This way we will be able to query faster.But when ever i need to know which clusters have a certain attribute (A1), my query will go slow since i will need to use regexp search in mysql.

Items in set is non-duplicate.that is [a1,b1,c1] is valid while [a1,b1,a1,c1] is not.

millions of sets, each will hundreds of items.

Body:
Have 2 columns in the table for searching.  One is the exact, complete, list of the values, sorted.  It's a long string, probably TEXT.  The other is a hash of that string.  I might suggest MD5, then chop to 32 bits and put into INT UNSIGNED (or BINARY(4)).  INDEX this column, but not UNIQUE.

Now, to check for existence, do likewise with the incoming 'set' -- build the string, and compute the hash.  Look up the hashed value in the table.  It will give you only a few rows, including some duds.  Double check with the long string.

WHERE hash = $hash
  AND str = '$str'

The lookup will be quite fast.  The prep work (building the sorted string and computing the hash) will not be too difficult.  It will be quite easy to code in, say, PHP.

Caveats:

This works only for an exact match of the set.

It scales quite well.  If you have more than, say, a billion sets, then a 32-bit hash won't be big adequate.  (But BIGINT and a longer BINARY would work.)

ContentLicense: CC BY-SA 3.0


问:
Does Bison allow "?" in its syntax
I am trying to write Grammar for java specification
for example:-

```<code>COMPILATION_UNIT: PACKAGE_DEC? IMPORT_DECS? TYPE_DECS?
</code>```

but it doesn't work
I have the following error:

invalid character: `?'

for each question mark I use in my file.y

I know that Bison has special characters and it should handle it

Please help

答:
As you have seen, bison does not implement the ? regular expression optionality operator. Nor does it implement +  or * repetition operators. That's because the right-hand sides of productions in contex-free grammars are not regular expressions.

Yacc/bison context-free grammars do allow the | alternation operator, but as an abbreviation:

```<code>a : b | c
</code>```

Is exactly the same as writing

```<code>a : b
a : c
</code>```

and semantic actions only apply to the alternative in which  they are specified, so that

```<code>a : b | c { /* C action; */ }
</code>```

Is equivalent to:

```<code>a : b    { /* Implicit default action*/ }
a : c    { /* C action; */ }
</code>```

It is tempting to create X_opt non-terminals to capture the semantics of X?:

```<code>X_opt: X | %empty { $$ = default_value; }
</code>```

In many simple cases that will work fine, but there are also many grammars in which that introduces an unnecessary shift-reduce conflict. Consider, for example:

```<code>label: IDENT ':'
label_opt: label | %empty
statement: label_opt expr
</code>```

Since expr can start with an identifier, there is no way to know if an IDENT token starts a label or if it starts an expr following an empty label_opt. But LR(1) requires that the empty label_opt be reduced before the IDENT is consumed. So the above grammar is LR(2) and cannot be correctly parsed by an LR(1) parser.

That problem does not occur without the use of the label_opt shortcut:

```<code>label: IDENT ':'
statement: label expr
         | expr
</code>```

Since the parser now does not have decide between label and expr before the ':' is encountered.

Title: Does Bison allow "?" in its syntax

Body:
I am trying to write Grammar for java specification
for example:-

COMPILATION_UNIT: PACKAGE_DEC? IMPORT_DECS? TYPE_DECS?

but it doesn't work
I have the following error:

invalid character: `?'

for each question mark I use in my file.y

I know that Bison has special characters and it should handle it

Please help

Body:
As you have seen, bison does not implement the ? regular expression optionality operator. Nor does it implement +  or * repetition operators. That's because the right-hand sides of productions in contex-free grammars are not regular expressions.

Yacc/bison context-free grammars do allow the | alternation operator, but as an abbreviation:

a : b | c

Is exactly the same as writing

a : b
a : c

and semantic actions only apply to the alternative in which  they are specified, so that

a : b | c { /* C action; */ }

Is equivalent to:

a : b    { /* Implicit default action*/ }
a : c    { /* C action; */ }

It is tempting to create X_opt non-terminals to capture the semantics of X?:

X_opt: X | %empty { $$ = default_value; }

In many simple cases that will work fine, but there are also many grammars in which that introduces an unnecessary shift-reduce conflict. Consider, for example:

label: IDENT ':'
label_opt: label | %empty
statement: label_opt expr

Since expr can start with an identifier, there is no way to know if an IDENT token starts a label or if it starts an expr following an empty label_opt. But LR(1) requires that the empty label_opt be reduced before the IDENT is consumed. So the above grammar is LR(2) and cannot be correctly parsed by an LR(1) parser.

That problem does not occur without the use of the label_opt shortcut:

label: IDENT ':'
statement: label expr
         | expr

Since the parser now does not have decide between label and expr before the ':' is encountered.


问:
Spring framework Servlet.init() for servlet dispatcher threw exception
I have some simple spring code
my controller:

```<code>package com.luv2code.springdemo.mvc;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    // add an initbinder ... to convert trim input strings
    // remove leading and trailing whitespace
    // resolve issue for our validation

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {

        StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);

        dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
    }

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {

        theModel.addAttribute("customer", new Customer());

        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer,
            BindingResult theBindingResult) {

        System.out.println("Last name: |" + theCustomer.getLastName() + "|");

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        }
        else {
            return "customer-confirmation";
        }
    }
}
</code>```

my jsp:

```<code><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>

<head>
    <title>Customer Registration Form</title>

    <style>
        .error {color:red}
    </style>
</head>
<body>

<i>Fill out the form. Asterisk (*) means required.</i>
<br><br>

    <form:form action="processForm" modelAttribute="customer">

        First name: <form:input path="firstName" />

        <br><br>

        Last name (*): <form:input path="lastName" />
        <form:errors path="lastName" cssClass="error" />

        <br><br>

        Free passes  (*): <form:input path="freePasses" />
        <form:errors path="freePasses" cssClass="error" />

        <br><br>

        Postal Code: <form:input path="postalCode" />
        <form:errors path="postalCode" cssClass="error" />

        <br><br>

        <input type="submit" value="Submit" />

    </form:form>

</body>

</html>
</code>```

and my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>spring-mvc-demo</display-name>

    <!-- Spring MVC Configs -->

    <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

stacktrace:

```<code>Dec 06, 2017 11:43:25 PM org.springframework.web.servlet.FrameworkServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-mvc-demo] threw load() exception
java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 06, 2017 11:43:25 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3248 ms
Dec 06, 2017 11:43:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Dec 06 23:43:26 EST 2017]; root of context hierarchy
Dec 06, 2017 11:43:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-demo-servlet.xml]
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/showForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.showForm(org.springframework.ui.Model)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/processForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.processForm(com.luv2code.springdemo.mvc.Customer,org.springframework.validation.BindingResult)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/]}" onto public java.lang.String com.luv2code.springdemo.mvc.HomeController.showPage()
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
</code>```

but when I run on tomcat, it shows "HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception", and description "description The server encountered an internal error that prevented it from fulfilling this request."  Actually I tried some easy spring code earlier today, it works. And this time I tried to use validation api and copy some hibernate files to lib, but failed. Anyone could help me out? Thanks!

答:
I think you missed some information in web.xml file

```<code><web-app>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</webapp>
</code>```

Body:
I have some simple spring code
my controller:

package com.luv2code.springdemo.mvc;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    // add an initbinder ... to convert trim input strings
    // remove leading and trailing whitespace
    // resolve issue for our validation

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {

        StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);

        dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
    }

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {

        theModel.addAttribute("customer", new Customer());

        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer,
            BindingResult theBindingResult) {

        System.out.println("Last name: |" + theCustomer.getLastName() + "|");

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        }
        else {
            return "customer-confirmation";
        }
    }
}

my jsp:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <title>Customer Registration Form</title>

Fill out the form. Asterisk (*) means required.

    <form:form action="processForm" modelAttribute="customer">

        First name: <form:input path="firstName" />

        Last name (*): <form:input path="lastName" />
        <form:errors path="lastName" cssClass="error" />

        Free passes  (*): <form:input path="freePasses" />
        <form:errors path="freePasses" cssClass="error" />

        Postal Code: <form:input path="postalCode" />
        <form:errors path="postalCode" cssClass="error" />

        <input type="submit" value="Submit" />

    </form:form>

and my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>spring-mvc-demo</display-name>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

stacktrace:

Dec 06, 2017 11:43:25 PM org.springframework.web.servlet.FrameworkServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-mvc-demo] threw load() exception
java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 06, 2017 11:43:25 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3248 ms
Dec 06, 2017 11:43:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Dec 06 23:43:26 EST 2017]; root of context hierarchy
Dec 06, 2017 11:43:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-demo-servlet.xml]
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/showForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.showForm(org.springframework.ui.Model)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/processForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.processForm(com.luv2code.springdemo.mvc.Customer,org.springframework.validation.BindingResult)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/]}" onto public java.lang.String com.luv2code.springdemo.mvc.HomeController.showPage()
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager

but when I run on tomcat, it shows "HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception", and description "description The server encountered an internal error that prevented it from fulfilling this request."  Actually I tried some easy spring code earlier today, it works. And this time I tried to use validation api and copy some hibernate files to lib, but failed. Anyone could help me out? Thanks!

Body:
I think you missed some information in web.xml file

<web-app>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</webapp>


问:
Cannot Access Variable Intent on RecyclerView.Adapter<CustomAdapter.ViewHolder> when I declare on other my activity
Please someone help me, I want to display image, text, and detail product from RecyclerView.Adapter<CustomAdapter.ViewHolder> (First Intent) to My Detail Product Second Intent with intent. But I cannot access variable abc on First Intent when I declare in Second Intent.

Please someone help me.

this is RecyclerView.Adapter<CustomAdapter.ViewHolder> or First Intent

```<code>public class ViewHolder extends RecyclerView.ViewHolder{

    private ImageView image;
    private TextView text;
    private TextView nama;
    private TextView harga;

    public ViewHolder(final View itemView) {
        super(itemView);
        image = (ImageView) itemView.findViewById(R.id.image);
        text = (TextView) itemView.findViewById(R.id.text);
        nama= (TextView) itemView.findViewById(R.id.nama);
        harga = (TextView) itemView.findViewById(R.id.harga);

        itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent abc = new Intent(v.getContext(), DetailProduct.class);
                abc.putExtra("abb", my_data.get(getAdapterPosition()).getDetail());
                v.getContext().startActivity(abc);
            }
        });
    }
}
</code>```

And this is my Detail Product or Second Intent

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail_product);
    TextView resulttext = (TextView) findViewById(R.id.hasiltext);

    String text = abc.getStringExtra("abb"); // i cannot acces variable abc in detailproduct
    resulttext.setText(text);
}
</code>```

答:
The problem is in DetailActivity</p>

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_product);
        TextView resulttext = (TextView) findViewById(R.id.hasiltext);
        if(getTntent()!=null && getIntent().hasExtra("abb")){
        String text = getIntent().getStringExtra("abb");
        resulttext.setText(text);
    }
}
</code>```

Body:
Please someone help me, I want to display image, text, and detail product from RecyclerView.Adapter<CustomAdapter.ViewHolder> (First Intent) to My Detail Product Second Intent with intent. But I cannot access variable abc on First Intent when I declare in Second Intent.

Please someone help me.

this is RecyclerView.Adapter<CustomAdapter.ViewHolder> or First Intent

public class ViewHolder extends RecyclerView.ViewHolder{

    private ImageView image;
    private TextView text;
    private TextView nama;
    private TextView harga;

    public ViewHolder(final View itemView) {
        super(itemView);
        image = (ImageView) itemView.findViewById(R.id.image);
        text = (TextView) itemView.findViewById(R.id.text);
        nama= (TextView) itemView.findViewById(R.id.nama);
        harga = (TextView) itemView.findViewById(R.id.harga);

        itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent abc = new Intent(v.getContext(), DetailProduct.class);
                abc.putExtra("abb", my_data.get(getAdapterPosition()).getDetail());
                v.getContext().startActivity(abc);
            }
        });
    }
}

And this is my Detail Product or Second Intent

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail_product);
    TextView resulttext = (TextView) findViewById(R.id.hasiltext);

    String text = abc.getStringExtra("abb"); // i cannot acces variable abc in detailproduct
    resulttext.setText(text);
}

Body:
The problem is in DetailActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_product);
        TextView resulttext = (TextView) findViewById(R.id.hasiltext);
        if(getTntent()!=null && getIntent().hasExtra("abb")){
        String text = getIntent().getStringExtra("abb");
        resulttext.setText(text);
    }
}


问:
ImportError: No module named 'mysite' from omv of pi3
I want to work with Apache 2 and Django 2.0.
So I modified /etc/apache2/sites-sites-available/000-default.conf and /home/duen/django/mysite/wsgi.py.

```<code>python = 3.4.2
django = 2.0
apache = 2.4.10
device = raspbarry pi 3 model B
os = OpenMediaVault 3.0.88
</code>```

000-default.conf

```<code><VirtualHost *: 80>
  ServerAdmin sin12070@gmail.com
  DocumentRoot / var / www / html
  ErrorLog $ {APACHE_LOG_DIR} /error.log
  CustomLog $ {APACHE_LOG_DIR} /access.log combined
  WSGIDaemonProcess mysite python-path = / home / duen / django / mysite: /home/duen/django/venv/lib/python3.4/site-packages
  WSGIScriptAlias / /home/duen/django/mysite/wsgi.py
  <Directory / home / duen / django / mysite>
    <Files wsgi.py>
      Require all granted
    </Files>
  </Directory>
</VirtualHost>
</code>```

wsgi.py

```<code>import os
import sys

sys.path.append ('/ hoem / duen / django')
sys.path.append ('/ hoem / duen / django / mysite')
sys.path.append ('/ home / duen / django / venv / lib / python3.4 / site-packages')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault ("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application ()
</code>```

However, when I accessed the web page, I could see this error in error.log.

error.log

```<code>mod_wsgi (pid=9040): Exception occurred processing WSGI script '/home/duen/django/mysite/wsgi.py'.
Traceback (most recent call last)
File "/home/duen/django/mysite/wsgi.py", line 20, in <module>
application = get_wsgi_application()
File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application
django.setup(set_prefix=False)
File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 19, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 106, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2212, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked
ImportError: No module named 'mysite'
</code>```

答:
You aren't telling mod_wsgi to run your WSGI application in the daemon process group you setup. Change:

```<code>WSGIDaemonProcess mysite python-path=/home/duen/django/mysite:/home/duen/django/venv/lib/python3.4/site-packages
WSGIScriptAlias / /home/duen/django/mysite/wsgi.py
</code>```

to:

```<code>WSGIDaemonProcess mysite python-path=/home/duen/django/mysite \
    python-home=/home/duen/django/venv
WSGIScriptAlias / /home/duen/django/mysite/wsgi.py \
    process-group=mysite application-group=%{GLOBAL}
</code>```

Also note I changed to using python-home, which is the recommended way of specifying the virtual environment location.

For details on how to set up the virtual environment properly see:

http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html

Body:
I want to work with Apache 2 and Django 2.0.
So I modified /etc/apache2/sites-sites-available/000-default.conf and /home/duen/django/mysite/wsgi.py.

python = 3.4.2
django = 2.0
apache = 2.4.10
device = raspbarry pi 3 model B
os = OpenMediaVault 3.0.88

000-default.conf

<VirtualHost *: 80>
  ServerAdmin sin12070@gmail.com
  DocumentRoot / var / www / html
  ErrorLog $ {APACHE_LOG_DIR} /error.log
  CustomLog $ {APACHE_LOG_DIR} /access.log combined
  WSGIDaemonProcess mysite python-path = / home / duen / django / mysite: /home/duen/django/venv/lib/python3.4/site-packages
  WSGIScriptAlias / /home/duen/django/mysite/wsgi.py
  <Directory / home / duen / django / mysite>
    <Files wsgi.py>
      Require all granted
    </Files>
  </Directory>
</VirtualHost>

wsgi.py

import os
import sys

sys.path.append ('/ hoem / duen / django')
sys.path.append ('/ hoem / duen / django / mysite')
sys.path.append ('/ home / duen / django / venv / lib / python3.4 / site-packages')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault ("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application ()

However, when I accessed the web page, I could see this error in error.log.

error.log

mod_wsgi (pid=9040): Exception occurred processing WSGI script '/home/duen/django/mysite/wsgi.py'.
Traceback (most recent call last)
File "/home/duen/django/mysite/wsgi.py", line 20, in <module>
application = get_wsgi_application()
File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application
django.setup(set_prefix=False)
File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 19, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 106, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2212, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked
ImportError: No module named 'mysite'

Body:
You aren't telling mod_wsgi to run your WSGI application in the daemon process group you setup. Change:

WSGIDaemonProcess mysite python-path=/home/duen/django/mysite:/home/duen/django/venv/lib/python3.4/site-packages
WSGIScriptAlias / /home/duen/django/mysite/wsgi.py

to:

WSGIDaemonProcess mysite python-path=/home/duen/django/mysite \
    python-home=/home/duen/django/venv
WSGIScriptAlias / /home/duen/django/mysite/wsgi.py \
    process-group=mysite application-group=%{GLOBAL}

Also note I changed to using python-home, which is the recommended way of specifying the virtual environment location.

For details on how to set up the virtual environment properly see:

http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html


问:
ParameterError: data must be of type numpy.ndarray (While Using Librosa)
I am trying to use Librosa library(Python 3.x) for the first time to extract features from multiple audio files which are in wav format. I am facing a issue where it says the data should be of type numpy.ndarray even when it is of that type. Here is my code:

mylist is a list of all the wav audio files in my directory.

```<code>import os
import librosa
mylist= os.listdir('RawData/')

for y in mylist:
   X, sample_rate = librosa.load('RawData/'+y, res_type='kaiser_fast')
   print(type(sample_rate))
   sample_rate = np.array(sample_rate)
   print(type(X))
   print(type(sample_rate))
   mfccs = np.mean(librosa.feature.mfcc(x=X, sr=sample_rate, n_mfcc=40),axis=0)
</code>```

And this is the output and the error that pops up:

```<code>class 'int'

class 'numpy.ndarray'

class 'numpy.ndarray'

ParameterError                            Traceback (most recent call last)
ipython-input-23-817ec793d6c4 in module()
  7     mfccs = np.mean(librosa.feature.mfcc(x=X,
  8                                          sr=sample_rate,
----> 9                                          n_mfcc=40),
 10                     axis=0)
 .
 .
 .
 ParameterError: data must be of type numpy.ndarray
</code>```

Any help is appreciated

答:
you perhaps meant to say
    librosa.feature.mfcc(y=X,

https://librosa.github.io/librosa/generated/librosa.feature.mfcc.html

Body:
I am trying to use Librosa library(Python 3.x) for the first time to extract features from multiple audio files which are in wav format. I am facing a issue where it says the data should be of type numpy.ndarray even when it is of that type. Here is my code:

mylist is a list of all the wav audio files in my directory.

import os
import librosa
mylist= os.listdir('RawData/')

for y in mylist:
   X, sample_rate = librosa.load('RawData/'+y, res_type='kaiser_fast')
   print(type(sample_rate))
   sample_rate = np.array(sample_rate)
   print(type(X))
   print(type(sample_rate))
   mfccs = np.mean(librosa.feature.mfcc(x=X, sr=sample_rate, n_mfcc=40),axis=0)

And this is the output and the error that pops up:

class 'int'

class 'numpy.ndarray'

class 'numpy.ndarray'

ParameterError                            Traceback (most recent call last)
ipython-input-23-817ec793d6c4 in module()
  7     mfccs = np.mean(librosa.feature.mfcc(x=X,
  8                                          sr=sample_rate,
----> 9                                          n_mfcc=40),
 10                     axis=0)
 .
 .
 .
 ParameterError: data must be of type numpy.ndarray

Any help is appreciated


问:
Time Complexity of Fibonacci Algorithm
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)</p>

```<code>public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}
</code>```

答:
Your recursive code has exponential runtime. But I don't think the base is 2, but probably the golden ratio (about 1.62). But of course O(1.62^n) is automatically O(2^n) too.

The runtime can be calculated recursively:

```<code>t(1)=1
t(2)=1
t(n)=t(n-1)+t(n-2)+1
</code>```

This is very similar to the recursive definition of the fibonacci numbers themselves. The +1 in the recursive equation is probably irrelevant for large n. S I believe that it grows approximately as fast as the fibo numbers, and those grow exponentially with the golden ratio as base.

You can speed it up using memoization, i.e. caching already calculated results. Then it has O(n) runtime just like the iterative version.

Your iterative code has a runtime of O(n)

You have a simple loop with O(n) steps and constant time for each iteration.

Title: Time Complexity of Fibonacci Algorithm

Body:
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)

public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}

Body:
Your recursive code has exponential runtime. But I don't think the base is 2, but probably the golden ratio (about 1.62). But of course O(1.62^n) is automatically O(2^n) too.

The runtime can be calculated recursively:

t(1)=1
t(2)=1
t(n)=t(n-1)+t(n-2)+1

This is very similar to the recursive definition of the fibonacci numbers themselves. The +1 in the recursive equation is probably irrelevant for large n. S I believe that it grows approximately as fast as the fibo numbers, and those grow exponentially with the golden ratio as base.

You can speed it up using memoization, i.e. caching already calculated results. Then it has O(n) runtime just like the iterative version.

Your iterative code has a runtime of O(n)

You have a simple loop with O(n) steps and constant time for each iteration.

ContentLicense: CC BY-SA 2.5


问:
Image resizes after async download AFNetworking UiTableView
i have implemented AFNetworking to async download the images to my table, everything works fine, but when i scroll down the table the image in the cell shrinks.

my code look like this:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    [cell.imageView setImageWithURL:url
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}
</code>```

here are some screenshots:

picture 1

picture 2

any tips will be vary apreciate.
regards.

答:
There are different type of content mode available for image view in ios

For Example,

1) The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

```<code>cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
</code>```

2) The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.

```<code>cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
</code>```

3) The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.

```<code>cell.imageView.contentMode = UIViewContentModeScaleToFill;
</code>```

For further details you can refer, Apple Documentation

In the case of your comment you can also create Custom UItableview
cell or Prototype cell  And in that cell's UI you can add imageview and label for title and set the
constraint for the image view as per you requirement

Body:
i have implemented AFNetworking to async download the images to my table, everything works fine, but when i scroll down the table the image in the cell shrinks.

my code look like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    [cell.imageView setImageWithURL:url
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}

here are some screenshots:

picture 1

picture 2

any tips will be vary apreciate.
regards.

Body:
There are different type of content mode available for image view in ios

For Example,

1) The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

cell.imageView.contentMode = UIViewContentModeScaleAspectFit;

2) The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.

cell.imageView.contentMode = UIViewContentModeScaleAspectFill;

3) The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.

cell.imageView.contentMode = UIViewContentModeScaleToFill;

For further details you can refer, Apple Documentation

In the case of your comment you can also create Custom UItableview
cell or Prototype cell  And in that cell's UI you can add imageview and label for title and set the
constraint for the image view as per you requirement


问:
Form does not read javascript before redirect to another page
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.</p>

```<code><html>
<script>
    function fnValidate(){
     with document.frmAdd{
    var x;
    x = txtEmail.value;

    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
    return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
    return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
    return false; }

     } //end_with
    } //end_fnValidate()

</script>
<body>
    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required> <br>
        Name     : <input type=text name="txtName" size=50 required> <br>
        Email    : <input type=text name="txtEmail" size=50 required> <br>
        D.O.B    : <input type=date name="txtDOB" size=20 required> <br>
        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>
        <br><br>
        Username         : <input type=text name="txtUserName" size=20
            required> <br>
        Password         : <input type=password name="txtPwd" size=20
            required> <br>
        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required> <br><br>
        <input type=submit name=btnSubmit value=SAVE>
    </form>
</body>
</html>
</code>```

答:
Wrap the with statement expression with a round brackets. That being said, the use of the with statement is not recommended anymore (see the MDN documentation).

```<code>function fnValidate()
{
  with (document.frmAdd) {
    var x;
    x = txtEmail.value;
    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
        return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
        return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
    return false; }
  } //end_with
  return;
} //end_fnValidate()
</code>```

Body:
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.

    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required>

        Name     : <input type=text name="txtName" size=50 required>

        Email    : <input type=text name="txtEmail" size=50 required>

        D.O.B    : <input type=date name="txtDOB" size=20 required>

        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>

        Username         : <input type=text name="txtUserName" size=20
            required>

        Password         : <input type=password name="txtPwd" size=20
            required>

        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required>

        <input type=submit name=btnSubmit value=SAVE>
    </form>

Body:
Wrap the with statement expression with a round brackets. That being said, the use of the with statement is not recommended anymore (see the MDN documentation).

function fnValidate()
{
  with (document.frmAdd) {
    var x;
    x = txtEmail.value;
    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
        return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
        return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
    return false; }
  } //end_with
  return;
} //end_fnValidate()


问:
Postgresql - not using parallelism
I am executing a select query using full outer join across 2 tables which are in 2 different databases. I'm using Postgresql 9.6.

The query is not going with parallelism even if we set the below parameters:

```<code>work_mem=256MB,
max_worker_process=40,
force_parallel_mode=on,
max_parallel_workers_per_gather=4,
parallel_tuple_cost=0.1,
parallel_setup_cost=1000,
min_parallel_relation_size=8MB
</code>```

This is the query:

```<code>SELECT mea.ocs_cdr_type,
       mea.ocs_time_stamp,
       mea.sum_ocs_call_cost,
       ctr.ctr_name
FROM mea_req_54 mea
   FULL OUTER JOIN country ctr ON mea.ocs_imei  = ctr.ctr_name;
</code>```

This is the definition of mea_req_54:

```<code>                      Table "public.mea_req_54"
           Column           |            Type             | Modifiers
----------------------------+-----------------------------+-----------
 mer_id                     | numeric(19,0)               | not null
 mer_from_dttm              | timestamp without time zone | not null
 mer_to_dttm                | timestamp without time zone | not null
 fng_id                     | numeric(19,0)               |
 ocs_imsi_number_norm       | character varying(255)      |
 ocs_account_number         | character varying(255)      |
 ocs_charging_id            | character varying(255)      |
 ocs_cdr_type               | character varying(255)      |
 ocs_bit_description        | character varying(255)      |
 ocs_time_stamp_raw         | timestamp without time zone |
 ocs_time_stamp             | timestamp without time zone |
 ocs_duration               | numeric(10,0)               |
 ocs_duration_str           | character varying(255)      |
 ocs_upload_volume          | numeric(19,0)               |
 ocs_download_volume        | numeric(19,0)               |
 sum_ocs_total_volume       | numeric(19,0)               |
 sum_ocs_call_cost          | numeric(19,0)               |
 ocs_plmn_identifier        | character varying(255)      |
 ocs_imei                   | character varying(255)      |
 ocs_user_loc_info          | character varying(255)      |
 ocs_bp_id                  | character varying(255)      |
 ocs_ref_spec_from_contract | character varying(255)      |
 ocs_subapp_in_contract_acc | character varying(255)      |
 ocs_baseline_date_bill     | timestamp without time zone |
 ocs_target_date_bill       | timestamp without time zone |
 ocs_date_of_origin_bill    | timestamp without time zone |
 ctr_id                     | numeric(10,0)               |
 ctr_iso_cd                 | character varying(255)      |
 ctr_name                   | character varying(255)      |
 dblink_run                 | numeric(10,0)               |
Indexes:
    "mea_req_54_pk" UNIQUE, btree (mer_id)
</code>```

This is the definition of country:

```<code>                  Table "public.country"
       Column        |          Type          | Modifiers
---------------------+------------------------+-----------
 ctr_id              | numeric(10,0)          | not null
 ctr_iso_cd          | character varying(255) | not null
 ctr_name            | character varying(255) | not null
 system_generated_fl | character(1)           |
 ctr_delete_fl       | character(1)           | not null
 ctr_dial_code       | character varying(255) | not null
 ctr_version_id      | numeric(10,0)          | not null
 ptn_id              | numeric(10,0)          | not null
Indexes:
    "country_ak" UNIQUE, btree (ctr_name)
    "country_pk" UNIQUE, btree (ctr_id)
    "country_ss1" UNIQUE, btree (ctr_iso_cd)
</code>```

This is the execution plan:

```<code>                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
 Hash Full Join  (cost=482.50..14564568.50 rows=300000000 width=29) (actual time=8.810..305863.949 rows=300015000 loops=1)
   Hash Cond: ((mea.ocs_imei)::text = (ctr.ctr_name)::text)
   ->  Seq Scan on mea_req_54 mea  (cost=0.00..10439086.00 rows=300000000 width=19) (actual time=0.005..131927.791 rows=300000000 loops=1)
   ->  Hash  (cost=295.00..295.00 rows=15000 width=13) (actual time=8.784..8.784 rows=15000 loops=1)
         Buckets: 16384  Batches: 1  Memory Usage: 791kB
         ->  Seq Scan on country ctr  (cost=0.00..295.00 rows=15000 width=13) (actual time=0.008..4.138 rows=15000 loops=1)
 Planning time: 0.085 ms
 Execution time: 355065.791 ms
(8 rows)
</code>```

答:
Post reducing the parallel_tuple_cost and parallel_setup_cost parameters from the default values, the query ran with parallelism.

But I wanted to know about these parameters what exactly they are ?

Title: Postgresql - not using parallelism

Body:
I am executing a select query using full outer join across 2 tables which are in 2 different databases. I'm using Postgresql 9.6.

The query is not going with parallelism even if we set the below parameters:

work_mem=256MB,
max_worker_process=40,
force_parallel_mode=on,
max_parallel_workers_per_gather=4,
parallel_tuple_cost=0.1,
parallel_setup_cost=1000,
min_parallel_relation_size=8MB

This is the query:

SELECT mea.ocs_cdr_type,
       mea.ocs_time_stamp,
       mea.sum_ocs_call_cost,
       ctr.ctr_name
FROM mea_req_54 mea
   FULL OUTER JOIN country ctr ON mea.ocs_imei  = ctr.ctr_name;

This is the definition of mea_req_54:

                      Table "public.mea_req_54"
           Column           |            Type             | Modifiers
----------------------------+-----------------------------+-----------
 mer_id                     | numeric(19,0)               | not null
 mer_from_dttm              | timestamp without time zone | not null
 mer_to_dttm                | timestamp without time zone | not null
 fng_id                     | numeric(19,0)               |
 ocs_imsi_number_norm       | character varying(255)      |
 ocs_account_number         | character varying(255)      |
 ocs_charging_id            | character varying(255)      |
 ocs_cdr_type               | character varying(255)      |
 ocs_bit_description        | character varying(255)      |
 ocs_time_stamp_raw         | timestamp without time zone |
 ocs_time_stamp             | timestamp without time zone |
 ocs_duration               | numeric(10,0)               |
 ocs_duration_str           | character varying(255)      |
 ocs_upload_volume          | numeric(19,0)               |
 ocs_download_volume        | numeric(19,0)               |
 sum_ocs_total_volume       | numeric(19,0)               |
 sum_ocs_call_cost          | numeric(19,0)               |
 ocs_plmn_identifier        | character varying(255)      |
 ocs_imei                   | character varying(255)      |
 ocs_user_loc_info          | character varying(255)      |
 ocs_bp_id                  | character varying(255)      |
 ocs_ref_spec_from_contract | character varying(255)      |
 ocs_subapp_in_contract_acc | character varying(255)      |
 ocs_baseline_date_bill     | timestamp without time zone |
 ocs_target_date_bill       | timestamp without time zone |
 ocs_date_of_origin_bill    | timestamp without time zone |
 ctr_id                     | numeric(10,0)               |
 ctr_iso_cd                 | character varying(255)      |
 ctr_name                   | character varying(255)      |
 dblink_run                 | numeric(10,0)               |
Indexes:
    "mea_req_54_pk" UNIQUE, btree (mer_id)

This is the definition of country:

                  Table "public.country"
       Column        |          Type          | Modifiers
---------------------+------------------------+-----------
 ctr_id              | numeric(10,0)          | not null
 ctr_iso_cd          | character varying(255) | not null
 ctr_name            | character varying(255) | not null
 system_generated_fl | character(1)           |
 ctr_delete_fl       | character(1)           | not null
 ctr_dial_code       | character varying(255) | not null
 ctr_version_id      | numeric(10,0)          | not null
 ptn_id              | numeric(10,0)          | not null
Indexes:
    "country_ak" UNIQUE, btree (ctr_name)
    "country_pk" UNIQUE, btree (ctr_id)
    "country_ss1" UNIQUE, btree (ctr_iso_cd)

This is the execution plan:

                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
 Hash Full Join  (cost=482.50..14564568.50 rows=300000000 width=29) (actual time=8.810..305863.949 rows=300015000 loops=1)
   Hash Cond: ((mea.ocs_imei)::text = (ctr.ctr_name)::text)
   ->  Seq Scan on mea_req_54 mea  (cost=0.00..10439086.00 rows=300000000 width=19) (actual time=0.005..131927.791 rows=300000000 loops=1)
   ->  Hash  (cost=295.00..295.00 rows=15000 width=13) (actual time=8.784..8.784 rows=15000 loops=1)
         Buckets: 16384  Batches: 1  Memory Usage: 791kB
         ->  Seq Scan on country ctr  (cost=0.00..295.00 rows=15000 width=13) (actual time=0.008..4.138 rows=15000 loops=1)
 Planning time: 0.085 ms
 Execution time: 355065.791 ms
(8 rows)