问:
Javascript object got no access to its properties
I got an object with some information

```<code>function node(id, title, content, isPrivate, dateOfCreation) {
  this.id = id;
  this.title = title;
  this.content = content;
  this.isPrivate = isPrivate;
  this.dateOfCreation = dateOfCreation;
  this.lastEdited = dateOfCreation;
}
</code>```

and I can search for this object by its id

```<code>// this.nodes -> my array of objects
  this.getNodeById = function(nodeId){
    return $.grep(this.nodes, function(e){ return e.id === nodeId; });
  }
</code>```

so this seems to work fine. When testing it I call a method first "test"

```<code>function test(){ // add a new object to the store at this.nodes
  store.addNode(new node("abcde12345", "title one", "content one", false, getCurrentDate()));
}
</code>```

and the object gets added successfully. After that I call a method when initializing the website

```<code>function initEditor(nodeId){
test(); // call the testroutine
nodeId = "abcde12345"; // set the id
var n = store.getNodeById(nodeId); // search for this object in the store (datastore object)

var i = n.id;
var t = n.title;
var c = n.content;
var p = n.isPrivate;
var d = n.dateOfCreation;
var l = n.lastEdited;

debugger;
</code>```

so my problem is, the variables i, t, c, p, d, l are null. And I don't get why because the variable "n" is correct. n stores the object but I can not access the properties of it.

For more information, this is my datastore "class"

```<code>var store = new dataStore();

function dataStore() {
  this.nodes = []; // the array of my objects

  this.getNodes = function() { // get all the objects
    return this.nodes;
  }

  this.addNode = function(entry) { // add a new object
    this.nodes.push(entry);
  }

  this.deleteNode = function(entry) { // delete an object from the array
    var index = this.nodes.indexOf(entry);
    if (index > -1)
      this.nodes.splice(index, 1);
  }

  this.getNodeById = function(nodeId){ // get an object by its id
    return $.grep(this.nodes, function(e){ return e.id === nodeId; });
  }
}
</code>```

答:
The content of the variables is undefined because $.grep(array, function) returns an array with all elements that satisfied a filter function.

If the id will be unique you could change .getNodeById() to always return the first element of the result array:

```<code>this.getNodeById = function(nodeId){
  return $.grep(this.nodes, function(e){ return e.id === nodeId; })[0];
}
</code>```

Or you could use Array.prototype.find() instead of $.grep():

```<code>this.getNodeById = function(nodeId){
  return this.nodes.find(function(e){ return e.id === nodeId; });
}
</code>```

In both cases the result will be undefined if there is no node with the given id.

Body:
I got an object with some information

function node(id, title, content, isPrivate, dateOfCreation) {
  this.id = id;
  this.title = title;
  this.content = content;
  this.isPrivate = isPrivate;
  this.dateOfCreation = dateOfCreation;
  this.lastEdited = dateOfCreation;
}

and I can search for this object by its id

// this.nodes -> my array of objects
  this.getNodeById = function(nodeId){
    return $.grep(this.nodes, function(e){ return e.id === nodeId; });
  }

so this seems to work fine. When testing it I call a method first "test"

function test(){ // add a new object to the store at this.nodes
  store.addNode(new node("abcde12345", "title one", "content one", false, getCurrentDate()));
}

and the object gets added successfully. After that I call a method when initializing the website

function initEditor(nodeId){
test(); // call the testroutine
nodeId = "abcde12345"; // set the id
var n = store.getNodeById(nodeId); // search for this object in the store (datastore object)

var i = n.id;
var t = n.title;
var c = n.content;
var p = n.isPrivate;
var d = n.dateOfCreation;
var l = n.lastEdited;

debugger;

so my problem is, the variables i, t, c, p, d, l are null. And I don't get why because the variable "n" is correct. n stores the object but I can not access the properties of it.

For more information, this is my datastore "class"

var store = new dataStore();

function dataStore() {
  this.nodes = []; // the array of my objects

  this.getNodes = function() { // get all the objects
    return this.nodes;
  }

  this.addNode = function(entry) { // add a new object
    this.nodes.push(entry);
  }

  this.deleteNode = function(entry) { // delete an object from the array
    var index = this.nodes.indexOf(entry);
    if (index > -1)
      this.nodes.splice(index, 1);
  }

  this.getNodeById = function(nodeId){ // get an object by its id
    return $.grep(this.nodes, function(e){ return e.id === nodeId; });
  }
}

Body:
The content of the variables is undefined because $.grep(array, function) returns an array with all elements that satisfied a filter function.

If the id will be unique you could change .getNodeById() to always return the first element of the result array:

this.getNodeById = function(nodeId){
  return $.grep(this.nodes, function(e){ return e.id === nodeId; })[0];
}

Or you could use Array.prototype.find() instead of $.grep():

this.getNodeById = function(nodeId){
  return this.nodes.find(function(e){ return e.id === nodeId; });
}

In both cases the result will be undefined if there is no node with the given id.


来源: stackexchange

问:
Installing systemd inside a ubuntu14.04 docker container - Is it possible?
Am trying to install and configure openstack (devstack) inside docker container. While installing am getting the following error

"Failed to get D-Bus connection: No connection to service manager."

Later, I checked and found that its because of systemd problem. When I tried executing the command systemd

```<code>$>systemd
</code>```

Am getting the following output.

Trying to run as user instance, but the system has not been booted with systemd.

Following are the things which am used.

Host machine OS : Ubuntu 14.04,
Docker Version : Docker version 1.12.4, build 1564f02,
Docker Container OS : Ubuntu 14.04

Can anyone help in this. Thanks in advance.

答:
First of all, systemd expects /sys/fs/cgroup to be mounted. Additionally, you must make the container privileged, or else this happens:

```<code>docker run -v /sys/fs/cgroup:/sys/fs/cgroup:ro --privileged -it --rm ubuntu
</code>```

Then you can go ahead and run /bin/systemd --system --unit=basic.target from bash, and it should run normally (with some errors of course, because Docker does not virtualize an entire system, nor is the library:ubuntu image more than the minimum size required to run properly):

After you have systemd running (semi-)properly, you can simply use a docker stop to stop the container.

This post is based on my own research, a few weeks of it too, for a project I like to call initbuntu (originally I tried to get init running, but running systemd directly was my only solution after all my failed tries). The container will be available on Docker Hub as logandark/initbuntu, Soon™. For now, a broken copy (or not broken, I dunno) is available there at the time of posting.

Sources (kinda):

/sys/fs/cgroup: Here

systemd --system: A StackOverflow post I lost the link to.

ContentLicense: CC BY-SA 3.0

Body:
Am trying to install and configure openstack (devstack) inside docker container. While installing am getting the following error

"Failed to get D-Bus connection: No connection to service manager."

Later, I checked and found that its because of systemd problem. When I tried executing the command systemd

$>systemd

Am getting the following output.

Trying to run as user instance, but the system has not been booted with systemd.

Following are the things which am used.

Host machine OS : Ubuntu 14.04,
Docker Version : Docker version 1.12.4, build 1564f02,
Docker Container OS : Ubuntu 14.04

Can anyone help in this. Thanks in advance.

Body:
First of all, systemd expects /sys/fs/cgroup to be mounted. Additionally, you must make the container privileged, or else this happens:

docker run -v /sys/fs/cgroup:/sys/fs/cgroup:ro --privileged -it --rm ubuntu

Then you can go ahead and run /bin/systemd --system --unit=basic.target from bash, and it should run normally (with some errors of course, because Docker does not virtualize an entire system, nor is the library:ubuntu image more than the minimum size required to run properly):

After you have systemd running (semi-)properly, you can simply use a docker stop to stop the container.

This post is based on my own research, a few weeks of it too, for a project I like to call initbuntu (originally I tried to get init running, but running systemd directly was my only solution after all my failed tries). The container will be available on Docker Hub as logandark/initbuntu, Soon™. For now, a broken copy (or not broken, I dunno) is available there at the time of posting.

Sources (kinda):

/sys/fs/cgroup: Here

systemd --system: A StackOverflow post I lost the link to.


问:
How can I sort my list in selection sort not by index, but by numbers?
The question is just pure curiosity, since I quite  recently started learning algorithms and data structures and applying knowledge in python.
my code is:

```<code>def sorting(listik):
    n = range(len(listik))
    for i in n:
        lowest = min(listik[i:])
        for j in n:
            if listik[j] < listik[lowest:]:
                lowest, listik[j] = i, j

listik = [2,8,5,4,7,1,6,9,10,3]
sorting(listik)
print listik
</code>```

output is correct, but it is sorted by indexes as it's supposed to.
I have seen codes that do that with for loop, but those were not selection sort algorithms, however i can't be 100% sure if this is possible applying this algorithm.(also, would love to hear a comment, if this algorithm could be simplified,w/o using external libraries tho)
Thank you !

答:
The built-in sorted function will sort the list of numbers, regardless of index.</p>

```<code>print(sorted(listik))
</code>```

Body:
The question is just pure curiosity, since I quite  recently started learning algorithms and data structures and applying knowledge in python.
my code is:

def sorting(listik):
    n = range(len(listik))
    for i in n:
        lowest = min(listik[i:])
        for j in n:
            if listik[j] < listik[lowest:]:
                lowest, listik[j] = i, j

listik = [2,8,5,4,7,1,6,9,10,3]
sorting(listik)
print listik

output is correct, but it is sorted by indexes as it's supposed to.
I have seen codes that do that with for loop, but those were not selection sort algorithms, however i can't be 100% sure if this is possible applying this algorithm.(also, would love to hear a comment, if this algorithm could be simplified,w/o using external libraries tho)
Thank you !

Body:
The built-in sorted function will sort the list of numbers, regardless of index.

print(sorted(listik))


问:
How to flip up shapes in shiny by clicking a button?
I want to include a semantic shape element in my shiny app (shapes:
https://semantic-ui.com/modules/shape.html#/usage).
I am able to construct the shape by using shinyjs and shiny.semantic.
But I don't know how to create a button that flips the shape by clicking on it.

Here an example:

Ui.R:

```<code>    library(shiny)

    # Define UI for application that draws a histogram
    shinyUI(semanticPage(
      shinyjs::useShinyjs(),

      div(class="ui text shape",
          div(class="sides",
              div(class="ui header side active","This side starts visible."),
              div(class="ui header side","This is yet another side"),
              div(class="ui header side","This is the last side")
          )
      ),
 tags$button(id="test",class="ui button","Flip")

      ))
</code>```

Server.R:

```<code>library(shiny)
library(shinyjs)
#devtools::install_github("Appsilon/shiny.semantic")
library(shiny.semantic)
#devtools::install_github("Appsilon/highlighter")
library(highlighter)
jsCode <- "
$('.shape').shape();
$('.shape').shape('flip up');
$('test').shape('flip up');
"

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  runjs(jsCode)

})
</code>```

This creates both the button and a shape, but how do I make the button flipping the shape?

答:
I think you need this JS code:

```<code>jsCode <- "
$('.shape').shape();
$('#test').on('click', function(){$('.shape').shape('flip up');});
"
</code>```

Or just:

```<code>jsCode <- "
    $('.shape').shape();
    "
</code>```

and in the ui:

```<code>  tags$button(id="test", class="ui button", "Flip", onclick="$('.shape').shape('flip up');")
</code>```

Body:
I want to include a semantic shape element in my shiny app (shapes:
https://semantic-ui.com/modules/shape.html#/usage).
I am able to construct the shape by using shinyjs and shiny.semantic.
But I don't know how to create a button that flips the shape by clicking on it.

Here an example:

Ui.R:

    library(shiny)

    # Define UI for application that draws a histogram
    shinyUI(semanticPage(
      shinyjs::useShinyjs(),

      div(class="ui text shape",
          div(class="sides",
              div(class="ui header side active","This side starts visible."),
              div(class="ui header side","This is yet another side"),
              div(class="ui header side","This is the last side")
          )
      ),
 tags$button(id="test",class="ui button","Flip")

      ))

Server.R:

library(shiny)
library(shinyjs)
#devtools::install_github("Appsilon/shiny.semantic")
library(shiny.semantic)
#devtools::install_github("Appsilon/highlighter")
library(highlighter)
jsCode <- "
$('.shape').shape();
$('.shape').shape('flip up');
$('test').shape('flip up');
"

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  runjs(jsCode)

})

This creates both the button and a shape, but how do I make the button flipping the shape?

Body:
I think you need this JS code:

jsCode <- "
$('.shape').shape();
$('#test').on('click', function(){$('.shape').shape('flip up');});
"

Or just:

jsCode <- "
    $('.shape').shape();
    "

and in the ui:

  tags$button(id="test", class="ui button", "Flip", onclick="$('.shape').shape('flip up');")


问:
Python win32 service
I have a minimal python win32 service service.py that does nothing special:

```<code>import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "display service"
    # _svc_description_='ddd'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
         win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)
</code>```

When I run:

```<code> service.py install
 service.py start
</code>```

it works fine but when I compile the service.py file with py2exe to service.exe and run the following:

```<code>service.exe install
service.exe start [or trying to restart the service  from the Services.msc]
</code>```

I get this message:

```<code>Could not start the  service name service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion
</code>```

How can I resolve this problem?

Also here the distutil code:

```<code>from distutils.core import setup
import py2exe

py2exe_options = {"includes": ['decimal'],'bundle_files': 1}

setup(console=[{"script":'Service.py'}],
    options={"py2exe": py2exe_options},
    zipfile = None,
    },
 )
</code>```

答:
A quick google came up with this: http://islascruz.org/html/index.php?gadget=StaticPage&action=Page&id=6

It has Italian comments, but I can help you translate some stuff if you don't know Italian.

To truly debug your problem, I guess we will need to see your setup.py distutils script...

Title: Python win32 service

Body:
I have a minimal python win32 service service.py that does nothing special:

import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "display service"
    # _svc_description_='ddd'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
         win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)

