问:
how to search for letters which are next to each other?
string = 'woraaadaaaa';

If I want to find if there is 'word' in string:

```<code>for x in string:
    if 'word' in string:
    print(word)
</code>```

But I want to print it just when letters are next to each other, so for instance in string 'aaawordaaa' there is 'word', but in 'aaworad' not. How to do this?
This is what I am looking help in

答:
Its just like the example below.

```<code>  s="aaawordaaa"
  if 'word' in s:
     print('word')
  else:
      print("did not find the word")
</code>```

The mistake you were doing is looping through it and which is not required, because you were however looking for continuous appearance of the word "word"

In the above example since 'word' is present as a continuous appearance you will get your desired output.

Also have a look at basic_tutorial which shall help you understand much more.

Body:
string = 'woraaadaaaa';

If I want to find if there is 'word' in string:

for x in string:
    if 'word' in string:
    print(word)

But I want to print it just when letters are next to each other, so for instance in string 'aaawordaaa' there is 'word', but in 'aaworad' not. How to do this?
This is what I am looking help in

Body:
Its just like the example below.

  s="aaawordaaa"
  if 'word' in s:
     print('word')
  else:
      print("did not find the word")

The mistake you were doing is looping through it and which is not required, because you were however looking for continuous appearance of the word "word"

In the above example since 'word' is present as a continuous appearance you will get your desired output.

Also have a look at basic_tutorial which shall help you understand much more.


来源: stackexchange

问:
Import html from typescript with webpack
I am trying to import html into a variable in typescript using webpack.

Here is my setup:

package.json:

```<code>{
  "devDependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "html-loader": "^0.5.1",
    "ts-loader": "^2.3.7",
    "typescript": "^2.5.3",
    "webpack": "^3.6.0"
  }
}
</code>```

webpack.config.js:

```<code>const path = require('path');
const webpack = require('webpack');

module.exports = {
  context: path.join(__dirname),
  entry: './main',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'app.js'
  },
  resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".ts", ".js"],
    modules: [
      "node_modules",
      path.join(__dirname, 'app'),
    ],
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.html$/,
        loader: 'html-loader',
      },
      // Faster alternative to ts-loader
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        options: {
          configFileName: 'tsconfig.json',
        },
        exclude: /(node_modules)/,
      },
    ],
  },
};
</code>```

main.ts:

```<code>import template from './template.html';
console.log(template);
</code>```

template.html:

```<code><p>Hello World !</p>
</code>```

When I try to compile with with webpack:

```<code>$ ./node_modules/.bin/webpack

[at-loader] Using typescript@2.5.3 from typescript and "tsconfig.json" from /tmp/test/tsconfig.json.

[at-loader] Checking started in a separate process...

[at-loader] Checking finished with 1 errors
Hash: d06d08edc313f90c0533
Version: webpack 3.6.0
Time: 2194ms
 Asset     Size  Chunks             Chunk Names
app.js  2.72 kB       0  [emitted]  main
   [0] ./main.ts 136 bytes {0} [built]
   [1] ./template.html 40 bytes {0} [built]

ERROR in [at-loader] ./main.ts:1:22
    TS2307: Cannot find module './template.html'.
</code>```

I've been on this for half a day so you can be sure template.html is where it is supposed to be.

From what I understand from webpack config is that the html-loader is supposed to process the file first, so it should load the content of the html file into the variable. At least, this used to work with es6...

Can anyone tel me how to load html into a variable with webpack / typescript? Or at least what is wrong with my approach.

答:
An easy workaround is to stick with CommonJS "require" when loading non-TypeScript assets:

```<code>const template = require('./template.html');
</code>```

If you'd prefer to keep using import, it's possible to configure the TypeScript compiler to load the file as a string. The method below worked for me under TypeScript 2.4.2.

Add this block to your project's type declarations file (mine is called typings.d.ts):

```<code>// typings.d.ts
declare module '*.html' {
  const content: string;
  export default content;
}
</code>```

You should now be able to import html files like this:

```<code>// main.ts
import template from './template.html';
console.log(template); // <p>Hello world !</p>
</code>```

Full disclosure: my project used different loaders from yours (see below).

```<code>// webpack.config.js
config.module = {
  rules: [
    {
      test: /\.ts$/,
      loader: '@ngtools/webpack'
    },
    {
      test: /\.html$/,
      use: 'raw-loader'
    }
  ]
}
</code>```

There's a Github thread here where other solutions are discussed.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to import html into a variable in typescript using webpack.

Here is my setup:

package.json:

{
  "devDependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "html-loader": "^0.5.1",
    "ts-loader": "^2.3.7",
    "typescript": "^2.5.3",
    "webpack": "^3.6.0"
  }
}

webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  context: path.join(__dirname),
  entry: './main',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'app.js'
  },
  resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".ts", ".js"],
    modules: [
      "node_modules",
      path.join(__dirname, 'app'),
    ],
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.html$/,
        loader: 'html-loader',
      },
      // Faster alternative to ts-loader
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        options: {
          configFileName: 'tsconfig.json',
        },
        exclude: /(node_modules)/,
      },
    ],
  },
};

main.ts:

import template from './template.html';
console.log(template);

template.html:

Hello World !

When I try to compile with with webpack:

$ ./node_modules/.bin/webpack

[at-loader] Using typescript@2.5.3 from typescript and "tsconfig.json" from /tmp/test/tsconfig.json.

[at-loader] Checking started in a separate process...

[at-loader] Checking finished with 1 errors
Hash: d06d08edc313f90c0533
Version: webpack 3.6.0
Time: 2194ms
 Asset     Size  Chunks             Chunk Names
app.js  2.72 kB       0  [emitted]  main
   [0] ./main.ts 136 bytes {0} [built]
   [1] ./template.html 40 bytes {0} [built]

ERROR in [at-loader] ./main.ts:1:22
    TS2307: Cannot find module './template.html'.

I've been on this for half a day so you can be sure template.html is where it is supposed to be.

From what I understand from webpack config is that the html-loader is supposed to process the file first, so it should load the content of the html file into the variable. At least, this used to work with es6...

Can anyone tel me how to load html into a variable with webpack / typescript? Or at least what is wrong with my approach.

