问:
Get CORS preflight request to follow ODATA routing
I'm using Microsoft.AspNet.WebApi.Cors to enable cross origin request for certain actions on certain controllers (both WebApi & OData) using the [EnableCors(...)] attribute.

This works fine for all the WebApi requests and most OData, but on a particular controller we have two POST actions that are given different routes by the [ODataRoute(...)], and the preflight request for either of those actions is returned a 500 error saying that 'Multiple actions were found that match the request. It looks like CORS doesn't know to look for the OData routing.

Has anyone else experienced this problem and come up with a solution?

Here is the route config:

```<code>// Web API routes
config.MapHttpAttributeRoutes();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: _GetModel());

// Web API configuration and services
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
</code>```

And here is the controller with the duplicate actions:

```<code>[EnableCors("*", "*", "*")]
[ODataRoute("Action-1")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

[EnableCors("*", "*", "*")]
[ODataRoute("Action-2")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}
</code>```

答:
That is definitely not a CORS issue. It is an issue with your route map.

You might wanna take a look at this to solve the 'Multiple actions were found that match the request' issue:
Multiple actions were found that match the request: webapi
or Web API Routing - multiple actions were found that match the request

If you include your Web API route definition in your question, we could help better.

Body:
I'm using Microsoft.AspNet.WebApi.Cors to enable cross origin request for certain actions on certain controllers (both WebApi & OData) using the [EnableCors(...)] attribute.

This works fine for all the WebApi requests and most OData, but on a particular controller we have two POST actions that are given different routes by the [ODataRoute(...)], and the preflight request for either of those actions is returned a 500 error saying that 'Multiple actions were found that match the request. It looks like CORS doesn't know to look for the OData routing.

Has anyone else experienced this problem and come up with a solution?

Here is the route config:

// Web API routes
config.MapHttpAttributeRoutes();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: _GetModel());

// Web API configuration and services
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

And here is the controller with the duplicate actions:

[EnableCors("*", "*", "*")]
[ODataRoute("Action-1")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

[EnableCors("*", "*", "*")]
[ODataRoute("Action-2")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}


来源: stackexchange

问:
How to set a random color for each group of elements looping through an array?
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

```<code><div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div>
</code>```

Javascript : This is what I tried but everything stay on the same color.

```<code>function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});
</code>```

Any solution ?

答:
You could passing with $(this) instead of .element in eachEl function , change like this eachEl($(this))

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

1

2

3

4

5

6

7

8

Javascript : This is what I tried but everything stay on the same color.

function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});

Any solution ?

Body:
You could passing with $(this) instead of .element in eachEl function , change like this eachEl($(this))

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div>


问:
I am little bit confused about escaping closure
I am new to swift and trying to learn when I saw apple doc in it there is a definition about escaping closure like:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

@ other hand I saw a blog where blogger explained about completion handler like:

There are times you put a closure as one of the parameters, but you only want to execute the closure after the function returns. For example, what if you want to print “Hello, world” only after you’ve completely switched to the next ViewController?

So I want to know if completion handler and escaping closure are same or what?

答:
I want to know that completion handler and escaping closure are same
  or what?

Completion and Error Handlers are related to a process that should be done after executing -and returning- a chunk of code (function):

Completion handlers are callbacks that allow a client to perform some
  action when a framework method or function completes its task.
  https://developer.apple.com/library/content/featuredarticles/Short_Practical_Guide_Blocks/

which are -logically- representation of escaping closures.

So, referring to the escaping closures definition, a completion handler is by default is an escaping closures.

For reviewing example(s), you might want to check this answer. Also, if you think that you need more description about what is the escaping closure, you might wan to check this Q&A.


问:
Parse a file for all occurrences of a string and generate key-values in JSON

I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

```<code>[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]
</code>```

This is what I have tried:

```<code>with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json
</code>```

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

答:
import re
import json

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read()

```<code>matcher = re.compile('(?P<g1>[silencedetect @ \w+?\])\s+?silence_start:\s+?(?P<g2>-?\d+?\.\d+?).*?\n([^\[]+?\n)?(?P=g1)\s+?silence_end:\s+?(?P<g3>-?\d+?\.\d+?).+?\|\s+?silence_duration:\s+?(?P<g4>-?\d+?\.\d+?).*?\n')
matchiter= matcher.findall(data)
#(1) (2)
string=""
for i, matchediter in enumerate( matchiter):
    string+= '{"id": {},\n, "silence_start":{},\n"silence_end": {},\n"silence_duration":{}}'. format(i, matchediter.group(g2),matchediter.group(g3),matchediter.group(g4)).

json.dumps(string)
</code>```

(1) You might want to pass some flags like "re.IGNORECASE" to make your script immune to such changes.

(2) I prefer using non greedy sequences recognition patterns, it may have an impact on recognition and speed. Use of named groups is a matter of personal taste.
They can be of use if you decide instead to use a matcher.sub operation to reformat the read() at once, instead of using iteration to rebuild the file text.
I could add the replacement string if you can't figure it out. Else I prefer using .group of match object, it is made for this and may use the names you will choose instead of g1, g2, g3, g4.

Overall I prefer using finditer as it is basically made for this kind of operation, findall yields tuples of captured groups, that is nice but you may sometimes want to use infos relative to the complete match, pattern, positional index in the analyzed text, etc.

Edit: I made the regex robust to any string added after duration figures, and to multiple spaces. I also take the intercalated lines into account, you can capture them by naming the group if you want.
It captures 189 occurrences, there are 190 "silence start" but the last one is not followed by end and duration info.

Body:
I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]

This is what I have tried:

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

Body:
import re
import json

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read()