When I run:

 service.py install
 service.py start

it works fine but when I compile the service.py file with py2exe to service.exe and run the following:

service.exe install
service.exe start [or trying to restart the service  from the Services.msc]

I get this message:

Could not start the  service name service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion

How can I resolve this problem?

Also here the distutil code:

from distutils.core import setup
import py2exe

py2exe_options = {"includes": ['decimal'],'bundle_files': 1}

setup(console=[{"script":'Service.py'}],
    options={"py2exe": py2exe_options},
    zipfile = None,
    },
 )

ContentLicense: CC BY-SA 2.5


问:
3rd div doesn't touch the top because first and second are under eachother
I don't think the title is a good one but I don't know how to say it in a better way.

I have 3 divs representing an image, user info, user experience.

Due to mobile responsiveness experience must come last, but with the code below the experience div doesn't touch the top.

.one{
 width: 40%;
 height: 50px;
 padding: 5px;
 background-color: #0f0;
}
.two{
 width: 40%;
 height: 70px;
 padding: 5px;
 background-color: #0ff;
 float: left;
}
.three{
 width: 56%;
 height: 100px;
 padding: 5px;
 background-color: #f00;
 float: right;
}
.four{
 width: 500px;
 padding: 5px;
 margin: 5px;
 background-color: #ff0;
 float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="four">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
    <div class="three">3 experience</div>
</div></code>```

How it should look like:

答:
Your 1st div(image) has a margin to the right so 3rd div(experience) won't fit in. So at first you have to wrap the 1st two div's into a container like the example below

```<code><div class="four">
    <div class = "container">
       <div class="one">1 image</div>
       <div class="two">2 info</div>
    </div>
    <div class="three">3 experience</div>
</div>
</code>```

After that you will need to inline the container and set the width of container to 40% and first two div's to 100% like the CSS below.

```<code>.one{
    width: 100%;
    height: 50px;
    padding: 5px;
    background-color: #0f0;
}
.container {
    display:inline-block;
    width:40%;
 }
.two{
    width: 100%;
    height: 70px;
    padding: 5px;
    background-color: #0ff;
    float: left;
}
.three{
    width: 56%;
    height: 100px;
    padding: 5px;
    vertical-align: text-top;
    background-color: #f00;
    float: right;
 }
.four{
    width: 500px;
    padding: 5px;
    margin: 5px;
    background-color: #ff0;
    float: left;
}
</code>```

Here's it on Codepen and Jsfiddle

Body:
I don't think the title is a good one but I don't know how to say it in a better way.

I have 3 divs representing an image, user info, user experience.

Due to mobile responsiveness experience must come last, but with the code below the experience div doesn't touch the top.

.one{
 width: 40%;
 height: 50px;
 padding: 5px;
 background-color: #0f0;
}
.two{
 width: 40%;
 height: 70px;
 padding: 5px;
 background-color: #0ff;
 float: left;
}
.three{
 width: 56%;
 height: 100px;
 padding: 5px;
 background-color: #f00;
 float: right;
}
.four{
 width: 500px;
 padding: 5px;
 margin: 5px;
 background-color: #ff0;
 float: left;
}

1 image

2 info

3 experience

How it should look like:

Body:
Your 1st div(image) has a margin to the right so 3rd div(experience) won't fit in. So at first you have to wrap the 1st two div's into a container like the example below

<div class="four">
    <div class = "container">
       <div class="one">1 image</div>
       <div class="two">2 info</div>
    </div>
    <div class="three">3 experience</div>
</div>

After that you will need to inline the container and set the width of container to 40% and first two div's to 100% like the CSS below.

.one{
    width: 100%;
    height: 50px;
    padding: 5px;
    background-color: #0f0;
}
.container {
    display:inline-block;
    width:40%;
 }
.two{
    width: 100%;
    height: 70px;
    padding: 5px;
    background-color: #0ff;
    float: left;
}
.three{
    width: 56%;
    height: 100px;
    padding: 5px;
    vertical-align: text-top;
    background-color: #f00;
    float: right;
 }
.four{
    width: 500px;
    padding: 5px;
    margin: 5px;
    background-color: #ff0;
    float: left;
}

Here's it on Codepen and Jsfiddle


答:
Wrap div's one and two in a div that sets the width and floats left, then float div three to the right.

Make div class one and two to 100% width so they fill the left div completely, and set the left div to the width you wanted.

HTML:

```<code><div class="four">
    <div class="left">
        <div class="one">
            1 image
        </div>
        <div class="two">
            2 info
        </div>
    </div>
    <div class="three">
        3 experience
    </div>
</div>
</code>```

CSS:

```<code>.one{
    height: 50px;
    padding: 5px;
    background-color: #0f0;
    display: block;
}
.two{
    height: 70px;
    padding: 5px;
    background-color: #0ff;
    display: block;
}
.three{
    width: 56%;
    height: 100px;
    padding: 5px;
    background-color: #f00;
    float: right;
    display: inline-block;
}

.left {
    float: left;
    display: block;
    width: 42%;
}
.four{
    width: 500px;
    padding: 5px;
    margin: 5px;
    background-color: #ff0;
    display: block;
    float: left;
}
</code>```

Title: 3rd div doesn't touch the top because first and second are under eachother

Body:
Wrap div's one and two in a div that sets the width and floats left, then float div three to the right.

Make div class one and two to 100% width so they fill the left div completely, and set the left div to the width you wanted.

HTML:

<div class="four">
    <div class="left">
        <div class="one">
            1 image
        </div>
        <div class="two">
            2 info
        </div>
    </div>
    <div class="three">
        3 experience
    </div>
</div>

CSS:

.one{
    height: 50px;
    padding: 5px;
    background-color: #0f0;
    display: block;
}
.two{
    height: 70px;
    padding: 5px;
    background-color: #0ff;
    display: block;
}
.three{
    width: 56%;
    height: 100px;
    padding: 5px;
    background-color: #f00;
    float: right;
    display: inline-block;
}

.left {
    float: left;
    display: block;
    width: 42%;
}
.four{
    width: 500px;
    padding: 5px;
    margin: 5px;
    background-color: #ff0;
    display: block;
    float: left;
}


问:
Form with radio buttons + logic
I'm trying to create a form (kind of like a quiz) that uses radio buttons and logic to generate and display different diagnostic results. Here is what I have for some of the form structure (there are many more options and the logic is more weighty in the real version):

```<code>  <form action='index.php' method='post'>
  Q1: Does Patient experience Symptom X?
  <br/>
  <label><input type="radio" name="Q1" value="Q1Y"/> Yes</label>
  <label><input type="radio" name="Q1" value="Q1N"/> No</label>
  <br/>
  <br/>

  Q2: Does Patient experience Symptom Y?
  <br/>
  <label><input type="radio" name="Q2" value="Q2Y"/> Yes</label>
  <label><input type="radio" name="Q2" value="Q2N"/> No</label>
  <br/>
  <br/>

  Q3: Does Patient experience Symptom Z?
  <br/>
  <label><input type="radio" name="Q3" value="Q3Y"/> Yes</label>
  <label><input type="radio" name="Q3" value="Q3N"/> No</label>
  <br/>
  <br/>

  <input type="submit" name="formSubmit" value="See Result"/>
  <br/>
</code>```

How do I set up the rest of the logic such that:

```<code>If (Q1Y && Q2Y){
Diagnosis = A;
}

If (Q2Y && Q3Y){
Diagnosis = B;
}
</code>```

Ideally, the diagnosis would store in a variable then show on the current page when the user clicks submit on the form.

答:
Use nested objects to hold the results of all the combinations of answers.

```<code>var allDiagnosis = {
    Q1Y: {
        Q2Y: {
            Q3Y: 'A',
            Q3N: 'B'
        },
        Q2N: {
            Q3Y: 'C',
            Q3N: 'D'
        },
    Q1N: {
        Q2Y: {
            Q3Y: 'E',
            Q3N: 'F'
        },
        Q2N: {
            Q3Y: 'G',
            Q3N: 'H'
        }
    }
}
</code>```

Then get the value of each input, and do:

```<code>var diagnosis = allDiagnosis[value1][value2][value3];
</code>```

Title: Form with radio buttons + logic

Body:
I'm trying to create a form (kind of like a quiz) that uses radio buttons and logic to generate and display different diagnostic results. Here is what I have for some of the form structure (there are many more options and the logic is more weighty in the real version):

  <form action='index.php' method='post'>
  Q1: Does Patient experience Symptom X?

  <input type="radio" name="Q1" value="Q1Y"/> Yes
  <input type="radio" name="Q1" value="Q1N"/> No

  Q2: Does Patient experience Symptom Y?

  <input type="radio" name="Q2" value="Q2Y"/> Yes
  <input type="radio" name="Q2" value="Q2N"/> No

  Q3: Does Patient experience Symptom Z?

  <input type="radio" name="Q3" value="Q3Y"/> Yes
  <input type="radio" name="Q3" value="Q3N"/> No

  <input type="submit" name="formSubmit" value="See Result"/>

How do I set up the rest of the logic such that:

If (Q1Y && Q2Y){
Diagnosis = A;
}

If (Q2Y && Q3Y){
Diagnosis = B;
}

Ideally, the diagnosis would store in a variable then show on the current page when the user clicks submit on the form.

Body:
Use nested objects to hold the results of all the combinations of answers.

var allDiagnosis = {
    Q1Y: {
        Q2Y: {
            Q3Y: 'A',
            Q3N: 'B'
        },
        Q2N: {
            Q3Y: 'C',
            Q3N: 'D'
        },
    Q1N: {
        Q2Y: {
            Q3Y: 'E',
            Q3N: 'F'
        },
        Q2N: {
            Q3Y: 'G',
            Q3N: 'H'
        }
    }
}

Then get the value of each input, and do:

var diagnosis = allDiagnosis[value1][value2][value3];


问:
Cannot Open Connection Error on Azure ML Studio (Running R Script)
I am trying to run an R Script in Azure ML. The code runs for several hours and then stop with this error displayed:

```<code>Error 0063: The following error occurred during evaluation of R script:
---------- Start of error message from R ----------
cannot open the connection

cannot open the connection
----------- End of error message from R -----------
Start time: UTC 04/03/2017 21:09:34
End time: UTC 04/03/2017 23:33:48
</code>```

I have ran the code in RStudio, therefore I am quite confident that the R code is not the problem. Can it be a server issue and how to avoid it?

Thanks

答:
If the code runs, verify if the problem is with the package.
For packages that are not in Azure AML you have to load them as a dataset (after installing locally) See this: https://blogs.msdn.microsoft.com/benjguin/2014/09/24/how-to-upload-an-r-package-to-azure-machine-learning/ </p>

Body:
I am trying to run an R Script in Azure ML. The code runs for several hours and then stop with this error displayed:

Error 0063: The following error occurred during evaluation of R script:
---------- Start of error message from R ----------
cannot open the connection

cannot open the connection
----------- End of error message from R -----------
Start time: UTC 04/03/2017 21:09:34
End time: UTC 04/03/2017 23:33:48

I have ran the code in RStudio, therefore I am quite confident that the R code is not the problem. Can it be a server issue and how to avoid it?

Thanks


问:
How do I include an externally maintained directory as a VisualStudio 2008 C# Project Resource?
I have a  directory which contains externally maintained html help files for a Visual Studio 2008 project.  The directory could potentially contain an arbitrary number of files from build to build.  I know how to add a directory and files to a project including them through the Solution Explorer as required output (content), but in this case I want to always automatically include the specified html directory, all of its subfolders, and all of its files without having to set properties each time a file is added.

I do not want to set the "Build Action" and "Copy to Output Directory" properties each time each time there are changes in the help files.  Another constraint is I am using both an installation project (part of the same solution) and a ClickOnce install depending on the deployment environment.   This seems like it should be incredibly simple, but I have been unable to find an answer so far.

Thanks for the help!

答:
One method you might look into is to tweak the .csproj file and add a post build target to do the copying.  This should be close to what you need:</p>

```<code><ItemGroup>
    <DocumentationFiles Include="DocsDirectory\**\*"/>
</ItemGroup>

<Target Name="AfterBuild">
    <Copy
        SourceFiles="@(DocumentationFiles)"
        DestinationFolder="Output\Docs\"
    />
</Target>
</code>```

Body:
One method you might look into is to tweak the .csproj file and add a post build target to do the copying.  This should be close to what you need:

<ItemGroup>
    <DocumentationFiles Include="DocsDirectory\**\*"/>
</ItemGroup>

<Target Name="AfterBuild">
    <Copy
        SourceFiles="@(DocumentationFiles)"
        DestinationFolder="Output\Docs\"
    />
</Target>


问:
OnItemClickListener not getting invoked on Button inside GridView
I am trying to create a GridView that contains some buttons. The buttons are getting populated but the OnItemClickListener() is not getting invoked when a Button inside the GridView is clicked.

Activty Class Code

```<code>gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ButtonAdapter(getApplicationContext(),answer));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            flipper.showNext();

        }
    });