Body:
An easy workaround is to stick with CommonJS "require" when loading non-TypeScript assets:

const template = require('./template.html');

If you'd prefer to keep using import, it's possible to configure the TypeScript compiler to load the file as a string. The method below worked for me under TypeScript 2.4.2.

Add this block to your project's type declarations file (mine is called typings.d.ts):

// typings.d.ts
declare module '*.html' {
  const content: string;
  export default content;
}

You should now be able to import html files like this:

// main.ts
import template from './template.html';
console.log(template); // <p>Hello world !</p>

Full disclosure: my project used different loaders from yours (see below).

// webpack.config.js
config.module = {
  rules: [
    {
      test: /\.ts$/,
      loader: '@ngtools/webpack'
    },
    {
      test: /\.html$/,
      use: 'raw-loader'
    }
  ]
}

There's a Github thread here where other solutions are discussed.


问:
How I can I lazily read multiple JSON values from a file/stream in Python?
I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately json.load() just .read()s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.

Is there any way to do this? Using the standard library would be ideal, but if there's a third-party library I'd use that instead.

At the moment I'm putting each object on a separate line and using json.loads(f.readline()), but I would really prefer not to need to do this.

Example Use

example.py

import my_json as json
import sys

for o in json.iterload(sys.stdin):
    print("Working on a", type(o))
```

<h3>in.txt</h3>

<pre class="lang-js prettyprint-override"><code>{"foo": ["bar", "baz"]} 1 2 [] 4 5 6
</code>```

example session

$ python3.2 example.py < in.txt
Working on a dict
Working on a int
Working on a int
Working on a list
Working on a int
Working on a int
Working on a int
```

答:
If you use a json.JSONDecoder instance you can use raw_decode member function. It returns a tuple of python representation of the JSON value and an index to where the parsing stopped. This makes it easy to slice (or seek in a stream object) the remaining JSON values. I'm not so happy about the extra while loop to skip over the white space between the different JSON values in the input but it gets the job done in my opinion.

```<code>import json

def yield_multiple_value(f):
    '''
    parses multiple JSON values from a file.
    '''
    vals_str = f.read()
    decoder = json.JSONDecoder()
    try:
        nread = 0
        while nread < len(vals_str):
            val, n = decoder.raw_decode(vals_str[nread:])
            nread += n
            # Skip over whitespace because of bug, below.
            while nread < len(vals_str) and vals_str[nread].isspace():
                nread += 1
            yield val
    except json.JSONDecodeError as e:
        pass
    return
</code>```

The next version is much shorter and eats the part of the string that is already parsed. It seems that for some reason a second call json.JSONDecoder.raw_decode() seems to fail when the first character in the string is a whitespace, that is also the reason why I skip over the whitespace in the whileloop above ...

```<code>def yield_multiple_value(f):
    '''
    parses multiple JSON values from a file.
    '''
    vals_str = f.read()
    decoder = json.JSONDecoder()
    while vals_str:
        val, n = decoder.raw_decode(vals_str)
        #remove the read characters from the start.
        vals_str = vals_str[n:]
        # remove leading white space because a second call to decoder.raw_decode()
        # fails when the string starts with whitespace, and
        # I don't understand why...
        vals_str = vals_str.lstrip()
        yield val
    return
</code>```

In the documentation about the json.JSONDecoder class the method raw_decode https://docs.python.org/3/library/json.html#encoders-and-decoders contains the following:

This can be used to decode a JSON document from a string that may have
  extraneous data at the end.

And this extraneous data can easily be another JSON value. In other words the method might be written with this purpose in mind.

With the input.txt using the upper function I obtain the example output as presented in the original question.

Body:
I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately json.load() just .read()s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.

Is there any way to do this? Using the standard library would be ideal, but if there's a third-party library I'd use that instead.

At the moment I'm putting each object on a separate line and using json.loads(f.readline()), but I would really prefer not to need to do this.

Example Use

example.py

import my_json as json
import sys

for o in json.iterload(sys.stdin):
    print("Working on a", type(o))

in.txt

{"foo": ["bar", "baz"]} 1 2 [] 4 5 6

example session

$ python3.2 example.py < in.txt
Working on a dict
Working on a int
Working on a int
Working on a list
Working on a int
Working on a int
Working on a int

Body:
If you use a json.JSONDecoder instance you can use raw_decode member function. It returns a tuple of python representation of the JSON value and an index to where the parsing stopped. This makes it easy to slice (or seek in a stream object) the remaining JSON values. I'm not so happy about the extra while loop to skip over the white space between the different JSON values in the input but it gets the job done in my opinion.

import json

def yield_multiple_value(f):
    '''
    parses multiple JSON values from a file.
    '''
    vals_str = f.read()
    decoder = json.JSONDecoder()
    try:
        nread = 0
        while nread < len(vals_str):
            val, n = decoder.raw_decode(vals_str[nread:])
            nread += n
            # Skip over whitespace because of bug, below.
            while nread < len(vals_str) and vals_str[nread].isspace():
                nread += 1
            yield val
    except json.JSONDecodeError as e:
        pass
    return

The next version is much shorter and eats the part of the string that is already parsed. It seems that for some reason a second call json.JSONDecoder.raw_decode() seems to fail when the first character in the string is a whitespace, that is also the reason why I skip over the whitespace in the whileloop above ...

def yield_multiple_value(f):
    '''
    parses multiple JSON values from a file.
    '''
    vals_str = f.read()
    decoder = json.JSONDecoder()
    while vals_str:
        val, n = decoder.raw_decode(vals_str)
        #remove the read characters from the start.
        vals_str = vals_str[n:]
        # remove leading white space because a second call to decoder.raw_decode()
        # fails when the string starts with whitespace, and
        # I don't understand why...
        vals_str = vals_str.lstrip()
        yield val
    return

In the documentation about the json.JSONDecoder class the method raw_decode https://docs.python.org/3/library/json.html#encoders-and-decoders contains the following:

This can be used to decode a JSON document from a string that may have
  extraneous data at the end.

And this extraneous data can easily be another JSON value. In other words the method might be written with this purpose in mind.

With the input.txt using the upper function I obtain the example output as presented in the original question.


问:
SQL Union on the Join subsets
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

```<code>create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID
</code>```

This gives out the response:

```<code>aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00
</code>```

But what is required is:

```<code>aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
</code>```

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

```<code>with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;
</code>```

答:
Please use this:</p>

```<code>select
     id = col.value('(id)[1]', 'nvarchar(256)')
    ,cv_modstamp = col.value('(cv_modstamp)[1]', 'datetimeoffset(7)')
    ,sf_deleteddate = col.value('(sf_deleteddate)[1]', 'datetimeoffset(7)')