matcher = re.compile('(?P<g1>[silencedetect @ \w+?\])\s+?silence_start:\s+?(?P<g2>-?\d+?\.\d+?).*?\n([^\[]+?\n)?(?P=g1)\s+?silence_end:\s+?(?P<g3>-?\d+?\.\d+?).+?\|\s+?silence_duration:\s+?(?P<g4>-?\d+?\.\d+?).*?\n')
matchiter= matcher.findall(data)
#(1) (2)
string=""
for i, matchediter in enumerate( matchiter):
    string+= '{"id": {},\n, "silence_start":{},\n"silence_end": {},\n"silence_duration":{}}'. format(i, matchediter.group(g2),matchediter.group(g3),matchediter.group(g4)).

json.dumps(string)

(1) You might want to pass some flags like "re.IGNORECASE" to make your script immune to such changes.

(2) I prefer using non greedy sequences recognition patterns, it may have an impact on recognition and speed. Use of named groups is a matter of personal taste.
They can be of use if you decide instead to use a matcher.sub operation to reformat the read() at once, instead of using iteration to rebuild the file text.
I could add the replacement string if you can't figure it out. Else I prefer using .group of match object, it is made for this and may use the names you will choose instead of g1, g2, g3, g4.

Overall I prefer using finditer as it is basically made for this kind of operation, findall yields tuples of captured groups, that is nice but you may sometimes want to use infos relative to the complete match, pattern, positional index in the analyzed text, etc.

Edit: I made the regex robust to any string added after duration figures, and to multiple spaces. I also take the intercalated lines into account, you can capture them by naming the group if you want.
It captures 189 occurrences, there are 190 "silence start" but the last one is not followed by end and duration info.


问:
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradigm.

Before I simply added middleware in my express server to catch these things, but it looks like there is some kind of pre-hook that is erroring out my requests.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response

I assumed that I could do this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","*")
})
```

<p>or the equivalent but this doesn't seem to fix it. I also of course tried</p>

<pre class="lang-js prettyprint-override"><code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})
</code>```

Still no luck.

答:
That same issue i was facing.

I did a simple change.

```<code>  <modulename>.config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradigm.

Before I simply added middleware in my express server to catch these things, but it looks like there is some kind of pre-hook that is erroring out my requests.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response

I assumed that I could do this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","*")
})

or the equivalent but this doesn't seem to fix it. I also of course tried

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})

Still no luck.

Body:
That same issue i was facing.

I did a simple change.

  <modulename>.config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});


问:
Strange Characters after downloading Chinese table from html
I am using MAC OS X 10.12 system.
I downloaded a table from http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2011/51/06/81/510681114.html
.
The table was encoded with GB2312, however, I used GBK to save the table. The main part of the code is like the following:

```<code>req = urllib2.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' })
page = urllib2.urlopen(req ).read()
tables=BeautifulSoup(page,'html.parser',
parse_only=SoupStrainer(),from_encoding='gbk')
f = open(path, 'w')
for row in tables.findAll("tr"):
    cells = row.findAll("td")
    write_to_file = cells[0].find(text=True) + "," + cells[1].find(text=True)
+ "\n"
    write_to_unicode = write_to_file.encode('utf-8')
    f.write(write_to_unicode)