</code>```

Custom Button Adapter

```<code>public class ButtonAdapter extends BaseAdapter{

private Context context;
private int[] numbers = new int[100];
private String[] answer;

public ButtonAdapter (Context context,String[] answer){
    this.context = context;
    this.answer = answer;
    for(int i=0;i<100;i++){
        numbers[i] = i+1;
    }
}

@Override
public int getCount() {
    return numbers.length;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    View gridView;
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if(view == null) {
        gridView = new View(context);
        gridView = inflater.inflate(R.layout.adapter, null);

    } else {
        gridView = (View) view;
    }

    Button button = (Button) gridView.findViewById(R.id.adapter_button);
    button.setText(numbers[i]+"");

    if(answer[i].equals("null"))
        button.setBackgroundColor(context.getResources().getColor(R.color.reset));
    else
        button.setBackgroundColor(context.getResources().getColor(R.color.optionCheck));

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

adapter.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/adapter_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>
</code>```

acitvity_layout.xml

```<code><GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:numColumns="5"
        android:columnWidth="50dp"
        android:stretchMode="columnWidth"
        android:layout_below="@+id/back"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</code>```

答:
You need to implement an interface and have your Activity subscribe to the specific button presses via the interface listener. Your ButtonAdapter should implement the onClickListener, but your Activity should implement the interface with your custom methods.  The Activity and the Adapter are two different worlds with two different scopes.  Go through this post slowly and follow its logic.  It should set you in the right direction: How to create interface between Fragment and adapter?

The way an adapter works with a Fragment is virtually the same as it does with an Activity.

Body:
I am trying to create a GridView that contains some buttons. The buttons are getting populated but the OnItemClickListener() is not getting invoked when a Button inside the GridView is clicked.

Activty Class Code

gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ButtonAdapter(getApplicationContext(),answer));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            flipper.showNext();

        }
    });

Custom Button Adapter

public class ButtonAdapter extends BaseAdapter{

private Context context;
private int[] numbers = new int[100];
private String[] answer;

public ButtonAdapter (Context context,String[] answer){
    this.context = context;
    this.answer = answer;
    for(int i=0;i<100;i++){
        numbers[i] = i+1;
    }
}

@Override
public int getCount() {
    return numbers.length;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    View gridView;
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if(view == null) {
        gridView = new View(context);
        gridView = inflater.inflate(R.layout.adapter, null);

    } else {
        gridView = (View) view;
    }

    Button button = (Button) gridView.findViewById(R.id.adapter_button);
    button.setText(numbers[i]+"");

    if(answer[i].equals("null"))
        button.setBackgroundColor(context.getResources().getColor(R.color.reset));
    else
        button.setBackgroundColor(context.getResources().getColor(R.color.optionCheck));

    return gridView;
}
}

adapter.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/adapter_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

acitvity_layout.xml

<GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:numColumns="5"
        android:columnWidth="50dp"
        android:stretchMode="columnWidth"
        android:layout_below="@+id/back"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


问:
img url by id bbcode
I want to get the link from src atribute by specific ID

For example I have following bbcode tags:

```<code>[img alt="" src="http://google.com" id="image"]
[img src="http://google.com" id="image2" alt=""]
[img id="image3" src="http://google.com" alt=""]
</code>```

I tried with \[img(?:[^]]+src="(.+?)"[^]]+(?:id|class)="image"|[^]]+(?:id|class)="image"[^]]+src="(.+?)")

but for the second image it doesnt work

https://regex101.com/r/7owPlM/3

答:
You could try something like this(https://regex101.com/r/SDYM7u/3):

```<code>\[img\s(?:.*?src="(.*?)".*?)?id="image"(?:.*?src="(.*?)".*?)?[^\]]*]
</code>```

using flags g and m.The only downside is that in this case you will need to check both capture group 1 and 2 to find your url. When src precedes id attribute then the match is stored in Group 1 but when id attribute precedes src then the url is stored in group 2.

Title: img url by id bbcode

Body:
I want to get the link from src atribute by specific ID

For example I have following bbcode tags:

[img alt="" src="http://google.com" id="image"]
[img src="http://google.com" id="image2" alt=""]
[img id="image3" src="http://google.com" alt=""]

I tried with \[img(?:[^]]+src="(.+?)"[^]]+(?:id|class)="image"|[^]]+(?:id|class)="image"[^]]+src="(.+?)")

but for the second image it doesnt work

https://regex101.com/r/7owPlM/3

Body:
You could try something like this(https://regex101.com/r/SDYM7u/3):

\[img\s(?:.*?src="(.*?)".*?)?id="image"(?:.*?src="(.*?)".*?)?[^\]]*]

using flags g and m.The only downside is that in this case you will need to check both capture group 1 and 2 to find your url. When src precedes id attribute then the match is stored in Group 1 but when id attribute precedes src then the url is stored in group 2.


Title: How can I sort my list in selection sort not by index, but by numbers?

Body:
you can use sort :

>>> listik = [2,8,5,4,7,1,6,9,10,3]
>>> listik.sort()
>>> listik
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


问:
Failed to resolve com.android.support:support-compat:25.4.0
I am trying to include this library to my project by adding

```<code>compile 'jp.wasabeef:recyclerview-animators:2.2.7'
</code>```

to the dependencies. When the graddle sync happens an error produced like below

Failed to resolve com.android.support:support-recycleriew-v7:25.4.0

Failed to resolve com.android.support:support-compat:25.4.0

Failed to resolve com.android.support:support-core-ui:25.4.0

The graddle dependencies looks like

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:recyclerview-v7:25.4.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.volley:volley:1.0.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-core:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
compile 'com.android.support:support-core-ui:25.4.0'
compile 'com.android.support:support-compat:25.4.0'
compile 'jp.wasabeef:recyclerview-animators:2.2.7'

}
</code>```

What is wrong here?

答:
```<code>Failed to resolve com.android.support:support-recycleview:25.4.0
</code>```

There is no library by that name. There is com.android.support:recyclerview-v7:25.4.0.

```<code>Failed to resolve com.android.support:support-compat:25.4.0
Failed to resolve com.android.support:support-core-ui:25.4.0
</code>```

These are in the new Google Maven repo. Add maven { url "https://maven.google.com" } to your repositories closure, as shown in the documentation.

Body:
I am trying to include this library to my project by adding

compile 'jp.wasabeef:recyclerview-animators:2.2.7'

to the dependencies. When the graddle sync happens an error produced like below

Failed to resolve com.android.support:support-recycleriew-v7:25.4.0

Failed to resolve com.android.support:support-compat:25.4.0

Failed to resolve com.android.support:support-core-ui:25.4.0

The graddle dependencies looks like

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:recyclerview-v7:25.4.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.volley:volley:1.0.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-core:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
compile 'com.android.support:support-core-ui:25.4.0'
compile 'com.android.support:support-compat:25.4.0'
compile 'jp.wasabeef:recyclerview-animators:2.2.7'

}