from

( select [myData] = convert(xml, (

    select
         [rec/id] = D1.id, [rec/cv_modstamp] = d1.cv_modstamp, [rec/sf_deleteddate] = d1.sf_deleteddate
        ,[data] = null
        ,[rec/id] = D2.id, [rec/cv_modstamp] = d2.cv_modstamp, [rec/sf_deleteddate] = d2.sf_deleteddate
    from
    (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                      FROM TEST
                      WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                      GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
     AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
     AND   A.SF_Deleteddate IS NULL
    ) D1
    INNER JOIN
     (
        select A.*
        FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                      FROM TEST
                      WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                      GROUP BY id) T
        WHERE A.id = T.T_ALIAS_ID
        AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND   A.SF_Deleteddate IS NULL
     )
    D2 ON D1.ID = D2.ID
    FOR XML PATH('data')
))) as t
cross apply t.myData.nodes('data/rec') as tab(col);
</code>```

Title: SQL Union on the Join subsets

Body:
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID

This gives out the response:

aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00

But what is required is:

aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;

Body:
Please use this:

select
     id = col.value('(id)[1]', 'nvarchar(256)')
    ,cv_modstamp = col.value('(cv_modstamp)[1]', 'datetimeoffset(7)')
    ,sf_deleteddate = col.value('(sf_deleteddate)[1]', 'datetimeoffset(7)')
from

( select [myData] = convert(xml, (

    select
         [rec/id] = D1.id, [rec/cv_modstamp] = d1.cv_modstamp, [rec/sf_deleteddate] = d1.sf_deleteddate
        ,[data] = null
        ,[rec/id] = D2.id, [rec/cv_modstamp] = d2.cv_modstamp, [rec/sf_deleteddate] = d2.sf_deleteddate
    from
    (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                      FROM TEST
                      WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                      GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
     AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
     AND   A.SF_Deleteddate IS NULL
    ) D1
    INNER JOIN
     (
        select A.*
        FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                      FROM TEST
                      WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                      GROUP BY id) T
        WHERE A.id = T.T_ALIAS_ID
        AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND   A.SF_Deleteddate IS NULL
     )
    D2 ON D1.ID = D2.ID
    FOR XML PATH('data')
))) as t
cross apply t.myData.nodes('data/rec') as tab(col);


问:
html2text: How to parse urls containing special characters?
I'm trying to use Aaron Swartz's Python html2text library (on Python 2.7). I haven't succeeded at using html2text() on strings containing a link whose URL has a special character. For example:

```<code># -*- coding: utf-8 -*-
import html2text
s = u'Link <a href="https://en.wikipedia.org/wiki/Málaga">here</a>!'
str = html2text.html2text(s)
</code>```

Fails with error:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 31: ordinal not in range(128)
</code>```

Whereas:

```<code># -*- coding: utf-8 -*-
import html2text
s = u'<a href="https://en.wikipedia.org/wiki/Malaga">héré</a>!'
str = html2text.html2text(s)
</code>```

(which has special characters, but only in text, not in the URL) works just fine.

I must be missing something with the encoding, but I can't find anything in the documentation. Is there a way of telling html2text to use a non-ascii encoder in its url parser?

答:
You can encode non-ascii characters with urllib.quote (urllib.parse.quote in Python3).  The charecters specified in the safe parameter will not be encoded.

```<code>import html2text
from urllib import quote

s = 'Link <a href="https://en.wikipedia.org/wiki/Málaga">here</a>!'
q = quote(s, safe=' <>="/:!')
s = html2text.html2text(q)

print q
print s

Link <a href="https://en.wikipedia.org/wiki/M%C3%A1laga">here</a>!
Link [here](https://en.wikipedia.org/wiki/M%C3%A1laga)!
</code>```

You can't have unicode characters in href because it is formatted in string.
The error comes from html2text.HTML2Text.close in line 163 : outtext = nochr.join(self.outtextlist), where nochr is unicode(''), and self.outtextlist is a list of the tag parts:

```<code>[u'Link ', '[', u'h\xe9r\xe9', '](https://en.wikipedia.org/wiki/Mlaga)', u'!', '\n', '']
</code>```

As you can see the item containing the href is not a unicode string.

That's because in html2text.HTML2Text.handle_tag, in function link_url, line 440, url is formated to string: ']({url}{title})'.format(url=escape_md(url), title=title).

If you change it to unicode (u']({url}{title})') you'll get a unicode string in self.outtextlist:

```<code>[u'Link ', '[', u'h\xe9r\xe9', u'](https://en.wikipedia.org/wiki/Ml\xe1ga)', u'!', '\n','']
</code>```

and the output with u'Link héré!' will be:

```<code>Link [héré](https://en.wikipedia.org/wiki/Mlága)!
</code>```

However i don't recommend modifying the original code. A possible solution would be to subclass HTML2Text and overwrite link_url, but the problem is that link_url is a local function, so you would have to overwrite the entire handle_tag method.

Body:
I'm trying to use Aaron Swartz's Python html2text library (on Python 2.7). I haven't succeeded at using html2text() on strings containing a link whose URL has a special character. For example:

# -*- coding: utf-8 -*-
import html2text
s = u'Link here!'
str = html2text.html2text(s)

Fails with error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 31: ordinal not in range(128)

Whereas:

# -*- coding: utf-8 -*-
import html2text
s = u'héré!'
str = html2text.html2text(s)

(which has special characters, but only in text, not in the URL) works just fine.

I must be missing something with the encoding, but I can't find anything in the documentation. Is there a way of telling html2text to use a non-ascii encoder in its url parser?

Body:
You can encode non-ascii characters with urllib.quote (urllib.parse.quote in Python3).  The charecters specified in the safe parameter will not be encoded.