f.close()
</code>```

I repeated this pattern of code for many other similar tables, however, for some links (like the one I posted here), the Chinese tables downloaded are with strange characters. Here is the example.

```<code>´úÂë,³ÇÏç·ÖÀà,Ãû³Æ
510681114001,121,½ÖµÀ¾ÓÃñÎ¯Ô±»á
510681114201,220,ðÀÃù´å´åÃñÎ¯Ô±»á
510681114202,220,°×º×´å´åÃñÎ¯Ô±»á
510681114203,122,Áâ½Ç´å´åÃñÎ¯Ô±»á
510681114204,122,»Æ¼Òµê´å´åÃñÎ¯Ô±»á
510681114205,122,»¨ÌÁ´å´åÃñÎ¯Ô±»á
510681114206,220,ÔÂÍå´å´åÃñÎ¯Ô±»á
510681114207,122,°×ÔÆ´å´åÃñÎ¯Ô±»á
510681114208,220,Á¹Ë®¾®´å´åÃñÎ¯Ô±»á
510681114209,122,Çàþh´å´åÃñÎ¯Ô±»á
</code>```

What should I do to convert this table to real Chinese, or what should I do to download the Chinese table?

The problem is, if I choose to use GB2312, maybe for this table, it can be shown with Chinese correctly, but for other tables, it will still show these annoying strange characters.

答:
I just got the inspiration from here
http://zzi.io/?p=275
for example

```<code>a=u"´úÂë"
print a.encode('iso-8859-1').decode('gbk')
</code>```

Result is

```<code>代码
</code>```

So this problem is partly solved.

Body:
I am using MAC OS X 10.12 system.
I downloaded a table from http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2011/51/06/81/510681114.html
.
The table was encoded with GB2312, however, I used GBK to save the table. The main part of the code is like the following:

req = urllib2.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' })
page = urllib2.urlopen(req ).read()
tables=BeautifulSoup(page,'html.parser',
parse_only=SoupStrainer(),from_encoding='gbk')
f = open(path, 'w')
for row in tables.findAll("tr"):
    cells = row.findAll("td")
    write_to_file = cells[0].find(text=True) + "," + cells[1].find(text=True)
+ "\n"
    write_to_unicode = write_to_file.encode('utf-8')
    f.write(write_to_unicode)
f.close()

I repeated this pattern of code for many other similar tables, however, for some links (like the one I posted here), the Chinese tables downloaded are with strange characters. Here is the example.

´úÂë,³ÇÏç·ÖÀà,Ãû³Æ
510681114001,121,½ÖµÀ¾ÓÃñÎ¯Ô±»á
510681114201,220,ðÀÃù´å´åÃñÎ¯Ô±»á
510681114202,220,°×º×´å´åÃñÎ¯Ô±»á
510681114203,122,Áâ½Ç´å´åÃñÎ¯Ô±»á
510681114204,122,»Æ¼Òµê´å´åÃñÎ¯Ô±»á
510681114205,122,»¨ÌÁ´å´åÃñÎ¯Ô±»á
510681114206,220,ÔÂÍå´å´åÃñÎ¯Ô±»á
510681114207,122,°×ÔÆ´å´åÃñÎ¯Ô±»á
510681114208,220,Á¹Ë®¾®´å´åÃñÎ¯Ô±»á
510681114209,122,Çàþh´å´åÃñÎ¯Ô±»á

What should I do to convert this table to real Chinese, or what should I do to download the Chinese table?

The problem is, if I choose to use GB2312, maybe for this table, it can be shown with Chinese correctly, but for other tables, it will still show these annoying strange characters.

Body:
I just got the inspiration from here
http://zzi.io/?p=275
for example

a=u"´úÂë"
print a.encode('iso-8859-1').decode('gbk')

Result is

代码

So this problem is partly solved.


问:
What is the reason for PUBACK retransmission when QoS level 1 is set in MQTT?
A student studying MQTT.

To test the MQTT, the broker used mosquitto, the publisher and subscriber used the paho library.

From publishers to brokers, the experiment of sending a message with a payload size of 1000 bytes continuously
We have proceeded.

I set the QoS level to 1 in the publisher, and when I sent the data to the broker, I got a question about checking the data through wireshark.

The above picture captures wireshark. (354) In response to the PUBLISH message, the broker sends a (355) PUBLISH ACK message. The broker then sends a (356) retransmission message, such as 355.

I have verified that publish ack occurs in piggybacked ack form in TCP, but I do not know why 356 is occurring.

Why does 356 occur?
I do not know the mechanism for retransmissions in piggybacked ack if it's a TCP problem.

答:
The broker isn't sending the retransmission, the TCP stack on the machine hosting the broker sent it because it did not receive a TCP sync response for the original in the required timeout (https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Timeout_based_retransmission).

If you check the actual content of 356 it should be exactly the same as 355


问:
Python: NameError: global name 'dot_parser' is not defined
Python is rather new to me.

I am trying to run the titanic machine learning example of the "Machine Learning in Python with Scikit" book. The classification with decision trees works fine (clf is defined properly) but if I want to visualize the decision tree (see code snippet below) I got the following error message (copied from IPython).

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-15b1b4a5d909> in <module>()
      3 dot_data = StringIO.StringIO()
      4 tree.export_graphviz(clf, out_file = dot_data, feature_names = ['PClass', 'AgeFill', 'Gender'])
----> 5 graph = pydot.graph_from_dot_data(dot_data.getvalue())
      6 graph.write_png('titanic.png')

C:\Users\885299\AppData\Local\Continuum\Anaconda32\lib\site-packages\pydot.pyc in graph_from_dot_data(data)

    218     """
    219
--> 220     return dot_parser.parse_dot_data(data)
    221
    222
NameError: global name 'dot_parser' is not defined
</code>```

Can somebody help me?

Code snippet that I used (similar to the book) was:

```<code>import pydot, StringIO

dot_data = StringIO.StringIO()
tree.export_graphviz(clf, out_file = dot_data, feature_names = ['Class', 'Age', 'Gender'])
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_png('titanic.png')

from IPython.core.display import Image
Image(filename = 'titanic.png')
</code>```

答:
Great solutions thanks. I had the same issue on Ubuntu 14.04. Just few words: when i try to uninstall pyparsing and pydot i had a error:

Not uninstalling pydot at /usr/lib/python2.7/dist-packages, owned by OS

i solved upgrading pip with

sudo pip install --upgrade pip

and then following the below commands:

sudo -H pip uninstall pydot
sudo -H pip uninstall pyparsing

and reinstalling:

sudo -H pip install pyparsing
sudo -H pip install pydot

Body:
Python is rather new to me.

I am trying to run the titanic machine learning example of the "Machine Learning in Python with Scikit" book. The classification with decision trees works fine (clf is defined properly) but if I want to visualize the decision tree (see code snippet below) I got the following error message (copied from IPython).

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-15b1b4a5d909> in <module>()
      3 dot_data = StringIO.StringIO()
      4 tree.export_graphviz(clf, out_file = dot_data, feature_names = ['PClass', 'AgeFill', 'Gender'])
----> 5 graph = pydot.graph_from_dot_data(dot_data.getvalue())
      6 graph.write_png('titanic.png')