What is wrong here?

Body:
Failed to resolve com.android.support:support-recycleview:25.4.0

There is no library by that name. There is com.android.support:recyclerview-v7:25.4.0.

Failed to resolve com.android.support:support-compat:25.4.0
Failed to resolve com.android.support:support-core-ui:25.4.0

These are in the new Google Maven repo. Add maven { url "https://maven.google.com" } to your repositories closure, as shown in the documentation.


问:
Wrapper for template callback?

Immediate callback

Consider the following example:

```<code>template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    callback(42);
}

int main()
{
    call_me_back([](const int & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

Here I provide call_me_back with a lambda that accepts an int. call_me_back calls callback after some long calculation, and callback prints it out. Easy as cake.

Now, say that depending on the execution, call_me_back needs to call callback either with an int or with some other type. We can edit the previous example to

```<code>template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    if(rand() % 2)
        callback(42);
    else
        callback("Kill all the humans.");
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

So far so good. Now callback can do all sorts of tricks and handle value depending on its type.

Delayed callback

Now, back to the first example. Say that call_me_back is not ready to immediately call callback with an int. What it can do, however, is to store the callback somewhere, and then call it later.

For example:

```<code>std :: function <void(const int &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = callback;
}

void ready_to_answer()
{
    the_callback(42);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

Now, instead of immediately calling callback, call_me_back stores callback in an std :: function <void(const int &)> object (I know, it's in the global scope, bear with me). Many things can then happen and at some point someone can call ready_to_answer, which retrieves the previously stored callback and calls it. For example, ready_to_answer can be called by another thread, but there is a whole lot of reasons why one would need a paradigm like this, where the callback can be stored and called later.

The problem

What if I wanted to implement the second example, but with a delayed callback?. I don't seem to be able to get my head around this.

I can imagine that std :: function is implemented with a virtual call operator that accepts some specific type. The std :: function then wraps a pointer / reference to a template wrapper class that stores the actual lambda and implements the call operator by forwarding its argument to the lambda it's storing. Nice and easy. But I can't have template virtual methods!

I have tried coming up with all sorts of solutions, but I couldn't find anything that could reasonably work. Is this really impossible to do? Is it impossible to have some externally provided lambda that accepts a const auto & argument stored somewhere, and then call it later?

答:
You are correct, it is impossible for an unbounded set of types, but you can do it if you know all the types in advance:</p>

```<code>std :: function <void(const std :: variant<int, std :: string> &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = [callback](const auto & arg)
    {
        std :: visit(callback, arg);
    };
}