import html2text
from urllib import quote

s = 'Link <a href="https://en.wikipedia.org/wiki/Málaga">here</a>!'
q = quote(s, safe=' <>="/:!')
s = html2text.html2text(q)

print q
print s

Link <a href="https://en.wikipedia.org/wiki/M%C3%A1laga">here</a>!
Link [here](https://en.wikipedia.org/wiki/M%C3%A1laga)!

You can't have unicode characters in href because it is formatted in string.
The error comes from html2text.HTML2Text.close in line 163 : outtext = nochr.join(self.outtextlist), where nochr is unicode(''), and self.outtextlist is a list of the tag parts:

[u'Link ', '[', u'h\xe9r\xe9', '](https://en.wikipedia.org/wiki/Mlaga)', u'!', '\n', '']

As you can see the item containing the href is not a unicode string.

That's because in html2text.HTML2Text.handle_tag, in function link_url, line 440, url is formated to string: ']({url}{title})'.format(url=escape_md(url), title=title).

If you change it to unicode (u']({url}{title})') you'll get a unicode string in self.outtextlist:

[u'Link ', '[', u'h\xe9r\xe9', u'](https://en.wikipedia.org/wiki/Ml\xe1ga)', u'!', '\n','']

and the output with u'Link <a href="https://en.wikipedia.org/wiki/Mlága">héré</a>!' will be:

Link [héré](https://en.wikipedia.org/wiki/Mlága)!

However i don't recommend modifying the original code. A possible solution would be to subclass HTML2Text and overwrite link_url, but the problem is that link_url is a local function, so you would have to overwrite the entire handle_tag method.


问:
Pandas Timeseries Data - Calculating product over intervals of varying length

I have some timeseries data that basically contains information on price change period by period. For example, let's say:

```<code>df = pd.DataFrame(columns = ['TimeStamp','PercPriceChange'])
df.loc[:,'TimeStamp']=[1457280,1457281,1457282,1457283,1457284,1457285,1457286]
df.loc[:,'PercPriceChange']=[0.1,0.2,-0.1,0.1,0.2,0.1,-0.1]
</code>```

so that df looks like

```<code>     TimeStamp  PercPriceChange
0    1457280              0.1
1    1457281              0.2
2    1457282             -0.1
3    1457283              0.1
4    1457284              0.2
5    1457285              0.1
6    1457286             -0.1
</code>```

What I want to achieve is to calculate the overall price change before the an increase/decrease streak ends, and store the value in the row where the streak started. That is, what I want is a column 'TotalPriceChange' :

```<code>   TimeStamp   PercPriceChange               TotalPriceChange
0    1457280              0.1             1.1 * 1.2  - 1 = 0.31
1    1457281              0.2                         0
2    1457282             -0.1                        -0.1
3    1457283              0.1           1.1 * 1.2 * 1.1  - 1 = 0.452
4    1457284              0.2                         0
5    1457285              0.1                         0
6    1457286             -0.1                        -0.1
</code>```

I can identify the starting points using something like:

```<code>df['turn'] = 0
df['PriceChange_L1'] = df['PercPriceChange'].shift(periods=1, freq=None, axis=0)
df.loc[ df['PercPriceChange'] * df['PriceChange_L1'] < 0, 'turn' ] = 1
</code>```

to get

```<code>    TimeStamp   PercPriceChange             turn
0    1457280              0.1          NaN or 1?
1    1457281              0.2             0
2    1457282             -0.1             1
3    1457283              0.1             1
4    1457284              0.2             0
5    1457285              0.1             0
6    1457286             -0.1             1
</code>```

Given this column "turn", I need help proceeding with my quest (or perhaps we don't need this "turn" at all). I am pretty sure I can write a nested for-loop going through the entire DataFrame row by row, calculating what I need and populating the column 'TotalPriceChange', but given that I plan on doing this on a fairly large data set (think minute or hour data for couple of years), I imagine nested for-loops will be really slow.

Therefore, I just wanted to check with you experts to see if there is any efficient solution to my problem that I am not aware of. Any help would be much appreciated!

Thanks!

答:
The calculation you are looking for looks like a groupby/product operation.
To set up the groupby operation, we need to assign a group value to each row. Taking the cumulative sum of the turn column gives the desired result:

```<code>df['group'] = df['turn'].cumsum()
# 0    0
# 1    0
# 2    1
# 3    2
# 4    2
# 5    2
# 6    3
# Name: group, dtype: int64
</code>```

Now we can define the TotalPriceChange column (modulo a little cleanup work) as

```<code>df['PercPriceChange_plus_one'] = df['PercPriceChange']+1
df['TotalPriceChange'] = df.groupby('group')['PercPriceChange_plus_one'].transform('prod') - 1
</code>```

```<code>import pandas as pd
df = pd.DataFrame({'PercPriceChange': [0.1, 0.2, -0.1, 0.1, 0.2, 0.1, -0.1],
                   'TimeStamp': [1457280, 1457281, 1457282, 1457283, 1457284, 1457285, 1457286]})

df['turn'] = 0
df['PriceChange_L1'] = df['PercPriceChange'].shift(periods=1, freq=None, axis=0)
df.loc[ df['PercPriceChange'] * df['PriceChange_L1'] < 0, 'turn' ] = 1

df['group'] = df['turn'].cumsum()

df['PercPriceChange_plus_one'] = df['PercPriceChange']+1
df['TotalPriceChange'] = df.groupby('group')['PercPriceChange_plus_one'].transform('prod') - 1
mask = (df['group'].diff() != 0)
df.loc[~mask, 'TotalPriceChange'] = 0

df = df[['TimeStamp', 'PercPriceChange', 'TotalPriceChange']]
print(df)
</code>```

yields

```<code>   TimeStamp  PercPriceChange  TotalPriceChange
0    1457280              0.1             0.320
1    1457281              0.2             0.000
2    1457282             -0.1            -0.100
3    1457283              0.1             0.452
4    1457284              0.2             0.000
5    1457285              0.1             0.000
6    1457286             -0.1            -0.100
</code>```

Body:
I have some timeseries data that basically contains information on price change period by period. For example, let's say:

df = pd.DataFrame(columns = ['TimeStamp','PercPriceChange'])
df.loc[:,'TimeStamp']=[1457280,1457281,1457282,1457283,1457284,1457285,1457286]
df.loc[:,'PercPriceChange']=[0.1,0.2,-0.1,0.1,0.2,0.1,-0.1]

so that df looks like

     TimeStamp  PercPriceChange
0    1457280              0.1
1    1457281              0.2
2    1457282             -0.1
3    1457283              0.1
4    1457284              0.2
5    1457285              0.1
6    1457286             -0.1

What I want to achieve is to calculate the overall price change before the an increase/decrease streak ends, and store the value in the row where the streak started. That is, what I want is a column 'TotalPriceChange' :

   TimeStamp   PercPriceChange               TotalPriceChange
0    1457280              0.1             1.1 * 1.2  - 1 = 0.31
1    1457281              0.2                         0
2    1457282             -0.1                        -0.1
3    1457283              0.1           1.1 * 1.2 * 1.1  - 1 = 0.452
4    1457284              0.2                         0
5    1457285              0.1                         0
6    1457286             -0.1                        -0.1

I can identify the starting points using something like:

df['turn'] = 0
df['PriceChange_L1'] = df['PercPriceChange'].shift(periods=1, freq=None, axis=0)
df.loc[ df['PercPriceChange'] * df['PriceChange_L1'] < 0, 'turn' ] = 1

to get

    TimeStamp   PercPriceChange             turn
0    1457280              0.1          NaN or 1?
1    1457281              0.2             0
2    1457282             -0.1             1
3    1457283              0.1             1
4    1457284              0.2             0
5    1457285              0.1             0
6    1457286             -0.1             1

Given this column "turn", I need help proceeding with my quest (or perhaps we don't need this "turn" at all). I am pretty sure I can write a nested for-loop going through the entire DataFrame row by row, calculating what I need and populating the column 'TotalPriceChange', but given that I plan on doing this on a fairly large data set (think minute or hour data for couple of years), I imagine nested for-loops will be really slow.

Therefore, I just wanted to check with you experts to see if there is any efficient solution to my problem that I am not aware of. Any help would be much appreciated!

Thanks!

Body:
The calculation you are looking for looks like a groupby/product operation.
To set up the groupby operation, we need to assign a group value to each row. Taking the cumulative sum of the turn column gives the desired result:

df['group'] = df['turn'].cumsum()
# 0    0
# 1    0
# 2    1
# 3    2
# 4    2
# 5    2
# 6    3
# Name: group, dtype: int64

Now we can define the TotalPriceChange column (modulo a little cleanup work) as

df['PercPriceChange_plus_one'] = df['PercPriceChange']+1
df['TotalPriceChange'] = df.groupby('group')['PercPriceChange_plus_one'].transform('prod') - 1

import pandas as pd
df = pd.DataFrame({'PercPriceChange': [0.1, 0.2, -0.1, 0.1, 0.2, 0.1, -0.1],
                   'TimeStamp': [1457280, 1457281, 1457282, 1457283, 1457284, 1457285, 1457286]})

df['turn'] = 0
df['PriceChange_L1'] = df['PercPriceChange'].shift(periods=1, freq=None, axis=0)
df.loc[ df['PercPriceChange'] * df['PriceChange_L1'] < 0, 'turn' ] = 1

df['group'] = df['turn'].cumsum()

df['PercPriceChange_plus_one'] = df['PercPriceChange']+1
df['TotalPriceChange'] = df.groupby('group')['PercPriceChange_plus_one'].transform('prod') - 1
mask = (df['group'].diff() != 0)
df.loc[~mask, 'TotalPriceChange'] = 0

df = df[['TimeStamp', 'PercPriceChange', 'TotalPriceChange']]
print(df)

yields

   TimeStamp  PercPriceChange  TotalPriceChange
0    1457280              0.1             0.320
1    1457281              0.2             0.000
2    1457282             -0.1            -0.100
3    1457283              0.1             0.452
4    1457284              0.2             0.000
5    1457285              0.1             0.000
6    1457286             -0.1            -0.100


问:
ModuleNotFound: No module named 'app'
Let's say I have the following folder structure intended to organize the tests in my project repo:

```<code>project/
    app.py
    tests/
        test.py
</code>```

app.py has a simple addition function:

```<code>def add(x, y):
    return x + y
</code>```

test.py tests this function:

```<code>from app import add
import unittest

class TestCase(unittest.TestCase):
    def test_add(self):
        print('Running the test!')
        self.assertEqual(add(3, 4), 7)

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

When I use nose2 everything works:

```<code>mac:project $ nose2
Running the test!
Ran 1 test in 0.000s
Ok
</code>```

The problem is when I try to run test.py directly I get the following error:

```<code>mac:project $ python tests/test.py
ModuleNotFound: No module named 'app'
</code>```

How can I fix this? The reason is I want to use the coverage package to measure code coverage and I'm getting the same error:

```<code>mac:project $ coverage run tests/test.py
ModuleNotFound: No module named 'app'
</code>```

I've tried from ..app import app but I get this error: ValueError: attempted relative import beyond top-level package

答:
When you run python tests/test.py, the tests directory is on the Python path, but the parent directory is not, so you can't import apps.

You can get the import to work by adding the project directory before the imports in test.py:

```<code>import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
</code>```

Title: ModuleNotFound: No module named 'app'

Body:
Let's say I have the following folder structure intended to organize the tests in my project repo:

project/
    app.py
    tests/
        test.py

app.py has a simple addition function:

def add(x, y):
    return x + y

test.py tests this function:

from app import add
import unittest

class TestCase(unittest.TestCase):
    def test_add(self):
        print('Running the test!')
        self.assertEqual(add(3, 4), 7)

if __name__ == '__main__':
    unittest.main()

When I use nose2 everything works:

mac:project $ nose2
Running the test!
Ran 1 test in 0.000s
Ok

The problem is when I try to run test.py directly I get the following error:

mac:project $ python tests/test.py
ModuleNotFound: No module named 'app'

How can I fix this? The reason is I want to use the coverage package to measure code coverage and I'm getting the same error:

mac:project $ coverage run tests/test.py
ModuleNotFound: No module named 'app'

I've tried from ..app import app but I get this error: ValueError: attempted relative import beyond top-level package

Body:
When you run python tests/test.py, the tests directory is on the Python path, but the parent directory is not, so you can't import apps.

You can get the import to work by adding the project directory before the imports in test.py:

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


问:
Can Function declaration or function prototype affects the working of the program
I am new beginner in the programming world and while I was coding on Functions in C, I came to know that there are three most important parts of the functions namely-

Function declaration or function prototype

Function call

Function definition

But, while I was solving a problem on factorials of a number I came to know in my code that when I am not including function declaration or function protocol in my code above main() then still the code is running and giving the output as 120. So my question is why a function declaration or function prototype is not affecting the output of my program or is it not necessary to include function declaration or prototype above main().

```<code>-------Code-----
#include<stdio.h>
#include<conio.h>

// int fact(int);
main()
{
   int x;
   x=fact(5);
   printf("The factorial is =%d",x);
}

int fact(int n)
{
  int f=1,i;
  for(I=1;i<=n;i++)
       f=f*I;
    return (f);
}
</code>```

答:
If you use a function without declaring it, the compiler may provide a default declaration. This is not part of modern C, but compilers may use old standards or be unduly lax in this regard. (It is better to require explicit declarations because it helps reduce mistakes.)

Any declaration of a function must match the definition of the function. The declaration gives the compiler information about how to call the function. If the declaration does not match, things can go wrong. So, yes, the declaration can affect your program; it can break it.

In this case, you got lucky, the default declaration of a function happened to match your function fact. The default declaration is a function that returns int and accepts whatever arguments you pass it, subject to default argument promotions. (Roughly speaking, the default argument promotions are that integers narrower than an int are converted to int, and float values are converted to double. So, if a function returns int and accepts only int and double arguments, it can match the default declaration.)

A good compiler will warn you that a declaration is missing or that a declaration is wrong. Your compiler has “switches” or other options that tell it what sorts of warning and error messages you want. You should ask for lots of warning messages.

Your compiler probably also has switches that say which version of C to use. (There have been several standard versions, most recently 1999 and 2011, and there are some non-standard variants.) You might want to request that your compiler use the C 2011 standard, until you have good reason to change that. (Unfortunately, if you are using Microsoft Visual C, I do not believe it supports C 2011.)

Body:
I am new beginner in the programming world and while I was coding on Functions in C, I came to know that there are three most important parts of the functions namely-

Function declaration or function prototype

Function call

Function definition

But, while I was solving a problem on factorials of a number I came to know in my code that when I am not including function declaration or function protocol in my code above main() then still the code is running and giving the output as 120. So my question is why a function declaration or function prototype is not affecting the output of my program or is it not necessary to include function declaration or prototype above main().

-------Code-----
#include<stdio.h>
#include<conio.h>

// int fact(int);
main()
{
   int x;
   x=fact(5);
   printf("The factorial is =%d",x);
}

int fact(int n)
{
  int f=1,i;
  for(I=1;i<=n;i++)
       f=f*I;
    return (f);
}


问:
No value supplied for the SQL parameter when geting radio button parameter from JSP
I'm trying to get values of a radio button in JSP. But I got this error.
When the radio button value is "All", the code run fine, but when it's another value, the issue appear. I printed the property and still got the value. I can't figure out where I'm wrong.

Error

```<code>    ERROR c.p.f.e.GlobalExceptionHandler - [URL] : http://localhost:8080/project/motsach/genre
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'theloai': This SqlParameterSource is empty
        at org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:342) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:348) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:204) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at com.project.form.dao.BookDaoImpl.findBookbyGenre(BookDaoImpl.java:119) ~[classes/:na]
        at com.project.form.service.BookServiceImpl.findBookbyGenre(BookServiceImpl.java:59) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at com.sun.proxy.$Proxy111.findBookbyGenre(Unknown Source) ~[na:na]
        at com.project.form.web.BookController.searchGenre(BookController.java:110) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [javax.servlet-api-3.1.0.jar:3.1.0]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [javax.servlet-api-3.1.0.jar:3.1.0]
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577) [jetty-security-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.Server.handle(Server.java:499) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) [jetty-io-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) [jetty-util-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) [jetty-util-9.2.11.v20150529.jar:9.2.11.v20150529]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
</code>```

JSP

```<code><form action="motsach/genre" modelAttribute="bookGenre" method="GET">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th><spring:message code="label.genre" /></th>
                    <th><input type="radio" name="theloai" value="Horror">Horror</th>
                    <th><input type="radio" name="theloai" value="Fantasy">Fantasy</th>
                    <th><input type="radio" name="theloai" value="Comedy">Comedy</th>
                    <th><input type="radio" name="theloai" value="Romantic">Romantic</th>
                    <th><input type="radio" name="theloai" value="All">All</th>
                    <th><input type="submit" value="Find" /></th>
                </tr>
            </thead>
        </table>
    </form>