C:\Users\885299\AppData\Local\Continuum\Anaconda32\lib\site-packages\pydot.pyc in graph_from_dot_data(data)

    218     """
    219
--> 220     return dot_parser.parse_dot_data(data)
    221
    222
NameError: global name 'dot_parser' is not defined

Can somebody help me?

Code snippet that I used (similar to the book) was:

import pydot, StringIO

dot_data = StringIO.StringIO()
tree.export_graphviz(clf, out_file = dot_data, feature_names = ['Class', 'Age', 'Gender'])
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_png('titanic.png')

from IPython.core.display import Image
Image(filename = 'titanic.png')


答:
To achieve this you need to loop through the .elements, choose a random colour from the array then set colour on that element.

The issue with your code was in the final part, as you were providing a selector which retrieved all the .elements to perform the css() call on, instead of the current one in the iteration. Try this, and note the use of this within the each loop to amend each specific element:

$(".elements").each(function() {
  var items = ["blue", "red", "yellow"];
  var colour = items[Math.floor(Math.random() * items.length)];
  $(this).css('color', colour);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <div class="element">1</div>
  <div class="element">2</div>
</div>

<div class="elements">
  <div class="element">3</div>
  <div class="element">4</div>
  <div class="element">5</div>
</div>

<div class="elements">
  <div class="element">6</div>
</div>

<div class="elements">
  <div class="element">7</div>
  <div class="element">8</div>
</div></code>```

Title: How to set a random color for each group of elements looping through an array?

Body:
To achieve this you need to loop through the .elements, choose a random colour from the array then set colour on that element.

The issue with your code was in the final part, as you were providing a selector which retrieved all the .elements to perform the css() call on, instead of the current one in the iteration. Try this, and note the use of this within the each loop to amend each specific element:

$(".elements").each(function() {
  var items = ["blue", "red", "yellow"];
  var colour = items[Math.floor(Math.random() * items.length)];
  $(this).css('color', colour);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <div class="element">1</div>
  <div class="element">2</div>
</div>

<div class="elements">
  <div class="element">3</div>
  <div class="element">4</div>
  <div class="element">5</div>
</div>

<div class="elements">
  <div class="element">6</div>
</div>

<div class="elements">
  <div class="element">7</div>
  <div class="element">8</div>
</div>


问:
angular use [ng-if] on select with options
I am using angular 1.5 and I am trying to use some logic for data I got back from the microsoft graph which is totally dynamic (key and value) and create a dropdown list. I go it working with a input box, but cannot seem to get it working with a select box.

The input box that works

```<code><input type="text" name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">
    <div ng-repeat="uniqueValue in vm.schemaExtentionsUniqueValues">
         <div ng-if="uniqueValue[0] == prop.internalName || uniqueValue[0] == prop.name">
              {{uniqueValue[1]}}
         </div>
    </div>
</code>```

The select box I was trying to build with sementic errors that is not working:

```<code> <select name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">
    <span ng-repeat="uniqueValue in vm.schemaExtentionsUniqueValues">
          <span ng-if="uniqueValue[0] == prop.internalName || uniqueValue[0] == prop.name">
              <option value="{{uniqueValue[1]}}">{{uniqueValue[1]}}</option>
          </span>
    </span>
 </select>
</code>```

The data

Any help will be appreciated. Cheers!

The value the first item in each array entry gets checked against a dynamic property.

答:
I would suggest moving a lot of your logic into your controller. This makes the template 'clean' and places the code where it is more easily accessible in one place.

This would basically mean filtering/sorting the schemaExtentionsUniqueValues before it gets to the template to be displayed.

```<code>schemeExtentionsUniqueValues(propName) {
  // Filter this based on propName passed in;
}
</code>```

The second span can be put into the option btw:

```<code><select name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">
  <span ng-repeat="uniqueValue in vm.schemaExtentionsUniqueValues(prop.name)">
    <option ng-if="uniqueValue[0] == prop.internalName || uniqueValue[0] == prop.name"
      value="{{uniqueValue[1]}}">{{uniqueValue[1]}}</option>
  </span>
</select>
</code>```

If you use your controller to determine what is inside schemaExtentionsUniqueValues then you probably won't need the ng-if on the option tag, and can just display as you would normally.

Body:
I am using angular 1.5 and I am trying to use some logic for data I got back from the microsoft graph which is totally dynamic (key and value) and create a dropdown list. I go it working with a input box, but cannot seem to get it working with a select box.

The input box that works

<input type="text" name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">

              {{uniqueValue[1]}}

The select box I was trying to build with sementic errors that is not working:

 <select name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">

              <option value="{{uniqueValue[1]}}">{{uniqueValue[1]}}</option>

 </select>

The data

Any help will be appreciated. Cheers!

The value the first item in each array entry gets checked against a dynamic property.

Body:
I would suggest moving a lot of your logic into your controller. This makes the template 'clean' and places the code where it is more easily accessible in one place.

This would basically mean filtering/sorting the schemaExtentionsUniqueValues before it gets to the template to be displayed.

schemeExtentionsUniqueValues(propName) {
  // Filter this based on propName passed in;
}

The second span can be put into the option btw:

<select name="{{prop.name}}" ng-model="vm.filterValues[prop.name]">
  <span ng-repeat="uniqueValue in vm.schemaExtentionsUniqueValues(prop.name)">
    <option ng-if="uniqueValue[0] == prop.internalName || uniqueValue[0] == prop.name"
      value="{{uniqueValue[1]}}">{{uniqueValue[1]}}</option>
  </span>
</select>

If you use your controller to determine what is inside schemaExtentionsUniqueValues then you probably won't need the ng-if on the option tag, and can just display as you would normally.


问:
ERROR Sorry! ionic serve can only be run in an Ionic project directory
I am using ionic 1 project. After update cordova i get "[ERROR] Sorry! ionic serve can only be run in an Ionic project directory" error message in ionic 1 project. When i try to create new ionic project by "ionic start myApp tabs" It build me new project and its ionic 2. How can i go back to ionic 1 and run my old project ?</p>

答:
I used the command below and it worked.
ionic state reset --plugins</p>


问:
Android Progress Dialog - Activity has leaked window DecorView
I am making post request using Volley and showing progress dialog. It is working fine but when we change orientation right after making post request. The app crashes with

```<code>AndroidRuntime: FATAL EXCEPTION main
java.lang.IllegalArgumentException: View:DecorView@fbad[Starting Verification Process] not attached to window manager
</code>```

Starting Verification Process is the title of Progress dialog.

How can I resolve this issue?

答:
On destroying your activity Dismiss the dialog.

@Override protected void onDestroy() {
      super.onDestroy();
      if (pDialog!=null && pDialog.isShowing()){
          pDialog.dismiss();
      } }

Body:
I am making post request using Volley and showing progress dialog. It is working fine but when we change orientation right after making post request. The app crashes with

AndroidRuntime: FATAL EXCEPTION main
java.lang.IllegalArgumentException: View:DecorView@fbad[Starting Verification Process] not attached to window manager

Starting Verification Process is the title of Progress dialog.

How can I resolve this issue?


问:
Change image by key arrows is not working.
I created function to change images by clickiking arrows.
My functions is not working. Can you give me some hints?

You can find my code below:

var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    // left arrow
    changeImage();
  } else if (e.keyCode == '39') {
    // right arrow
    changeImage();
  }

}

// document.onkeydown = checkKey();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="images" src="assets/1.jpg" /></code>```

Thank you,
Megi

答:
You have multiple problems with your script.

Remove the () on the end of this line document.onkeydown = checkKey();. Like you did it you will directly call the function instead of assignin it to the event.

The img_index value is not defined in your example and therefore it fails. You could just set it to 0 at the start.

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    // left arrow
    changeImage();
  } else if (e.keyCode == '39') {
    // right arrow
    changeImage();
  }

}

document.onkeydown = checkKey;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="images" src="assets/1.jpg" /></code>```

Body:
I created function to change images by clickiking arrows.
My functions is not working. Can you give me some hints?

You can find my code below:

var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    // left arrow
    changeImage();
  } else if (e.keyCode == '39') {
    // right arrow
    changeImage();
  }

}

// document.onkeydown = checkKey();

Thank you,
Megi

Body:
You have multiple problems with your script.

Remove the () on the end of this line document.onkeydown = checkKey();. Like you did it you will directly call the function instead of assignin it to the event.

The img_index value is not defined in your example and therefore it fails. You could just set it to 0 at the start.

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    // left arrow
    changeImage();
  } else if (e.keyCode == '39') {
    // right arrow
    changeImage();
  }

}

document.onkeydown = checkKey;

<img id="images" src="assets/1.jpg" />


问:
Unable to upload binary to iTunes connect using Xcode 8.3
I am trying to upload my app to iTunes connect for two days but I'm continuously getting an error saying "Operation Failed". Please anyone help.</p>

答: Try to upload your binary with Application Loader instead of Xcode. Application loader will upload you binary to ItunesConnect quickly.</p>


问:
Open image in modal (link in one div img in another)
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}</code>```

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

```

答:
You have missed  JavaScript Library File reference which is most required to perform click operation or any and to enable bootstrap model need bootstrap js. And also you are trying to find modal-icon01 in $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src')); which is not found, try to replace with this jquery
var imageSrc = $(".div-img").find('.front').find('img').attr('src');
here you storing image path by targating to its src by finding it parent class and its tag. check this working fiddle

Body:
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});

.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>


问:
NonUniqueResultException in Projection spring data jpa(spring boot)
I have two JPA(Hibernate) Entity

a) Course

```<code>@Entity
@Table(name="courses")
public class Course implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="course_id")
    private int courseId;

    @Id
    private int id;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="course")
    @JsonIgnore
    private Set<CourseProperty> courseProp;

    .... Rest 25 more columns(Properties)

    ... Setters & Getters for All

}
</code>```

b) CourseProperty

```<code>    @Entity
@Table(name="course_prop")
public class CourseProperty implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
long id;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumns({
    @JoinColumn(name="course_id", referencedColumnName="course_id",insertable=false,updatable=false),
    @JoinColumn(name="status", referencedColumnName="status",insertable=false, updatable=false),
  })
@Where(clause="status = 'live'")
@JsonIgnore
private Course course;

private int hierarchy_element_a;
private int hierarchy_element_b;
private int hierarchy_element_c;

.. Rest 10 more properties....

... Getters & Setters
</code>```

}

Now when I am fetching the Course Object, so obviously complete course object & embedded all course property objects are coming with it. But thats the memory issue for me. I only want 5 or 6 properties from Course & 3 (hierarchy_element) from CourseProperty.(Currently I am just trying fetching all properties for CourseProp).

So I have created One projection

```<code>public interface CourseProjection {

    // Courses Table
    public int getCourseId();
    public Integer getCourseType();
    public Integer getCreatedBy();
    public Timestamp getCreatedOn();
    public int getId();
    public String getName();

    //  Course Prop Table
    public Set<CourseProperty> getCourseProperty();

}
</code>```

The issue is that it is working when when course has only one property meaning one row for Course Property for a particular Course but giving exception when there are multiple rows. stack trace :

```<code>javax.persistence.NonUniqueResultException: result returns more than one elements
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:539) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:54) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.sun.proxy.$Proxy85.findByCourseIdAndStatus(Unknown Source) ~[na:na]
    at com.example.services.CourseService.findByCourseId(CourseService.java:17) ~[classes/:na]
    at com.example.DemoController.findOne(DemoController.java:22) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
</code>```

How do I change my code>?
Also then how to change it if I have to fetch only specific columns of CourseProp in Projection.

My Repo

```<code>public interface CourseRepository extends JpaRepository<Course, Integer>{
    public CourseObjectProjection findByCourseIdAndStatus(int courseId,String status);
}
</code>```

Service

```<code>@Service
public class CourseService {

    @Autowired
    private CourseRepository courseRepository;

    public CourseObjectProjection findByCourseId(int courseId){
        return courseRepository.findByCourseIdAndStatus(courseId, "live");
    }
}
</code>```

Dint write query, uses the JPA Query Methods.

答:
I've the same problem. The solution which works for me is add to projection

```<code>@Value("#{target.id}")
Long getId()
</code>```

Note that @Value("#{target.id}") is very important here.

Also you can change method from findBy to findDistinctBy

Body:
I have two JPA(Hibernate) Entity

a) Course

@Entity
@Table(name="courses")
public class Course implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="course_id")
    private int courseId;

    @Id
    private int id;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="course")
    @JsonIgnore
    private Set<CourseProperty> courseProp;

    .... Rest 25 more columns(Properties)

    ... Setters & Getters for All

}

b) CourseProperty

    @Entity
@Table(name="course_prop")
public class CourseProperty implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
long id;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumns({
    @JoinColumn(name="course_id", referencedColumnName="course_id",insertable=false,updatable=false),
    @JoinColumn(name="status", referencedColumnName="status",insertable=false, updatable=false),
  })
@Where(clause="status = 'live'")
@JsonIgnore
private Course course;

private int hierarchy_element_a;
private int hierarchy_element_b;
private int hierarchy_element_c;

.. Rest 10 more properties....

... Getters & Setters

}

Now when I am fetching the Course Object, so obviously complete course object & embedded all course property objects are coming with it. But thats the memory issue for me. I only want 5 or 6 properties from Course & 3 (hierarchy_element) from CourseProperty.(Currently I am just trying fetching all properties for CourseProp).

So I have created One projection

public interface CourseProjection {

    // Courses Table
    public int getCourseId();
    public Integer getCourseType();
    public Integer getCreatedBy();
    public Timestamp getCreatedOn();
    public int getId();
    public String getName();

    //  Course Prop Table
    public Set<CourseProperty> getCourseProperty();

}

The issue is that it is working when when course has only one property meaning one row for Course Property for a particular Course but giving exception when there are multiple rows. stack trace :

javax.persistence.NonUniqueResultException: result returns more than one elements
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:539) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:54) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.sun.proxy.$Proxy85.findByCourseIdAndStatus(Unknown Source) ~[na:na]
    at com.example.services.CourseService.findByCourseId(CourseService.java:17) ~[classes/:na]
    at com.example.DemoController.findOne(DemoController.java:22) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]

How do I change my code>?
Also then how to change it if I have to fetch only specific columns of CourseProp in Projection.

My Repo

public interface CourseRepository extends JpaRepository<Course, Integer>{
    public CourseObjectProjection findByCourseIdAndStatus(int courseId,String status);
}

Service

@Service
public class CourseService {

    @Autowired
    private CourseRepository courseRepository;

    public CourseObjectProjection findByCourseId(int courseId){
        return courseRepository.findByCourseIdAndStatus(courseId, "live");
    }
}

Dint write query, uses the JPA Query Methods.

Body:
I've the same problem. The solution which works for me is add to projection

@Value("#{target.id}")
Long getId()

Note that @Value("#{target.id}") is very important here.

Also you can change method from findBy to findDistinctBy


答:
you need to pass eachEl(this) instead of eachEl('.element') and then set color of all children of el to randomly selected color;

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).children('.element').css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl(this);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div></code>```

Body:
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

1

2

3

4

5

6

7

8

Javascript : This is what I tried but everything stay on the same color.

function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});

Any solution ?

Body:
you need to pass eachEl(this) instead of eachEl('.element') and then set color of all children of el to randomly selected color;

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).children('.element').css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl(this);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div>


问:
How to Exit windows phone 7 app?

Possible Duplicates:

  Windows Phone 7 close application

  Close a WP7 application programatically?

  Is there a way to programmatically quit my App? (Windows Phone 7)

Hi All,
       Is there any way to exit application in windows phone 7. My problem with EULA.xaml and MainPage.xaml is solved but have to exit my app on MainPage.xaml in either of the cases.
Thanks in advance.

答: This is what you need</p>

Title: How to Exit windows phone 7 app?

Body: This is what you need

ContentLicense: CC BY-SA 2.5


问:
Installing open Cart using XAMPP
I'm getting this error when I try installing open Cart on my system.

Fatal error:

Call to undefined function openssl_random_pseudo_bytes_() in C:\xampp\htdocs\shop\system\library\session.php on line 33

答: First of uncomment curl library in php.ini</p>

Title: Installing open Cart using XAMPP


问:
Viewpager OutofMemory on Fragment onCreateView
I am getting a strange OutOfMemoryError when using a ViewPager with a FragmentPagerAdapter.

The fragments have just a root element, and the Activity is very basic, as I have tried to strip it down to the bare bones to try and figure out where it is occuring.

It seems to happen after the onCreateView() in the Fragment, but can't seem to find the culprit.

Thanks very much for your help.

Activity

```<code>public class Activity_Content_Dialog extends AppCompatActivity {

    private SlideshowAdapter _slideShowAdapter;
    private ViewPager _viewPager;

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

        setContentView(R.layout.activity_content_dialog);

        _slideShowAdapter = new SlideshowAdapter(getSupportFragmentManager());

       _viewPager = (ViewPager) findViewById(R.id.viewPager);
       _viewPager.setAdapter(_slideShowAdapter);
    }
}
</code>```

xml

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_dialog_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>
</code>```

Fragment

```<code> public class Fragment_Empty extends Fragment {

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

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View  view =  inflater.inflate(R.layout.empty_frag,container);

            return view;
        }
    }
</code>```

xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" />
</code>```

Pager Adapter

```<code>public class SlideshowAdapter extends FragmentPagerAdapter {

    public SlideshowAdapter(FragmentManager fm) {
           super(fm);
    }

        @Override
        public Fragment getItem(int position) {
            return new Fragment_Empty();
        }

        @Override
        public int getCount() {
            return 2;
        }

}
</code>```

Finally, here is the error message

```<code>10-29 10:51:26.605  27188-27188/? E/art? Throwing OutOfMemoryError "Failed to allocate a 22227766 byte allocation with 14873872 free bytes and 14MB until OOM"
10-29 10:51:26.605  27188-27188/? E/AndroidRuntime? Error reporting crash
    java.lang.OutOfMemoryError: Failed to allocate a 22227766 byte allocation with 14873872 free bytes and 14MB until OOM
            at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
            at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
            at java.lang.StringBuffer.append(StringBuffer.java:278)
            at java.io.StringWriter.write(StringWriter.java:123)
            at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
            at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
            at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
            at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
            at java.io.PrintWriter.append(PrintWriter.java:691)
            at java.io.PrintWriter.append(PrintWriter.java:31)
            at java.lang.Throwable.printStackTrace(Throwable.java:324)
            at java.lang.Throwable.printStackTrace(Throwable.java:300)
            at android.util.Log.getStackTraceString(Log.java:335)
            at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:59)
            at com.android.internal.os.RuntimeInit.access$200(RuntimeInit.java:43)
            at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:85)
            at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
            at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
</code>```

答:
Change this section:

```<code> View  view =  inflater.inflate(R.layout.empty_frag,container);
</code>```

to:

```<code> View  view =  inflater.inflate(R.layout.empty_frag,container,false);
</code>```

Body:
I am getting a strange OutOfMemoryError when using a ViewPager with a FragmentPagerAdapter.

The fragments have just a root element, and the Activity is very basic, as I have tried to strip it down to the bare bones to try and figure out where it is occuring.

It seems to happen after the onCreateView() in the Fragment, but can't seem to find the culprit.

Thanks very much for your help.

Activity

public class Activity_Content_Dialog extends AppCompatActivity {

    private SlideshowAdapter _slideShowAdapter;
    private ViewPager _viewPager;

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

        setContentView(R.layout.activity_content_dialog);

        _slideShowAdapter = new SlideshowAdapter(getSupportFragmentManager());

       _viewPager = (ViewPager) findViewById(R.id.viewPager);
       _viewPager.setAdapter(_slideShowAdapter);
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_dialog_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Fragment

 public class Fragment_Empty extends Fragment {

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

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View  view =  inflater.inflate(R.layout.empty_frag,container);

            return view;
        }
    }

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" />

Pager Adapter

public class SlideshowAdapter extends FragmentPagerAdapter {

    public SlideshowAdapter(FragmentManager fm) {
           super(fm);
    }

        @Override
        public Fragment getItem(int position) {
            return new Fragment_Empty();
        }

        @Override
        public int getCount() {
            return 2;
        }

}

Finally, here is the error message

10-29 10:51:26.605  27188-27188/? E/art? Throwing OutOfMemoryError "Failed to allocate a 22227766 byte allocation with 14873872 free bytes and 14MB until OOM"
10-29 10:51:26.605  27188-27188/? E/AndroidRuntime? Error reporting crash
    java.lang.OutOfMemoryError: Failed to allocate a 22227766 byte allocation with 14873872 free bytes and 14MB until OOM
            at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
            at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
            at java.lang.StringBuffer.append(StringBuffer.java:278)
            at java.io.StringWriter.write(StringWriter.java:123)
            at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
            at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
            at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
            at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
            at java.io.PrintWriter.append(PrintWriter.java:691)
            at java.io.PrintWriter.append(PrintWriter.java:31)
            at java.lang.Throwable.printStackTrace(Throwable.java:324)
            at java.lang.Throwable.printStackTrace(Throwable.java:300)
            at android.util.Log.getStackTraceString(Log.java:335)
            at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:59)
            at com.android.internal.os.RuntimeInit.access$200(RuntimeInit.java:43)
            at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:85)
            at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
            at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)

Body:
Change this section:

 View  view =  inflater.inflate(R.layout.empty_frag,container);

to:

 View  view =  inflater.inflate(R.layout.empty_frag,container,false);


问:
Is my C# Entity Frameworks project haunted?
I am working on a .NET MVC solution and I get the error below when using the Package Manager Console to Add-Migration or update the SQL server.

System.TypeInitializationException: The type initializer for
  'System.Data.Entity.SqlServer.SqlProviderServices' threw an exception.
  ---> System.TypeLoadException: Method 'ExecuteAsync' in type 'System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy' from
  assembly 'EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' does not have an implementation.

What is interesting is that the code works if it is run on a colleague's computer (i.e. when pulled from git) or when placed into a new project. Other projects in the solution work fine with the Package Manager Console.

When this project was created, Entity Frameworks 6.1.3 was installed before the .Net target framework was changed from 4 to 4.5. This seems to be the cause of the problem, as a new project, created with the target framework set before Entity Frameworks is installed, works fine.

We have tried:

Reinstalling Entity Frameworks 6.1.3 (in fact removing and restoring all nuget packages)

Deleting local branch and removing files from the filesystem, before pulling code (which works on a colleague's PC) from git

Using the nuget command line to clear all local cached packages

Many combinations of the above

In all cases the error persists.

There must be a location where more data or configurations are stored related to the project, which are not managed by git and that are causing the error. Any ideas about where these data or configurations are stored?

答:
I cannot comment yet, need 50 xp.

Anyway please check your app/web config file, see if the version of EF is still the same. If so dubbelcheck your references, you might even need to delete them and add them manualy from you packages folder.


问:
Css Animation: how to make a scrolling text to be repeated
I found a css code to make a text sliding on my webpage from right to left, I found that I can adjust the speed of the slide in this line "animation: scroll-left 20s linear infinite;" where I can change the "seconds" argument.

But I would like the text to be repeated, i.e something like this:

```<code>Please read this page      Please read this page      Please read this      Please read     Pl
</code>```

instead of:

```<code>                                   Please read this page
</code>```

where one have to wait that the text finish the line to come back again.

Here is my code for now:

```<code> <!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<style>

.scroll-left {
 height: 50px;
 overflow: hidden;
 position: relative;
}
.scroll-left p {
 position: absolute;
 width: 100%;
 height: 100%;
 margin: 0;
 line-height: 50px;
 text-align: center;
 /* Starting position */
 -moz-transform:translateX(100%);
 -webkit-transform:translateX(100%);
 transform:translateX(100%);
 /* Apply animation to this element */
 -moz-animation: scroll-left 20s linear infinite;
 -webkit-animation: scroll-left 20s linear infinite;
 animation: scroll-left 20s linear infinite;
}
/* Move it (define the animation) */
@-moz-keyframes scroll-left {
 0%   { -moz-transform: translateX(100%); }
 100% { -moz-transform: translateX(-100%); }
}
@-webkit-keyframes scroll-left {
 0%   { -webkit-transform: translateX(100%); }
 100% { -webkit-transform: translateX(-100%); }
}
@keyframes scroll-left {
 0%   {
 -moz-transform: translateX(100%); /* Browser bug fix */
 -webkit-transform: translateX(100%); /* Browser bug fix */
 transform: translateX(100%);
 }
 100% {
 -moz-transform: translateX(-100%); /* Browser bug fix */
 -webkit-transform: translateX(-100%); /* Browser bug fix */
 transform: translateX(-100%);
 }
}
</style>

<body>

<div class="container">
<br><br><br><br><br><br><br><br><br><br>
  <div class="row">

    <div class="col-sm-offset-3 col-sm-6">

        <div class="scroll-left">
        <p>Please read this page </p>
        </div>

    </div>

  </div>

</div>

</body>
</html>
</code>```

I have tried all the options of this css code, but no one makes what I need.

Thank you

答:
Based on your request of a pure css solution, there's no other way to duplicate the text without appending a new one or using javascript:</p>

```<code>.scroll-left p:before, .scroll-left p:after{
  content: 'Please read this page';
  margin: 0 20px;
}
</code>```

Body:
I found a css code to make a text sliding on my webpage from right to left, I found that I can adjust the speed of the slide in this line "animation: scroll-left 20s linear infinite;" where I can change the "seconds" argument.

But I would like the text to be repeated, i.e something like this:

Please read this page      Please read this page      Please read this      Please read     Pl

instead of:

                                   Please read this page

where one have to wait that the text finish the line to come back again.

Here is my code for now:

 <!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Please read this page

I have tried all the options of this css code, but no one makes what I need.

Thank you

Body:
Based on your request of a pure css solution, there's no other way to duplicate the text without appending a new one or using javascript:

.scroll-left p:before, .scroll-left p:after{
  content: 'Please read this page';
  margin: 0 20px;
}


问:
Pandas equivalent of SQL case when statement to create new variable
I have this df:

```<code>data = np.array([[np.nan, 0], [2, 0], [np.nan, 1]])
df = pd.DataFrame(data=data, columns = ['a', 'b'])
</code>```

which looks like this:

```<code>     a    b
    --------
0   NaN  0.0
1   2.0  0.0
2   NaN  1.0
</code>```

My goal is to create a third column "c" that has a value of 1 when column "a" is equal to NaN and column "b" is equal to 0. "c" would be 0 otherwise. The simple SQL case statement would be:

```<code>(CASE WHEN a IS NULL AND b = 0 THEN 1 ELSE 0 END) AS C
</code>```

The desired output is this:

```<code>     a    b   c
    -----------
0   NaN  0.0  1
1   2.0  0.0  0
2   NaN  1.0  0
</code>```

My (wrong) try:

```<code>df['c'] = np.where(df['a']==np.nan & df['b'] == 0, 1, 0)
</code>```

Many thx.

答:
You cant check series value is NaN using np.nan instead use series.isnull()

Below code gives desired output:

```<code>df['c'] = np.where(df['a'].isnull() & np.array(df['b'] == 0),1,0)
</code>```

Body:
I have this df:

data = np.array([[np.nan, 0], [2, 0], [np.nan, 1]])
df = pd.DataFrame(data=data, columns = ['a', 'b'])

which looks like this:

     a    b
    --------
0   NaN  0.0
1   2.0  0.0
2   NaN  1.0

My goal is to create a third column "c" that has a value of 1 when column "a" is equal to NaN and column "b" is equal to 0. "c" would be 0 otherwise. The simple SQL case statement would be:

(CASE WHEN a IS NULL AND b = 0 THEN 1 ELSE 0 END) AS C

The desired output is this:

     a    b   c
    -----------
0   NaN  0.0  1
1   2.0  0.0  0
2   NaN  1.0  0

My (wrong) try:

df['c'] = np.where(df['a']==np.nan & df['b'] == 0, 1, 0)

Many thx.

Body:
You cant check series value is NaN using np.nan instead use series.isnull()

Below code gives desired output:

df['c'] = np.where(df['a'].isnull() & np.array(df['b'] == 0),1,0)


问:
Looking for a new language that supports both interpreted and native compilation modes
I currently program in Perl, Python, C#, C, C++, Java, and a few other languages, and I'm looking for a new language to use as a primary when doing personal projects.

My current criteria are:

can  be run as an interpreted language (i.e., run without having to wait to compile it);

can be compiled to native code;

are strongly typed (even if optionally);

support macros/templating/code morphing/wtf you want to call it;

has a decent number of libraries for it, or easily accessible to it;

Ideas?  Suggestions?

答:
Common Lisp fits: there is an optional typing, efficient native compilation is available, powerful REPL makes it a perfect choice for scripting, and there is a powerful macro metaprogramming.

OCaml fits as well, with CamlP4 for metaprogramming.


问:
How to set different background color of every three html table rows in alternate
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Any help is appreciated]1

答:
```<code><html>
<head>
<title></title>
<style>
    .green{background-color:white;}
    .blue{background-color:gray;}
</style>
<script>

function alterColor(id){
        var table = document.getElementById(id);
        var rows = table.getElementsByTagName("tr");    //get all the rows
        for(i = 0; i < rows.length; i++){               //alterColor styles
            doalterColor(rows[i], i);

        }
}
function doalterColor(row, i){
if((i % 6 == 0) ||(i % 6 == 1)||(i % 6 == 2)){
        row.className = "blue";
    }else{
        row.className = "green";
    }
}
</script>
</head>
<body onLoad="alterColor('mytable')">

<table id="mytable">
    <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 2</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 3</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 4</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 5</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 6</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 7</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 8</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 9</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 10</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 11</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 12</td>
    <td>cell 2</td>
  </tr><tr>
    <td>cell 13</td>
    <td>cell 2</td>
  </tr>
</table>
</body>
</code>```

Body:
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

Any help is appreciated]1