template <typename T> void ready_to_answer(const T & x)
{
    the_callback(x);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });

    if (std :: rand() % 2)
    {
        ready_to_answer(42);
    }
    else
    {
        ready_to_answer("Hi!");
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Wrapper for template callback?

Body:
Immediate callback

Consider the following example:

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    callback(42);
}

int main()
{
    call_me_back([](const int & value)
    {
        std :: cout << value << std :: endl;
    });
}

Here I provide call_me_back with a lambda that accepts an int. call_me_back calls callback after some long calculation, and callback prints it out. Easy as cake.

Now, say that depending on the execution, call_me_back needs to call callback either with an int or with some other type. We can edit the previous example to

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    if(rand() % 2)
        callback(42);
    else
        callback("Kill all the humans.");
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

So far so good. Now callback can do all sorts of tricks and handle value depending on its type.

Delayed callback

Now, back to the first example. Say that call_me_back is not ready to immediately call callback with an int. What it can do, however, is to store the callback somewhere, and then call it later.

For example:

std :: function <void(const int &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = callback;
}

void ready_to_answer()
{
    the_callback(42);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

Now, instead of immediately calling callback, call_me_back stores callback in an std :: function <void(const int &)> object (I know, it's in the global scope, bear with me). Many things can then happen and at some point someone can call ready_to_answer, which retrieves the previously stored callback and calls it. For example, ready_to_answer can be called by another thread, but there is a whole lot of reasons why one would need a paradigm like this, where the callback can be stored and called later.

The problem

What if I wanted to implement the second example, but with a delayed callback?. I don't seem to be able to get my head around this.

I can imagine that std :: function is implemented with a virtual call operator that accepts some specific type. The std :: function then wraps a pointer / reference to a template wrapper class that stores the actual lambda and implements the call operator by forwarding its argument to the lambda it's storing. Nice and easy. But I can't have template virtual methods!

I have tried coming up with all sorts of solutions, but I couldn't find anything that could reasonably work. Is this really impossible to do? Is it impossible to have some externally provided lambda that accepts a const auto & argument stored somewhere, and then call it later?

Body:
You are correct, it is impossible for an unbounded set of types, but you can do it if you know all the types in advance:

std :: function <void(const std :: variant<int, std :: string> &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = [callback](const auto & arg)
    {
        std :: visit(callback, arg);
    };
}

template <typename T> void ready_to_answer(const T & x)
{
    the_callback(x);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });

    if (std :: rand() % 2)
    {
        ready_to_answer(42);
    }
    else
    {
        ready_to_answer("Hi!");
    }
}


问:
Update List base on another list in JavaScript
How Can I update an Array based on another Array?

This is how I tried to do:

var ref = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

var elem = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

for (var i = 0; i < ref.length; i++) {

 ref.indexOf(elem[i]) === -1 ? ref.push(elem[i]) : console.log("This item already exists");

}
console.log(ref);
console.log(elem);```

This Loop caused an error because the length is changing after each iterate.

What I want is, to add each element from elem object if it doesn't exist in arr object and of course stays in JOSN format. In my example, it doesn't have to change.

答:
To avoid nested loops, you could build a Set with each of the keys that you have in ref. Let's say you consider the name to be the identifying key, then it would look like this:

```<code>ref = ref.concat(elem.filter(function (o) {
    return !this.has(o.name)
}, new Set(ref.map(o => o.name))));
</code>```

So, this builds the Set by taking all the names in ref, passes that as this to a filter callback, which checks for each elem entry whether it has a name that is in the set. If so, it is excluded by the filter. This filtered result is concatenated to ref.

If your identifying key is something else, like the combination name and title, then adjust the function that is used in the last map(.......), and apply the same logic in has().

Here is a fiddle (with slightly different sample data) that uses the combination of name and title as identifying key:

var ref = [{
  "name": "Jack",
  "title": "Manager",
  "description": "",
}, {
  "name": "Steve",
  "title": "CEO",
  "description": "A test description",
}];

var elem = [{
  "name": "Jack",
  "title": "Manager",
  "description": "",
}, {
  "name": "Steve",
  "title": "Programmer",
  "description": "Java addict",
}];

ref = ref.concat(elem.filter(function (o) {
    return !this.has(JSON.stringify([o.name, o.title]))
}, new Set(ref.map(o => JSON.stringify([o.name, o.title])))));

console.log(ref);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
How Can I update an Array based on another Array?

This is how I tried to do:

var ref = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

var elem = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

for (var i = 0; i < ref.length; i++) {

 ref.indexOf(elem[i]) === -1 ? ref.push(elem[i]) : console.log("This item already exists");

}
console.log(ref);
console.log(elem);

This Loop caused an error because the length is changing after each iterate.

What I want is, to add each element from elem object if it doesn't exist in arr object and of course stays in JOSN format. In my example, it doesn't have to change.

Body:
To avoid nested loops, you could build a Set with each of the keys that you have in ref. Let's say you consider the name to be the identifying key, then it would look like this:

ref = ref.concat(elem.filter(function (o) {
    return !this.has(o.name)
}, new Set(ref.map(o => o.name))));

So, this builds the Set by taking all the names in ref, passes that as this to a filter callback, which checks for each elem entry whether it has a name that is in the set. If so, it is excluded by the filter. This filtered result is concatenated to ref.

If your identifying key is something else, like the combination name and title, then adjust the function that is used in the last map(.......), and apply the same logic in has().

Here is a fiddle (with slightly different sample data) that uses the combination of name and title as identifying key:

var ref = [{
  "name": "Jack",
  "title": "Manager",
  "description": "",
}, {
  "name": "Steve",
  "title": "CEO",
  "description": "A test description",
}];

var elem = [{
  "name": "Jack",
  "title": "Manager",
  "description": "",
}, {
  "name": "Steve",
  "title": "Programmer",
  "description": "Java addict",
}];

ref = ref.concat(elem.filter(function (o) {
    return !this.has(JSON.stringify([o.name, o.title]))
}, new Set(ref.map(o => JSON.stringify([o.name, o.title])))));

console.log(ref);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Passing in a value to a usercontrol through a foreach loop
in my asp.net mark up I have a foreach loop that iterates through a simple list. In this foreach loop I am adding a new user control and attempting to pass in the value from the loop. However, this value just wont budge and get inside that damn  control! Anyone have any suggestions?

```<code><%foreach (userInfo i in this.items)
    { %>
        <uc1:ItemControl ID="ItemControl" runat="server" UserID='<%#Eval("userID") %>'/>
<%} %>
</code>```

userID is a public property in the control, when it goes to set, the value is just literally : <%#Eval("userID") %>. I've tried #Bind and =Value but nothing seems to work.

Any help would be appreciated!

答:
Looks like the perfect use case for a repeater:

```<code><asp:Repeater runat="server" id="myRepeater">
   <uc1:ItemControl ID="ItemControl" runat="server" />
</asp:Repeater>
</code>```

You can databind your list (this.items) to the repeater and in the code behind, in the DataBind event set the UserID property of the ItemControl control.

The reason your approach will not work is that IDs have to be unique in a page.

Body:
in my asp.net mark up I have a foreach loop that iterates through a simple list. In this foreach loop I am adding a new user control and attempting to pass in the value from the loop. However, this value just wont budge and get inside that damn  control! Anyone have any suggestions?

<%foreach (userInfo i in this.items)
    { %>
        <uc1:ItemControl ID="ItemControl" runat="server" UserID='<%#Eval("userID") %>'/>
<%} %>

userID is a public property in the control, when it goes to set, the value is just literally : <%#Eval("userID") %>. I've tried #Bind and =Value but nothing seems to work.

Any help would be appreciated!

Body:
Looks like the perfect use case for a repeater:

<asp:Repeater runat="server" id="myRepeater">
   <uc1:ItemControl ID="ItemControl" runat="server" />
</asp:Repeater>

You can databind your list (this.items) to the repeater and in the code behind, in the DataBind event set the UserID property of the ItemControl control.

The reason your approach will not work is that IDs have to be unique in a page.


问:
Scraping data with python
I'm working on a program to scrape address data from companies from a website. For this, I already have built a list with the links where this data can be found. On each of those links, the page source of the data I need looks like this:

http://imgur.com/a/V0kBK

For some reason though, I cannot seem to fetch the first line of the address, in this case "'t walletje 104 101"

All the other information comes through fine, as you can see here:

http://imgur.com/a/aUmSI

This is my code:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import string
import urllib

urllist=[]
url1="http://www.bisy.be/"

fname = "test2.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if line.startswith(" <tr class="):
        words= line.split()
        url2 = words[6]
        url3 = url1 + url2[1:48]
        urllist.append(url3)

for link in urllist:
    document = urllib.request.urlopen(link)
    html = document.read()
    soup = BeautifulSoup(html,"html.parser")
    name = soup.find("br")
    name2 = name.text.strip()
    print (name2)
</code>```