</code>```

Controller.

```<code>    @RequestMapping(value = { "motsach/genre" }, method = RequestMethod.GET)
    public String searchGenre(Model model, @ModelAttribute("bookGenre") Book book, @RequestParam String theloai) {
        System.out.println(theloai);
        if (theloai.equals("All")) {
            model.addAttribute("books", bookService.findAll());
        } else {
            model.addAttribute("books", bookService.findBookbyGenre(theloai));
        }
        return "redirect:/motsach";
    }
</code>```

DAOImplement
        public List findBookbyGenre(String theloai) {

```<code>        Map<String, Object> params = new HashMap<String, Object>();
        params.put("theloai", theloai);

        String sql = "SELECT * FROM books WHERE theloai=:theloai";

        List<Book> result = null;
        try {
            result = namedParameterJdbcTemplate.query(sql, new BookMapper());
        } catch (EmptyResultDataAccessException e) {
            // do nothing, return null
        }
        return result;
    }

private static final class BookMapper implements RowMapper<Book> {
        public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
            Book book = new Book();
            book.setBook_ID(rs.getInt("id"));
            book.setTensach(rs.getString("tensach"));
            book.setTacgia(rs.getString("tacgia"));
            book.setTheloai(rs.getString("theloai"));
            book.setTinhtrang(rs.getString("tinhtrang"));
            book.setImage(rs.getBytes("image"));
            book.setImage_name(rs.getString("image_name"));
            return book;
        }
    }