This code is doing the basics so far. Once everything works I will clean it and finetune it a bit. Is there anyone who can help me?
An example link for the people who want to check out the page source: http://www.bisy.be/?q=nl/bedrijf_fiche&id=KNO01C2015&nr=2027420160

Is there anyone who can point me in the right direction?

答:
this is a workaround by finding p tag with specific font size:

```<code>elements = soup.find_all("p")
for tag in elements:
    try:
        if "9pt" in tag["style"]:
            details = tag.text
            print(details)
    except:
        pass
</code>```

Title: Scraping data with python

Body:
I'm working on a program to scrape address data from companies from a website. For this, I already have built a list with the links where this data can be found. On each of those links, the page source of the data I need looks like this:

http://imgur.com/a/V0kBK

For some reason though, I cannot seem to fetch the first line of the address, in this case "'t walletje 104 101"

All the other information comes through fine, as you can see here:

http://imgur.com/a/aUmSI

This is my code:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import string
import urllib

urllist=[]
url1="http://www.bisy.be/"

fname = "test2.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if line.startswith(" <tr class="):
        words= line.split()
        url2 = words[6]
        url3 = url1 + url2[1:48]
        urllist.append(url3)

for link in urllist:
    document = urllib.request.urlopen(link)
    html = document.read()
    soup = BeautifulSoup(html,"html.parser")
    name = soup.find("br")
    name2 = name.text.strip()
    print (name2)

This code is doing the basics so far. Once everything works I will clean it and finetune it a bit. Is there anyone who can help me?
An example link for the people who want to check out the page source: http://www.bisy.be/?q=nl/bedrijf_fiche&id=KNO01C2015&nr=2027420160

Is there anyone who can point me in the right direction?

Body:
this is a workaround by finding p tag with specific font size:

elements = soup.find_all("p")
for tag in elements:
    try:
        if "9pt" in tag["style"]:
            details = tag.text
            print(details)
    except:
        pass


问:
Why is my service running before anything else?
I'm new to services, factories, etc; so there's still a lot I don't understand.

I have a ui-grid. When a row is selected, I want to use that data as a param in a service to get REST data to populate another grid.

This is what I think it should be doing:

gridOne is registered => Row Selected => Send selectedRow.id to Service => Service GETs data => data populates grid 2

This is what its actually doing:

Service GETs data => Error because selectedRow.id is not defined.

```<code>01| $scope.gridOne.onRegisterApi = function(gridApi){
02|     $scope.gridOneApi = gridApi
03|     $scope.gridOneApi.selection.on.rowSelectionChanged(null, function(row){
04|         $scope.gridOneSelectedRow = $scope.gridOneApi.selection.getSelectedRows()[0]
05|
06|         // v---Breakpoint on this line triggered before any grid is built---v
07|         myService.getAllObjects($scope.gridOneSelectedRow.id).then(response => {
08|             $scope.grid2.data = response
09|         }
10|     })
11| }
</code>```

My service looks like this:

```<code>app.service('myService', function ($http) {

    return {
        get: getObjects
    }

    function getOjects(id) {
        let url = `http://${domain}/object/${id}`
        return $http.get(url).then(response => {
            return response
        }).catch(error => {
            return error
        })
    }
}
</code>```

Why is the service function running before everything else?

答:
if you are writing a service, you should not return a object/function/something, your implementation function is used as a constructor to newed up and create instance of your service.

so if you want to use a service, a sample for your myService will be

```<code>app.service('myService', function ($http) {
    function getOjects(id) {
        //you should properly replace your domain, may be with the same domain by default if you start from object/...
        let url = `http://${domain}/object/+ id`
        return $http.get(url).then(response => {
            return response.data
        }).catch(error => {
            return error
        })
    }
    this.getAllObjects = getOjects;
})
</code>```

in case of factory

```<code>app.factory('myService', function ($http) {
    function getOjects(id) {
        //you should properly replace your domain, may be with the same domain by default if you start from object/...
        let url = `http://${domain}/object/+ id`
        return $http.get(url).then(response => {
            return response.data
        }).catch(error => {
            return error
        })
    }
    return {getAllObjects: getOjects};
})
</code>```

and in the injecting end you don't need to change the code the way you are using it to load data, just wrote the code in sync of use
and also, I wnder, why you are trying to select before the data is loaded, and inside the handler of row selection you want to call the data when now row is present at all, if the data is not loaded, right? I hope you are loading data for another grid grid2 on selection of a row of grid1, and then want to load corresponding data related to that row to grid2.

Feel free to comment, whatever doubt you still have.

Good Luck :)

Body:
I'm new to services, factories, etc; so there's still a lot I don't understand.

I have a ui-grid. When a row is selected, I want to use that data as a param in a service to get REST data to populate another grid.

This is what I think it should be doing:

gridOne is registered => Row Selected => Send selectedRow.id to Service => Service GETs data => data populates grid 2

This is what its actually doing:

Service GETs data => Error because selectedRow.id is not defined.

01| $scope.gridOne.onRegisterApi = function(gridApi){
02|     $scope.gridOneApi = gridApi
03|     $scope.gridOneApi.selection.on.rowSelectionChanged(null, function(row){
04|         $scope.gridOneSelectedRow = $scope.gridOneApi.selection.getSelectedRows()[0]
05|
06|         // v---Breakpoint on this line triggered before any grid is built---v
07|         myService.getAllObjects($scope.gridOneSelectedRow.id).then(response => {
08|             $scope.grid2.data = response
09|         }
10|     })
11| }

My service looks like this:

app.service('myService', function ($http) {

    return {
        get: getObjects
    }

    function getOjects(id) {
        let url = `http://${domain}/object/${id}`
        return $http.get(url).then(response => {
            return response
        }).catch(error => {
            return error
        })
    }
}

Why is the service function running before everything else?

Body:
if you are writing a service, you should not return a object/function/something, your implementation function is used as a constructor to newed up and create instance of your service.

so if you want to use a service, a sample for your myService will be

app.service('myService', function ($http) {
    function getOjects(id) {
        //you should properly replace your domain, may be with the same domain by default if you start from object/...
        let url = `http://${domain}/object/+ id`
        return $http.get(url).then(response => {
            return response.data
        }).catch(error => {
            return error
        })
    }
    this.getAllObjects = getOjects;
})

in case of factory

app.factory('myService', function ($http) {
    function getOjects(id) {
        //you should properly replace your domain, may be with the same domain by default if you start from object/...
        let url = `http://${domain}/object/+ id`
        return $http.get(url).then(response => {
            return response.data
        }).catch(error => {
            return error
        })
    }
    return {getAllObjects: getOjects};
})

and in the injecting end you don't need to change the code the way you are using it to load data, just wrote the code in sync of use
and also, I wnder, why you are trying to select before the data is loaded, and inside the handler of row selection you want to call the data when now row is present at all, if the data is not loaded, right? I hope you are loading data for another grid grid2 on selection of a row of grid1, and then want to load corresponding data related to that row to grid2.

Feel free to comment, whatever doubt you still have.

Good Luck :)


问:
Using MPI on Slurm, is there a way to send messages between separate jobs?
I'm new to using MPI (mpi4py) and Slurm. I need to run about 50000 tasks, so to obey the administrator-set limit of about 1000, I've been running them like this:

sbrunner.sh:

```<code>#!/bin/bash
for i in {1..50}
do
   sbatch m2slurm.sh $i
   sleep 0.1
done
</code>```

m2slurm.sh:

```<code>#!/bin/bash
#SBATCH --job-name=mpi
#SBATCH --output=mpi_50000.out
#SBATCH --time=0:10:00
#SBATCH --ntasks=1000

srun --mpi=pmi2 --output=mpi_50k${1}.out python par.py data_50000.pkl ${1} > ${1}py.out 2> ${1}.err
</code>```

par.py (irrelevant stuff omitted):

```<code>offset = (int(sys.argv[2])-1)*1000
comm = MPI.COMM_WORLD
k = comm.Get_rank()
d = data[k+offset]

# ... do something with d ...

allresults = comm.gather(result, root=0)
comm.Barrier()
if k == 0:
    print(allresults)
</code>```

Is this a sensible way to get around the limit of 1000 tasks?

Is there a better way to consolidate results? I now have 50 files I have to concatenate manually. Is there some comm_world that can exist between different jobs?

答:
I think you need to make your application divide the work among 1000 tasks (MPI ranks) and consolidate the results after that with MPI collective calls i.e. MPI_Reduce or MPI_AllReduce calls.

trying to work around the limit won't help you as the jobs you started will be queued one after another.

Jobs arrays will give similar behavior like what you did in the batch file you provided. So still your application must be able to processes all data items given only N tasks(MPI ranks).

No need to pool to make sure all other jobs are finished take a look at slurm job dependency parameter
https://hpc.nih.gov/docs/job_dependencies.html

Edit:

You can use job dependeny to make a new job that will run after all other jobs finish and this job will collect the results and merge them into one big file. I still believe you are over thinking the obvious solution make rank 0 (master collect all results and save them to the disk)

Body:
I'm new to using MPI (mpi4py) and Slurm. I need to run about 50000 tasks, so to obey the administrator-set limit of about 1000, I've been running them like this:

sbrunner.sh:

#!/bin/bash
for i in {1..50}
do
   sbatch m2slurm.sh $i
   sleep 0.1
done

m2slurm.sh:

#!/bin/bash
#SBATCH --job-name=mpi
#SBATCH --output=mpi_50000.out
#SBATCH --time=0:10:00
#SBATCH --ntasks=1000

srun --mpi=pmi2 --output=mpi_50k${1}.out python par.py data_50000.pkl ${1} > ${1}py.out 2> ${1}.err

par.py (irrelevant stuff omitted):

offset = (int(sys.argv[2])-1)*1000
comm = MPI.COMM_WORLD
k = comm.Get_rank()
d = data[k+offset]

# ... do something with d ...

allresults = comm.gather(result, root=0)
comm.Barrier()
if k == 0:
    print(allresults)

Is this a sensible way to get around the limit of 1000 tasks?

Is there a better way to consolidate results? I now have 50 files I have to concatenate manually. Is there some comm_world that can exist between different jobs?


问:
Fabric JS - Shapes are not displaying
I am using FabricJS and the shapes are not displaying, my code is on JSFiddle:

https://jsfiddle.net/270t9hfs/1/

```<code>var canvas = new fabric.Canvas("canvas");
    function addRectangle(){
                    var rect = new fabric.Rect({
                        left: 100,
                        top: 100,
                        fill: "red",
                        width: 20,
                        height: 20,
                        angle: 0
                    });
                    canvas.add(rect);
            }
</code>```

答:
The following example has a working addRectangle function:

<!DOCTYPE html>

    <title>Example</title>

    <canvas id="canvas" width="500" height="500"></canvas>
    <button onclick="addRectangle()">Add Rectangle</button>
    <button onclick="addTriangle()">Add Triangle</button>
    <button onclick="addCircle()">Add Circle</button>

```

Two issues were breaking your code:

Missing Fabric JS library

Initialising your Fabric JS canvas before the DOM had loaded. Moving the JavaScript to the bottom of the page resolves this. Alternatively you could use JavaScript to listen for when the DOM has loaded.

Title: Fabric JS - Shapes are not displaying

Body:
I am using FabricJS and the shapes are not displaying, my code is on JSFiddle:

https://jsfiddle.net/270t9hfs/1/

var canvas = new fabric.Canvas("canvas");
    function addRectangle(){
                    var rect = new fabric.Rect({
                        left: 100,
                        top: 100,
                        fill: "red",
                        width: 20,
                        height: 20,
                        angle: 0
                    });
                    canvas.add(rect);
            }

Body:
The following example has a working addRectangle function:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>

    <style type="text/css">
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            width: 200px;
            background-color: #f1f1f1;
        }

        li a{
            display: block;
            color: #000;
            padding: 8px 16px;
            text-decoration: none;
        }

        /* Change the link color on hover */
        li a:hover {
            background-color: #555;
            color: white;
        }

        #canvas {
            border: 1px solid;
        }
        button { margin-top: 9px }
</style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <button onclick="addRectangle()">Add Rectangle</button>
    <button onclick="addTriangle()">Add Triangle</button>
    <button onclick="addCircle()">Add Circle</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
    <script type="text/javascript">
    var canvas = new fabric.Canvas("canvas");
    function addRectangle(){
        var rect = new fabric.Rect({
            left: 100,
            top: 100,
            fill: "red",
            width: 20,
            height: 20,
            angle: 0
        });
        canvas.add(rect);
    }
    </script>
</body>
</html>

Two issues were breaking your code:

Missing Fabric JS library

Initialising your Fabric JS canvas before the DOM had loaded. Moving the JavaScript to the bottom of the page resolves this. Alternatively you could use JavaScript to listen for when the DOM has loaded.


问:
Using Javascript to write HTML inputs which call Javascript functions
I'll give you an example of what I'm trying to do.

In Javascript:

```<code>document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"
</code>```

The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:

```<code>webInput('a')
</code>```

In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.

I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.

答:
You can create your button within the javascript code and define the method therein.

```<code>var button = document.createElement('button');
button.addEventListener('click',function(){
   doSomething();
});
//This method adds your button to body
document.body.appendChild(button)
</code>```

Body:
I'll give you an example of what I'm trying to do.

In Javascript:

document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"

The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:

webInput('a')

In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.

I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.

Body:
You can create your button within the javascript code and define the method therein.

var button = document.createElement('button');
button.addEventListener('click',function(){
   doSomething();
});
//This method adds your button to body
document.body.appendChild(button)


问:
RadioButtons selected or not
Hi everyone I am trying to write a program that checks if all the radiobuttons I have are not selected, and print "Sorry you must select a radio button before continuing". I have gotten that message to print out, but when I select a radio button after that message pops up, I still get the "Sorry you must continue..." message.

Here is what I've come up with:

```<code>   no = (Button) findViewById(R.id.next);

        no.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                RadioButton r1 = (RadioButton) findViewById(R.id.radioButton);
                RadioButton r2 = (RadioButton) findViewById(R.id.radioButton2);
                RadioButton r3 = (RadioButton) findViewById(R.id.radioButton3);
                RadioButton r4 = (RadioButton) findViewById(R.id.radioButton4);
                RadioButton r5 = (RadioButton) findViewById(R.id.radioButton5);

                if(!(r1.isChecked() || r2.isChecked()) || r3.isChecked() || r4.isChecked() || r5.isChecked())
                {
                    riskLevel = Question1Activity.countPoints;
                    if(riskLevel >= 6 && riskLevel <= 9)
                    {
                        Toast.makeText(Question7Activity.this, "High Risk", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(v.getContext(), HighRiskActivity.class);
                        startActivity(intent);
                    }
                    if(riskLevel >= 3 && riskLevel <= 5)
                    {
                        Toast.makeText(Question7Activity.this, "Moderate Risk" , Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel >= 1 && riskLevel <= 2)
                    {
                        Toast.makeText(Question7Activity.this, "Low Risk", Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel == 0)
                    {
                        Toast.makeText(Question7Activity.this, "No Risk", Toast.LENGTH_SHORT).show();
                    }
                }else
                {
                    Toast.makeText(Question7Activity.this, "Well buddy nice try", Toast.LENGTH_SHORT).show();

                }
            }
        });