</code>```

答:
I had a similar issues and it was basically because the parameter mapping didn't like the spaces in the sql string.  I fixed it by replacing spaces around the equal sign.

Changing this:

```<code>String sql = "SELECT * FROM books WHERE theloai=:theloai";
</code>```

To

```<code>String sql = "SELECT * FROM books WHERE theloai = :theloai";
</code>```

Body:
I'm trying to get values of a radio button in JSP. But I got this error.
When the radio button value is "All", the code run fine, but when it's another value, the issue appear. I printed the property and still got the value. I can't figure out where I'm wrong.

Error

    ERROR c.p.f.e.GlobalExceptionHandler - [URL] : http://localhost:8080/project/motsach/genre
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'theloai': This SqlParameterSource is empty
        at org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:342) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:348) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:204) ~[spring-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at com.project.form.dao.BookDaoImpl.findBookbyGenre(BookDaoImpl.java:119) ~[classes/:na]
        at com.project.form.service.BookServiceImpl.findBookbyGenre(BookServiceImpl.java:59) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
        at com.sun.proxy.$Proxy111.findBookbyGenre(Unknown Source) ~[na:na]
        at com.project.form.web.BookController.searchGenre(BookController.java:110) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [javax.servlet-api-3.1.0.jar:3.1.0]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [javax.servlet-api-3.1.0.jar:3.1.0]
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577) [jetty-security-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) [jetty-servlet-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.Server.handle(Server.java:499) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) [jetty-server-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) [jetty-io-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) [jetty-util-9.2.11.v20150529.jar:9.2.11.v20150529]
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) [jetty-util-9.2.11.v20150529.jar:9.2.11.v20150529]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

JSP

<form action="motsach/genre" modelAttribute="bookGenre" method="GET">

                    <spring:message code="label.genre" />
                    <input type="radio" name="theloai" value="Horror">Horror
                    <input type="radio" name="theloai" value="Fantasy">Fantasy
                    <input type="radio" name="theloai" value="Comedy">Comedy
                    <input type="radio" name="theloai" value="Romantic">Romantic
                    <input type="radio" name="theloai" value="All">All
                    <input type="submit" value="Find" />

    </form>

Controller.

    @RequestMapping(value = { "motsach/genre" }, method = RequestMethod.GET)
    public String searchGenre(Model model, @ModelAttribute("bookGenre") Book book, @RequestParam String theloai) {
        System.out.println(theloai);
        if (theloai.equals("All")) {
            model.addAttribute("books", bookService.findAll());
        } else {
            model.addAttribute("books", bookService.findBookbyGenre(theloai));
        }
        return "redirect:/motsach";
    }

DAOImplement
        public List findBookbyGenre(String theloai) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("theloai", theloai);

        String sql = "SELECT * FROM books WHERE theloai=:theloai";

        List<Book> result = null;
        try {
            result = namedParameterJdbcTemplate.query(sql, new BookMapper());
        } catch (EmptyResultDataAccessException e) {
            // do nothing, return null
        }
        return result;
    }

private static final class BookMapper implements RowMapper<Book> {
        public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
            Book book = new Book();
            book.setBook_ID(rs.getInt("id"));
            book.setTensach(rs.getString("tensach"));
            book.setTacgia(rs.getString("tacgia"));
            book.setTheloai(rs.getString("theloai"));
            book.setTinhtrang(rs.getString("tinhtrang"));
            book.setImage(rs.getBytes("image"));
            book.setImage_name(rs.getString("image_name"));
            return book;
        }
    }

Body:
I had a similar issues and it was basically because the parameter mapping didn't like the spaces in the sql string.  I fixed it by replacing spaces around the equal sign.

Changing this:

String sql = "SELECT * FROM books WHERE theloai=:theloai";

To

String sql = "SELECT * FROM books WHERE theloai = :theloai";


问:
Implicit argument in constructor vs method signature
What difference does the compiler see in BroFinder1 and BroFinder2 that causes the first one to fail? I really need BroFinder1 to work as it is without utilizing patterns such as Aux Pattern.

trait Brother[I] {
  type Bro
  def get: Bro
}

class Foo
object Foo {
  implicit object bro extends Brother[Foo] {
    override type Bro = Bar

    override def get = new Bar
  }
}

class Bar {
  def barSpecificAction(): Unit = ()
}

class BroFinder1[I](implicit val b: Brother[I]) {
  def brotherOf: b.Bro = b.get
}

class BroFinder2[I] {
  def brotherOf(implicit b: Brother[I]): b.Bro = b.get
}

new BroFinder1[Foo].brotherOf.barSpecificAction() // Doesn't compile
//error: Error:(73, 32) value barSpecificAction is not a member of _1.b.Bro
//new BroFinder1[Foo].brotherOf.barSpecificAction();
                          ^
new BroFinder2[Foo].brotherOf.barSpecificAction() // Ok

//scala version: 2.12.4
```

答:
Because new BroFinder2[Foo].brotherOf is of type Bar and Bar has method barSpecificAction but new BroFinder1[Foo].brotherOf is of existential type

```<code>x.Bro forSome { val x: Brother[Foo] }
</code>```

and it doesn't have method barSpecificAction.

Body:
Because new BroFinder2[Foo].brotherOf is of type Bar and Bar has method barSpecificAction but new BroFinder1[Foo].brotherOf is of existential type

x.Bro forSome { val x: Brother[Foo] }

and it doesn't have method barSpecificAction.


问:
Database Design for Facebook Message like, application
Designing a facebook message like application for an internal application.

Is this how you would design it? any way to improve on this design? thanks :)

```<code>MESSAGE
Id
Subject
Content
ReadDate -- datetime
DeletedDate -- datetime
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_COMMENT
Id
MessageId
Content
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_RECIPIENT
Id
MessageId
Recipient -- UserId
ReadDate -- datetime
DeletedDate -- datetime
</code>```

EDIT: there might be something missing with the design or it may be incorrect, let me know.

答:
First, a few minor suggestions from an over-all design perspective:

Since you are using Pascal Case for your field names, you should also use it for the Table names to be consistent.  So MESSAGE_COMMENT should be MessageComment