</code>```

I know it's something really simple, but I can't think of what could be the problem.

-Thanks!

答:
```<code> if((r1.isChecked() || r2.isChecked()) || r3.isChecked() || r4.isChecked() || r5.isChecked())
                {
                    riskLevel = Question1Activity.countPoints;
                    if(riskLevel >= 6 && riskLevel <= 9)
                    {
                        Toast.makeText(Question7Activity.this, "High Risk", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(v.getContext(), HighRiskActivity.class);
                        startActivity(intent);
                    }
                    if(riskLevel >= 3 && riskLevel <= 5)
                    {
                        Toast.makeText(Question7Activity.this, "Moderate Risk" , Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel >= 1 && riskLevel <= 2)
                    {
                        Toast.makeText(Question7Activity.this, "Low Risk", Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel == 0)
                    {
                        Toast.makeText(Question7Activity.this, "No Risk", Toast.LENGTH_SHORT).show();
                    }
                }else                {
                    Toast.makeText(Question7Activity.this, "Well buddy nice try", Toast.LENGTH_SHORT).show();

                }
</code>```

Ah I fixed it I had to remove the not symbol from in front of the isChecked() conditions.

Title: RadioButtons selected or not

Body:
Hi everyone I am trying to write a program that checks if all the radiobuttons I have are not selected, and print "Sorry you must select a radio button before continuing". I have gotten that message to print out, but when I select a radio button after that message pops up, I still get the "Sorry you must continue..." message.

Here is what I've come up with:

   no = (Button) findViewById(R.id.next);

        no.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                RadioButton r1 = (RadioButton) findViewById(R.id.radioButton);
                RadioButton r2 = (RadioButton) findViewById(R.id.radioButton2);
                RadioButton r3 = (RadioButton) findViewById(R.id.radioButton3);
                RadioButton r4 = (RadioButton) findViewById(R.id.radioButton4);
                RadioButton r5 = (RadioButton) findViewById(R.id.radioButton5);

                if(!(r1.isChecked() || r2.isChecked()) || r3.isChecked() || r4.isChecked() || r5.isChecked())
                {
                    riskLevel = Question1Activity.countPoints;
                    if(riskLevel >= 6 && riskLevel <= 9)
                    {
                        Toast.makeText(Question7Activity.this, "High Risk", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(v.getContext(), HighRiskActivity.class);
                        startActivity(intent);
                    }
                    if(riskLevel >= 3 && riskLevel <= 5)
                    {
                        Toast.makeText(Question7Activity.this, "Moderate Risk" , Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel >= 1 && riskLevel <= 2)
                    {
                        Toast.makeText(Question7Activity.this, "Low Risk", Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel == 0)
                    {
                        Toast.makeText(Question7Activity.this, "No Risk", Toast.LENGTH_SHORT).show();
                    }
                }else
                {
                    Toast.makeText(Question7Activity.this, "Well buddy nice try", Toast.LENGTH_SHORT).show();

                }
            }
        });

I know it's something really simple, but I can't think of what could be the problem.

-Thanks!

Body:
 if((r1.isChecked() || r2.isChecked()) || r3.isChecked() || r4.isChecked() || r5.isChecked())
                {
                    riskLevel = Question1Activity.countPoints;
                    if(riskLevel >= 6 && riskLevel <= 9)
                    {
                        Toast.makeText(Question7Activity.this, "High Risk", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(v.getContext(), HighRiskActivity.class);
                        startActivity(intent);
                    }
                    if(riskLevel >= 3 && riskLevel <= 5)
                    {
                        Toast.makeText(Question7Activity.this, "Moderate Risk" , Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel >= 1 && riskLevel <= 2)
                    {
                        Toast.makeText(Question7Activity.this, "Low Risk", Toast.LENGTH_SHORT).show();

                    }
                    if(riskLevel == 0)
                    {
                        Toast.makeText(Question7Activity.this, "No Risk", Toast.LENGTH_SHORT).show();
                    }
                }else                {
                    Toast.makeText(Question7Activity.this, "Well buddy nice try", Toast.LENGTH_SHORT).show();

                }

Ah I fixed it I had to remove the not symbol from in front of the isChecked() conditions.


问:
Using @WebServlet annotation in external java project
I'm trying to work only with native java without using frameworks such as spring, struts etc.

I'm building a web application using servlets and jsps.

My project layout in Project explorer (in Eclipse):
   MyApp (java project),
   MyAppWEB (dynamic web project),
   MyAppWEBEAR (ear project),

Servlet is inside the MyApp project.
Jsp is inside MyAppWEB project.

Both projects added to EAR.
MyApp was added to MyAppWEB's manifest as jar in deployment assembly.

And now is the problem :
When i use  @WebServlet("/hi") above the servlet class name i get error 404.

But, if i define the servlet inside web.xml then everything works fine (without the annotation).

Also if export MyApp project as jar and put it inside WEB-INF/lib folder
without using web.xml then it works fine too.

So the question is, is it possible to use this annotation inside java project (with out exporting manually to jar and put inside WEB-INF/lib) ?

web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MyAppWEB</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
<!--   <servlet> -->
<!--     <description></description> -->
<!--     <display-name>HelloWorldServlet</display-name> -->
<!--     <servlet-name>HelloWorldServlet</servlet-name> -->
<!--     <servlet-class>com.MyCom.MyApp.Servlets.HelloWorldServlet</servlet-class> -->
<!--   </servlet> -->
<!--   <servlet-mapping> -->
<!--     <servlet-name>HelloWorldServlet</servlet-name> -->
<!--     <url-pattern>/Hello</url-pattern> -->
<!--   </servlet-mapping> -->
</web-app>
</code>```

HelloWorldServlet:

```<code>package com.MyCom.MyApp.Servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hi")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HelloWorldServlet() {
        super();
    }

    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/HelloWorld.jsp").forward(request, response);
    }

}
</code>```

HelloWorld.jsp :

```<code><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MyApp</title>
</head>
<body>
    <h1>Hello World !!</h1>
</body>
</html>
</code>```

答:
OK, got this figured out.
It appears one also need to add the MyApp.jar to Deployment Assembly of the MyAppWEB project, and not only in Manifest Entries. This in turn will put the the MyApp.jar at WEB-INF/lib automatically at deployment on server.
Now annotations works just fine.</p>

Body:
I'm trying to work only with native java without using frameworks such as spring, struts etc.

I'm building a web application using servlets and jsps.

My project layout in Project explorer (in Eclipse):
   MyApp (java project),
   MyAppWEB (dynamic web project),
   MyAppWEBEAR (ear project),

Servlet is inside the MyApp project.
Jsp is inside MyAppWEB project.

Both projects added to EAR.
MyApp was added to MyAppWEB's manifest as jar in deployment assembly.

And now is the problem :
When i use  @WebServlet("/hi") above the servlet class name i get error 404.

But, if i define the servlet inside web.xml then everything works fine (without the annotation).

Also if export MyApp project as jar and put it inside WEB-INF/lib folder
without using web.xml then it works fine too.

So the question is, is it possible to use this annotation inside java project (with out exporting manually to jar and put inside WEB-INF/lib) ?

web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MyAppWEB</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>

HelloWorldServlet:

package com.MyCom.MyApp.Servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hi")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HelloWorldServlet() {
        super();
    }

    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/HelloWorld.jsp").forward(request, response);
    }

}

HelloWorld.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MyApp</title>

Hello World !!


答:
In your second example you don't pass a function, you pass a reference to anonymous lambda object with two methods operator()(int) and operator(char const (&)[..]). So to store this kind of callback you need to either copy lambda object or store particular callback methods, that is using more than one ::std::function with corresponding signatures. Actually explicitly passing two callbacks for both cases would be clearer.

```<code>std::function< void (int) > delalyed_int_cb;
std::function< void (const char *) > delalyed_str_cb;

template< typename callable_taking_int, typename callable_taking_string > void
call_me_back(callable_taking_int && int_cb, callable_taking_string && str_cb)
{
    delalyed_int_cb = std::forward< callable_taking_int >(int_cb);
    delalyed_str_cb = std::forward< callable_taking_str >(str_cb);
    ...
}

void
ready_to_answer()
{
    if(rand() % 2)
    {
        delalyed_int_cb(42);
    }
    else
    {
        delalyed_str_cb("Kill all the humans.");
    }
}
</code>```

Title: Wrapper for template callback?

Body:
Immediate callback

Consider the following example:

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    callback(42);
}

int main()
{
    call_me_back([](const int & value)
    {
        std :: cout << value << std :: endl;
    });
}

Here I provide call_me_back with a lambda that accepts an int. call_me_back calls callback after some long calculation, and callback prints it out. Easy as cake.

Now, say that depending on the execution, call_me_back needs to call callback either with an int or with some other type. We can edit the previous example to

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    if(rand() % 2)
        callback(42);
    else
        callback("Kill all the humans.");
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

So far so good. Now callback can do all sorts of tricks and handle value depending on its type.

Delayed callback

Now, back to the first example. Say that call_me_back is not ready to immediately call callback with an int. What it can do, however, is to store the callback somewhere, and then call it later.

For example:

std :: function <void(const int &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = callback;
}

void ready_to_answer()
{
    the_callback(42);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

Now, instead of immediately calling callback, call_me_back stores callback in an std :: function <void(const int &)> object (I know, it's in the global scope, bear with me). Many things can then happen and at some point someone can call ready_to_answer, which retrieves the previously stored callback and calls it. For example, ready_to_answer can be called by another thread, but there is a whole lot of reasons why one would need a paradigm like this, where the callback can be stored and called later.

The problem

What if I wanted to implement the second example, but with a delayed callback?. I don't seem to be able to get my head around this.

I can imagine that std :: function is implemented with a virtual call operator that accepts some specific type. The std :: function then wraps a pointer / reference to a template wrapper class that stores the actual lambda and implements the call operator by forwarding its argument to the lambda it's storing. Nice and easy. But I can't have template virtual methods!

I have tried coming up with all sorts of solutions, but I couldn't find anything that could reasonably work. Is this really impossible to do? Is it impossible to have some externally provided lambda that accepts a const auto & argument stored somewhere, and then call it later?

Body:
In your second example you don't pass a function, you pass a reference to anonymous lambda object with two methods operator()(int) and operator(char const (&)[..]). So to store this kind of callback you need to either copy lambda object or store particular callback methods, that is using more than one ::std::function with corresponding signatures. Actually explicitly passing two callbacks for both cases would be clearer.

std::function< void (int) > delalyed_int_cb;
std::function< void (const char *) > delalyed_str_cb;

template< typename callable_taking_int, typename callable_taking_string > void
call_me_back(callable_taking_int && int_cb, callable_taking_string && str_cb)
{
    delalyed_int_cb = std::forward< callable_taking_int >(int_cb);
    delalyed_str_cb = std::forward< callable_taking_str >(str_cb);
    ...
}

void
ready_to_answer()
{
    if(rand() % 2)
    {
        delalyed_int_cb(42);
    }
    else
    {
        delalyed_str_cb("Kill all the humans.");
    }
}