Do not reuse the field name "Id" since it means something different in each table.  So "Id" in Message should be "MessageId", "Id" in MessageComment should be MessageCommentId, and so on

If the field is a Foreign Key, it should contain the name of the field it points to.  So, "CreatedBy" should be "CreatedByUserId" and "Recipient" should be "RecipientUserId".  Remember, the more explicit you are in naming your fields the less additional comments and documentation you will need and hence it will be less confusing for anyone else to understand what is intended.

Now, as far as the question of "is this an appropriate design to do X" is concerned, you will need to give more details on how you envision this system working.  It appears that the Message is the parent whereas any replies to it are considered MessageComments.  So far that looks ok.

I am not sure why you need "ReadDate" in the main Message table as that also exists at a more accurate level in MessageRecipient.  Unless of course you want to trap the FIRST time it is read but you can still get that from the MessageRecipient table by looking at all Recipients of a particular Message.

Lastly, you should consider not even having "MessageRecipientId" and using "MessageId" and "RecipientUserId" as the composite Primary Key.  This will ensure that you can only have a RecipientUserId on a Message one time without needing to create an additional Unique Index on those two fields.

ContentLicense: CC BY-SA 2.5

Body:
Designing a facebook message like application for an internal application.

Is this how you would design it? any way to improve on this design? thanks :)

MESSAGE
Id
Subject
Content
ReadDate -- datetime
DeletedDate -- datetime
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_COMMENT
Id
MessageId
Content
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_RECIPIENT
Id
MessageId
Recipient -- UserId
ReadDate -- datetime
DeletedDate -- datetime

EDIT: there might be something missing with the design or it may be incorrect, let me know.


问:
Allow no whitespace in required form field
I have a register form which allows users to create usernames and passwords. It requires the username field not be empty, but I need to require that it allow no whitespace at all.

I looked into preg_match() but I can't seem to get that to cooperate with my current code.

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {
    /* Validate Username */
    if (empty(trim($_POST["username"]))) {
        $username_err = "Username Required";
    }
</code>```

答:
No need to use Regex for something so simple. With strrpos() you can find the last occurence of a substring (space character) in a string (username).

If strrpos doesn't find a match, it will return false. So all you have to do is check if strrpos returns anything else but false:

```<code>if (empty(trim($_POST["username"]))) {
    $username_err = "Username Required";
} else if (strrpos($_POST["username"], ' ') !== false){
    $username_space_err = "Space found in username";
}
</code>```

Body:
I have a register form which allows users to create usernames and passwords. It requires the username field not be empty, but I need to require that it allow no whitespace at all.

I looked into preg_match() but I can't seem to get that to cooperate with my current code.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    /* Validate Username */
    if (empty(trim($_POST["username"]))) {
        $username_err = "Username Required";
    }

Body:
No need to use Regex for something so simple. With strrpos() you can find the last occurence of a substring (space character) in a string (username).

If strrpos doesn't find a match, it will return false. So all you have to do is check if strrpos returns anything else but false:

if (empty(trim($_POST["username"]))) {
    $username_err = "Username Required";
} else if (strrpos($_POST["username"], ' ') !== false){
    $username_space_err = "Space found in username";
}


问:
C# CosmosDB How to get only elements in array matching a specific value
I'm using the MongoDB API on CosmosDB.
My document has the following structure inside CosmosDB:

```<code>{
    "_id": "Companies",
    "companies_list": [
         {
            "name":"c1",
            "host": "www.example1.com"
         },{
            "name":"c2",
            "host": "www.example2.com"
         },{
            "name":"c3",
            "host": "www.example3.com"
         },{
            "name":"c4",
            "host": "www.example1.com"
         },
    ]
}
</code>```

Is it possible to project only elements in array which match the host condition?

I tried the following code but it doesn't work:

var filter = Builders<BsonDocument>.Filter.Eq("_id", "Companies");
var filterOnProjection = Builders<BsonDocument>.Filter.Eq("host", "www.example1.com");
var projection = Builders<BsonDocument>.Projection.ElemMatch("companies_list", filterOnProjection);
```

<p>Should return:</p>

```{
    "_id": "Companies",
    "companies_list": [
         {
            "name":"c1",
            "host": "www.example1.com"
        },{
            "name":"c4",
            "host": "www.example1.com"
         },
    ]
}
```

How can I do that?

答:
Some queries just cannot be nicely written using the current version of the C# driver... Try this one:</p>

```<code>var filter = Builders<BsonDocument>.Filter.Eq("_id", "Companies");
var result = collection.Aggregate()
    .Match(filter)
    .Project("{ 'companies_list': { $filter: { input: '$companies_list', cond: { $eq: [ '$$this.host', 'www.example1.com' ] } } } }")
    .ToList();
</code>```

Body:
I'm using the MongoDB API on CosmosDB.
My document has the following structure inside CosmosDB:

{
    "_id": "Companies",
    "companies_list": [
         {
            "name":"c1",
            "host": "www.example1.com"
         },{
            "name":"c2",
            "host": "www.example2.com"
         },{
            "name":"c3",
            "host": "www.example3.com"
         },{
            "name":"c4",
            "host": "www.example1.com"
         },
    ]
}

Is it possible to project only elements in array which match the host condition?

I tried the following code but it doesn't work:

var filter = Builders<BsonDocument>.Filter.Eq("_id", "Companies");
var filterOnProjection = Builders<BsonDocument>.Filter.Eq("host", "www.example1.com");
var projection = Builders<BsonDocument>.Projection.ElemMatch("companies_list", filterOnProjection);

Should return:

{
    "_id": "Companies",
    "companies_list": [
         {
            "name":"c1",
            "host": "www.example1.com"
        },{
            "name":"c4",
            "host": "www.example1.com"
         },
    ]
}

How can I do that?

Body:
Some queries just cannot be nicely written using the current version of the C# driver... Try this one:

var filter = Builders<BsonDocument>.Filter.Eq("_id", "Companies");
var result = collection.Aggregate()
    .Match(filter)
    .Project("{ 'companies_list': { $filter: { input: '$companies_list', cond: { $eq: [ '$$this.host', 'www.example1.com' ] } } } }")
    .ToList();