问:
Can an HTML / JavaScript pair reference another HTML file?
Given a completed page a.html, is it possible to build b.html which includes JavaScript such that b pulls data from a.html and outputs the data into b.html's window?  That is, is there any such thing like src=whatever.js where one can declare a variable of the other HTML page, so that something like this line like this would work (obviously doesn't as it is)?

```<code><html>
<head>
    <title>b.html</title>
</head>
<body>
    <script>
    var images = a.document.body.getElementsByTagName ("img");
</code>```

etc.

Thanks again for any help!  I see the 'may have your answer' above, but that uses JQuery, which I'm not looking for.

答:
The simple answer is 'no, javascript is explicitly forbidden from accessing local filesystem, so there's no way a.html can read the contents of b.html even if they reside in the same folder locally'.

That being said, however, if the are both being served by a web server, you could always ask it to fetch a.html for you and then use javascript to parse it, invisbile to the user, and extract the info you need from it.

Take a look at a rather clumsy example below, using invisible iframe HTML element - basically a container you can put on page and load a different page into, and then have access to its DOM tree. (There are limitations to prevent XSS attacks, but since both a.html and b.html are from one and the same domain, these do not apply in your case.)

a.html

```<code><!doctype html>
<html>
 <head>
......
 </head>
 <body>
...
<div id=aa>
 Some interesting stuff...
</div>
...
</body>
</html>
</code>```

b.html

```<code><!doctype html>
<html>
 <head>
......
 </head>
 <body>
...
<iframe src="a.html" onLoad="alert('The contents of div with id=aa from a.html is: ['+this.contentDocument.getElementById('aa').innerHTML+']');"></iframe>
...
</body>
</html>
</code>```

Here, it loads the entire document a.html into  element on page b.html (which you can make invisible through, say CSS) and, once it's loaded, it extracts the necessary div from the DOM tree of page a.html (which is accessible now through the iframe object in DOM of the current, b.html page) and makes use of its innerHTML property to prove that it can access it.

Here, the contentDocument property of the iframe object on page b.html points to the normal 'document' object of the page we have loaded into the iframe, giving us all the options we have when dealing with any page when we have its document root.

This example is clumsy by many counts of course, not least being the fact that you load TWO pages (b.html and a.html) into the browser (albeit a.html is invisible) instead of one and that is hardly efficient.

But it's a start and for realy simple scenarios it might be an adequate if unsophisticated solution )

Body:
Given a completed page a.html, is it possible to build b.html which includes JavaScript such that b pulls data from a.html and outputs the data into b.html's window?  That is, is there any such thing like src=whatever.js where one can declare a variable of the other HTML page, so that something like this line like this would work (obviously doesn't as it is)?

    <title>b.html</title>

Body:
The simple answer is 'no, javascript is explicitly forbidden from accessing local filesystem, so there's no way a.html can read the contents of b.html even if they reside in the same folder locally'.

That being said, however, if the are both being served by a web server, you could always ask it to fetch a.html for you and then use javascript to parse it, invisbile to the user, and extract the info you need from it.

Take a look at a rather clumsy example below, using invisible iframe HTML element - basically a container you can put on page and load a different page into, and then have access to its DOM tree. (There are limitations to prevent XSS attacks, but since both a.html and b.html are from one and the same domain, these do not apply in your case.)

a.html

<!doctype html>
<html>
 <head>
......
 </head>
 <body>
...
<div id=aa>
 Some interesting stuff...
</div>
...
</body>
</html>

b.html

<!doctype html>
<html>
 <head>
......
 </head>
 <body>
...
<iframe src="a.html" onLoad="alert('The contents of div with id=aa from a.html is: ['+this.contentDocument.getElementById('aa').innerHTML+']');"></iframe>
...
</body>
</html>

Here, it loads the entire document a.html into  element on page b.html (which you can make invisible through, say CSS) and, once it's loaded, it extracts the necessary div from the DOM tree of page a.html (which is accessible now through the iframe object in DOM of the current, b.html page) and makes use of its innerHTML property to prove that it can access it.

Here, the contentDocument property of the iframe object on page b.html points to the normal 'document' object of the page we have loaded into the iframe, giving us all the options we have when dealing with any page when we have its document root.

This example is clumsy by many counts of course, not least being the fact that you load TWO pages (b.html and a.html) into the browser (albeit a.html is invisible) instead of one and that is hardly efficient.

But it's a start and for realy simple scenarios it might be an adequate if unsophisticated solution )


来源: stackexchange

问:
Aborted Core Dumped
```<code>stack.out: malloc.c:2372:
sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1)- 1) * 2])) -
__builtin_offsetof (struct malloc_chunk, fd))))
    && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1)))
    && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Aborted (core dumped)
</code>```

When I was dealing with my codes that includes stack subject,and suddenly it is seen my gcc compiler's error I did not get anything,What does it mean,if you know these things,please tell my wrong in the program.Thanks in advance.

答:
It looks like you have corrupted heap memory, probably because you wrote well past the end of some malloc()'d memory. Use gdb to get a traceback of your function calls, and they may help you debug it. To get a traceback of your program, assuming it is called myProg, type the following:

```<code>gdb myProg
run
</code>```

after it gets this exception, type:

```<code>bt
</code>```

Because you are likely trampling memory, where the error occurred may not be a part of this traceback stack, but it is a good place to start. If this does not help, then use either valgrind or memwatch, both are described here and these tools will tell you where you are writing past the end of memory, resulting in the corruption, and the core dump.

ContentLicense: CC BY-SA 3.0

Title: Aborted Core Dumped

Body:
stack.out: malloc.c:2372:
sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1)- 1) * 2])) -
__builtin_offsetof (struct malloc_chunk, fd))))
    && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1)))
    && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Aborted (core dumped)

When I was dealing with my codes that includes stack subject,and suddenly it is seen my gcc compiler's error I did not get anything,What does it mean,if you know these things,please tell my wrong in the program.Thanks in advance.

Body:
It looks like you have corrupted heap memory, probably because you wrote well past the end of some malloc()'d memory. Use gdb to get a traceback of your function calls, and they may help you debug it. To get a traceback of your program, assuming it is called myProg, type the following:

gdb myProg
run

after it gets this exception, type:

bt

Because you are likely trampling memory, where the error occurred may not be a part of this traceback stack, but it is a good place to start. If this does not help, then use either valgrind or memwatch, both are described here and these tools will tell you where you are writing past the end of memory, resulting in the corruption, and the core dump.


问:
Scala Map of Strings not Compiling When CharSequence is expected
I'm trying to return a Map[CharSequence, CharSequence]. The point of the function is to check if another map has a certain key/value pair, and then return a particular CharSequence map.

If I just return an empty map (or string map), this compiles

```<code>def returnCharSequenceMap(someOtherMap: Option[Map[String,String]]): Map[CharSequence, CharSequence] = {
    Map.empty // or something like Map("A" -> "B")
}
</code>```

However, this fails to compile

```<code>def returnCharSequenceMap(someOtherMap: Option[Map[String, String]]): Map[CharSequence, CharSequence] = {
    someOtherMap.map { mapRecord =>
        case Some("conditionA") =>
            Map("a" -> "b")
        case Some("conditionB") =>
            Map("a" -> "b", "c" -> "d")
        case _ => Map.empty
    }
}.getOrElse(Map.empty)
</code>```

I get this rather obtuse error that I cannot decipher:

```<code>[error]  found   : scala.collection.immutable.Map[_19,String] where type _19 >: _1 <: CharSequence
[error]  required: Map[CharSequence,CharSequence]
[error] Note: _19 <: CharSequence, but trait Map is invariant in type A.
[error] You may wish to investigate a wildcard type such as `_ <: CharSequence`. (SLS 3.2.10)
[error]     }.getOrElse(Map.empty)
</code>```

Can someone help point out what I'm doing wrong? I'm trying to understand why I can't just return the map. Thanks!

答:
First, you cannot do pattern matching inside a function like this, without introducing it with the match keyword: what are you pattern matching on?

Then, assuming you want to pattern match on mapRecord (in which case you can simply remove the mapRecord =>, since a function can be given as a pattern matching on its parameter) note that it will never match, since the function in map takes a parameter of type Map[String, String], not of type Option[Map[String, String]].

While we're at it, you can use the collect method on Option (instead of map) to put only the interesting case in your patterns, and leave the case _ to be reduced as None, then to be dealt with in the getOrElse (thus avoiding to write Map.empty twice).

Now to really answer your question, the problem is with type inference and the invariance property of Map on its first type parameter.

To make sure that all the types are what you want them to be, you should put them as parameters to some of the functions that might need them. For instance, this code compiles:

```<code>def returnCharSequenceMap(someOtherMap: Option[Map[String, String]]): Map[CharSequence, CharSequence] = {
  someOtherMap.map[Map[CharSequence, CharSequence]] { _ =>
    Map("a" -> "b")
  }.getOrElse(Map.empty)
}
</code>```

Body:
I'm trying to return a Map[CharSequence, CharSequence]. The point of the function is to check if another map has a certain key/value pair, and then return a particular CharSequence map.

If I just return an empty map (or string map), this compiles

def returnCharSequenceMap(someOtherMap: Option[Map[String,String]]): Map[CharSequence, CharSequence] = {
    Map.empty // or something like Map("A" -> "B")
}

However, this fails to compile

def returnCharSequenceMap(someOtherMap: Option[Map[String, String]]): Map[CharSequence, CharSequence] = {
    someOtherMap.map { mapRecord =>
        case Some("conditionA") =>
            Map("a" -> "b")
        case Some("conditionB") =>
            Map("a" -> "b", "c" -> "d")
        case _ => Map.empty
    }
}.getOrElse(Map.empty)

I get this rather obtuse error that I cannot decipher:

[error]  found   : scala.collection.immutable.Map[_19,String] where type _19 >: _1 <: CharSequence
[error]  required: Map[CharSequence,CharSequence]
[error] Note: _19 <: CharSequence, but trait Map is invariant in type A.
[error] You may wish to investigate a wildcard type such as `_ <: CharSequence`. (SLS 3.2.10)
[error]     }.getOrElse(Map.empty)

Can someone help point out what I'm doing wrong? I'm trying to understand why I can't just return the map. Thanks!

Body:
First, you cannot do pattern matching inside a function like this, without introducing it with the match keyword: what are you pattern matching on?

Then, assuming you want to pattern match on mapRecord (in which case you can simply remove the mapRecord =>, since a function can be given as a pattern matching on its parameter) note that it will never match, since the function in map takes a parameter of type Map[String, String], not of type Option[Map[String, String]].

While we're at it, you can use the collect method on Option (instead of map) to put only the interesting case in your patterns, and leave the case _ to be reduced as None, then to be dealt with in the getOrElse (thus avoiding to write Map.empty twice).

Now to really answer your question, the problem is with type inference and the invariance property of Map on its first type parameter.

To make sure that all the types are what you want them to be, you should put them as parameters to some of the functions that might need them. For instance, this code compiles:

def returnCharSequenceMap(someOtherMap: Option[Map[String, String]]): Map[CharSequence, CharSequence] = {
  someOtherMap.map[Map[CharSequence, CharSequence]] { _ =>
    Map("a" -> "b")
  }.getOrElse(Map.empty)
}


问:
Java interact with windows cmd
I've searched for similar questions, but despite there where a lot with a similar title all have asked something different.

In my case I want that my java program interact with the terminal (Windows) by writing command and reading the response.

I've found the class ProcessBuilder, but does not seem that do what I want

What I' m searching for is something so:

start the cmd at some given position (like C:\Users\federico)

issue a command (dir or cd desktop); this should not open a command prompt window

read any output that command may result in

and so on, up to the user's exit from the program.

答: I suspect you simply don't know the English terms for this: what you're looking for is a way to execute commands in the OS, which is called "exec" in every programming language I know of, including Java: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String)</p>

Title: Java interact with windows cmd


问:
BrowserWindow in electron does not open
I just tried to test electron environment for programming with JavaScript on desktop with Windows 10.

So I have an app:

```<code>const electron=require("electron");
const app=electron.app;
const BrowserWindow=electron.BrowserWindow;

var mainWindow=null;

app.on("ready",function(){
  mainWindow=new BrowserWindow({height:600,width:800});
  mainWindow.loadURL("file://"+__dirname+"index.html");
});
</code>```

and index.html is:

```<code><html>
<head>
<title> MyIndex.html </title>
</head>
<body>
Hello World from Electron!<br>
</body>
</html>
</code>```

and package.json is:

```<code>{
"name":"Electron-Test",
"version":"0.1.0",
"main":"./main.js",
"scripts":{"start":"electron ."}
}
</code>```

If I run electron . or npm start the application seems to start, but no browser window opens. On console I have to press Ctrl-C to stop the application.
Does anyone know where is the problem?

答:
try to add one more/after file:

 you are also missing a /  before index.html

```<code>app.on("ready",function(){
  mainWindow=new BrowserWindow({height:600,width:800});
  mainWindow.loadURL("file:///"+__dirname+"/index.html");
});
</code>```

i saw it in this video, at 3:32 https://www.youtube.com/watch?v=i0AkgNv4U4E

Title: BrowserWindow in electron does not open

Body:
I just tried to test electron environment for programming with JavaScript on desktop with Windows 10.

So I have an app:

const electron=require("electron");
const app=electron.app;
const BrowserWindow=electron.BrowserWindow;

var mainWindow=null;

app.on("ready",function(){
  mainWindow=new BrowserWindow({height:600,width:800});
  mainWindow.loadURL("file://"+__dirname+"index.html");
});

and index.html is:

<title> MyIndex.html </title>

Hello World from Electron!

and package.json is:

{
"name":"Electron-Test",
"version":"0.1.0",
"main":"./main.js",
"scripts":{"start":"electron ."}
}

If I run electron . or npm start the application seems to start, but no browser window opens. On console I have to press Ctrl-C to stop the application.
Does anyone know where is the problem?

Body:
try to add one more/after file:

 you are also missing a /  before index.html

app.on("ready",function(){
  mainWindow=new BrowserWindow({height:600,width:800});
  mainWindow.loadURL("file:///"+__dirname+"/index.html");
});

i saw it in this video, at 3:32 https://www.youtube.com/watch?v=i0AkgNv4U4E


问:
Comparing Multiple Arrays Using Reduce
pretty new to Javascript and I've tried this question about 4 times now in a span of about a month and I am still unable to solve it.

So here is the question:
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs. BONUS: Use reduce!

The format is:

```<code>function intersection(arrays) {
  // Your Code Goes Here
}
</code>```

Test Case: Should log [15, 5]

```<code>console.log('Extensions 3 Test: ' + intersection([5, 10, 15, 20], [15, 88, 1, 5, 7]/*, [1, 10, 15, 5, 20]*/));
</code>```

My current solution: Works for the case of only have two items to compare, but not for the third one, I could make it so that I would loop through and compare the obtained values with the next array but I don't think I am on the right path... Also, I am not using reduce to implement it... And I am not sure if I am supposed to be using 'arguments.' Any help is appreciated! Thank you so much.

```<code>function intersection(arrays) {
  array = [];
  for (var i = 0; i < arguments.length; i++)
    array.push(arguments[i]);

  var result = [];

  for(var i = 0; i < array.length - 1; i++) {
    for(var j = 0; j < array[i].length; j++) {
      if (array[i+1].includes(array[i][j]))
        result.push(array[i][j]);
    }
  }

  return result;
}
</code>```

答:
Here's what I came up with using vanilla javascript and one call to reduce. </p>

```<code>function intersection(){
 var arrays = [].slice.call(arguments);
 var first = arrays[0];
 var rest = arrays.slice(1);

 return first.reduce(function(all, item, index){
  var push = rest.every(function(subArray){
      return subArray.indexOf(item) > -1;
    });
  if(push){
    all.push(item);
   }
  return all;
 },[])

}

console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
</code>```

Title: Comparing Multiple Arrays Using Reduce

Body:
pretty new to Javascript and I've tried this question about 4 times now in a span of about a month and I am still unable to solve it.

So here is the question:
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs. BONUS: Use reduce!

The format is:

function intersection(arrays) {
  // Your Code Goes Here
}

Test Case: Should log [15, 5]

console.log('Extensions 3 Test: ' + intersection([5, 10, 15, 20], [15, 88, 1, 5, 7]/*, [1, 10, 15, 5, 20]*/));

My current solution: Works for the case of only have two items to compare, but not for the third one, I could make it so that I would loop through and compare the obtained values with the next array but I don't think I am on the right path... Also, I am not using reduce to implement it... And I am not sure if I am supposed to be using 'arguments.' Any help is appreciated! Thank you so much.

function intersection(arrays) {
  array = [];
  for (var i = 0; i < arguments.length; i++)
    array.push(arguments[i]);

  var result = [];

  for(var i = 0; i < array.length - 1; i++) {
    for(var j = 0; j < array[i].length; j++) {
      if (array[i+1].includes(array[i][j]))
        result.push(array[i][j]);
    }
  }

  return result;
}

Body:
Here's what I came up with using vanilla javascript and one call to reduce.

function intersection(){
 var arrays = [].slice.call(arguments);
 var first = arrays[0];
 var rest = arrays.slice(1);

 return first.reduce(function(all, item, index){
  var push = rest.every(function(subArray){
      return subArray.indexOf(item) > -1;
    });
  if(push){
    all.push(item);
   }
  return all;
 },[])

}

console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));


问:
How do I open a .class file?
If I have a .class file, how do I open it/view the source code? I think I have to decompile it first, but how the heck do I do that?</p>

答: Just drag the .class file into your ide and it should show you the contents of that file, or you can use this http://www.javadecompilers.com/ to decompile the .class file.:)</p>

Title: How do I open a .class file?


问:
Java println weird output
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

```<code>import java.util.*;
import java.io.*;

public class Java1 {

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}
</code>```

答:
```<code>import java.util.*;
import java.io.IOException;

public class Java1
{
    public static void main(String args[])
    {
       int x = 4;
       int y = -5;
       System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
    }

    public static int func(int work, int y)
    {

        int z = work + y;// 5+-5 = 0
        work++; //6

        y++; //-4
        System.out.print("Z = " + z + " ");//0
        return z + work + y;  //0 + 6+-4 = 2
    }
}
</code>```

OUTPUT :

Z = 0 x = 4 func = 2 y = -6

Here the func() is executed first and hence the value of variable z is printed as 0 and then the x++ value is printed as 4.

Title: Java println weird output

Body:
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

import java.util.*;
import java.io.*;

public class Java1 {

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}

Body:
import java.util.*;
import java.io.IOException;

public class Java1
{
    public static void main(String args[])
    {
       int x = 4;
       int y = -5;
       System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
    }

    public static int func(int work, int y)
    {

        int z = work + y;// 5+-5 = 0
        work++; //6

        y++; //-4
        System.out.print("Z = " + z + " ");//0
        return z + work + y;  //0 + 6+-4 = 2
    }
}

OUTPUT :

Z = 0 x = 4 func = 2 y = -6

Here the func() is executed first and hence the value of variable z is printed as 0 and then the x++ value is printed as 4.


问:
Python - MatPlotLib.PyPlot - Removing tick marks from Right Axis
I have the following pyplot subroutine. All data passes correctly to the subroutine. However, I am not able to control two things:
1 - I can't make the right ticks disappear
2 - I can't place a 2nd y-label on the right axis

I've added an example image which has right-ticks that I'm trying to remove, and also trying to add a right-hand y-axis label.

Much thanks!

```<code>def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

    fig, ax = plt.subplots()

    colorZ2 = ('#002060', 'red')
    colorZ1 = ( '#92D050', 'purple')
    p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
    p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
    p3 = plt.Rectangle((0, 0), 1, 0, fc='black')
    p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
    p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

#   plt.ylim(yMin, yMax)

    ax2 = ax.twinx()
    ax2 = ax.twiny()

    ax3 = ax.twinx()
    ax3 = ax.twiny()

    dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

    ax.stackplot(dates, series1, series2, colors=colorZ1)
    ax2.stackplot(dates, series3, series4, colors=colorZ2)
    ax3.plot(dates, series5, c='black', lw=3)

    ax2.tick_params(labeltop='off', labelright='off')  # labelright is not working
    ax3.tick_params(labeltop='off', labelright='off')  # labelright is not working

# How do you turn off ticks on the right ticks?

    ax3.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='best', shadow=True)

    plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

    ax.set_ylabel(titleYlabel, fontsize=14)

# How do you get the label for the right to appear

    ax2.set_ylabel(titleYlabel2, fontsize=14) # not working
    ax3.set_ylabel(titleYlabel2, fontsize=14) # not working

    y_format = tkr.FuncFormatter(numFunc)
    ax.yaxis.set_major_formatter(y_format)

    props = dict(boxstyle='square', facecolor='none' )
    fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
    fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
    ax.grid(True)
    fig.autofmt_xdate()

    plt.show()

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s
</code>```

答:
Ok, I'm learning the mechanics of stackoverflow.com. I'm including the matplotlib subroutines, and an example of the output as I had hoped to achieve it.
def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

```<code>fig, ax = plt.subplots()
ax2 = ax.twinx()

colorZ2 = ('#002060', 'red')
colorZ1 = ( '#92D050', 'purple')
p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
p3 = plt.Line2D([], [], color='black', linewidth=4)
p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

ax.stackplot(dates, series1, series2, colors=colorZ1)
ax.stackplot(dates, series3, series4, colors=colorZ2)
ax.plot(dates, series5, c='black', lw=3)

ax.set_ylabel(titleYlabel, fontsize=14)
ax2.tick_params(labelright='off')
ax2.set_ylabel(titleYlabel2, fontsize=14)

ax.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='upper left', shadow=True)

plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

y_format = tkr.FuncFormatter(numFunc)
ax.yaxis.set_major_formatter(y_format)

props = dict(boxstyle='square', facecolor='none' )
fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
ax.grid(True)
fig.autofmt_xdate()

plt.show()
</code>```

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s

Not sure where the image went; but it's a supply/demand balance view of the U.S. Residual fuel market

Body:
I have the following pyplot subroutine. All data passes correctly to the subroutine. However, I am not able to control two things:
1 - I can't make the right ticks disappear
2 - I can't place a 2nd y-label on the right axis

I've added an example image which has right-ticks that I'm trying to remove, and also trying to add a right-hand y-axis label.

Much thanks!

def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

    fig, ax = plt.subplots()

    colorZ2 = ('#002060', 'red')
    colorZ1 = ( '#92D050', 'purple')
    p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
    p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
    p3 = plt.Rectangle((0, 0), 1, 0, fc='black')
    p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
    p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

#   plt.ylim(yMin, yMax)

    ax2 = ax.twinx()
    ax2 = ax.twiny()

    ax3 = ax.twinx()
    ax3 = ax.twiny()

    dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

    ax.stackplot(dates, series1, series2, colors=colorZ1)
    ax2.stackplot(dates, series3, series4, colors=colorZ2)
    ax3.plot(dates, series5, c='black', lw=3)

    ax2.tick_params(labeltop='off', labelright='off')  # labelright is not working
    ax3.tick_params(labeltop='off', labelright='off')  # labelright is not working

# How do you turn off ticks on the right ticks?

    ax3.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='best', shadow=True)

    plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

    ax.set_ylabel(titleYlabel, fontsize=14)

# How do you get the label for the right to appear

    ax2.set_ylabel(titleYlabel2, fontsize=14) # not working
    ax3.set_ylabel(titleYlabel2, fontsize=14) # not working

    y_format = tkr.FuncFormatter(numFunc)
    ax.yaxis.set_major_formatter(y_format)

    props = dict(boxstyle='square', facecolor='none' )
    fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
    fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
    ax.grid(True)
    fig.autofmt_xdate()

    plt.show()

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s

Body:
Ok, I'm learning the mechanics of stackoverflow.com. I'm including the matplotlib subroutines, and an example of the output as I had hoped to achieve it.
def makeChart(dataToGraph,  titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource):

fig, ax = plt.subplots()
ax2 = ax.twinx()

colorZ2 = ('#002060', 'red')
colorZ1 = ( '#92D050', 'purple')
p1 = plt.Rectangle((0, 0), 1, 1, fc='red')
p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060')
p3 = plt.Line2D([], [], color='black', linewidth=4)
p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050')
p5 = plt.Rectangle((0, 0), 1, 1, fc='purple')

dates, series1, series2, series3, series4, series5 = zip(*dataToGraph)

ax.stackplot(dates, series1, series2, colors=colorZ1)
ax.stackplot(dates, series3, series4, colors=colorZ2)
ax.plot(dates, series5, c='black', lw=3)

ax.set_ylabel(titleYlabel, fontsize=14)
ax2.tick_params(labelright='off')
ax2.set_ylabel(titleYlabel2, fontsize=14)

ax.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='upper left', shadow=True)

plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14)

y_format = tkr.FuncFormatter(numFunc)
ax.yaxis.set_major_formatter(y_format)

props = dict(boxstyle='square', facecolor='none' )
fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props)
fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props)
ax.grid(True)
fig.autofmt_xdate()

plt.show()

def numFunc(x, pos):  # formatter function takes tick label and tick position
    s = '{:0,d}'.format(int(x))
    return s

Not sure where the image went; but it's a supply/demand balance view of the U.S. Residual fuel market


问:
limit std::vector for given min and max values
I've a std::vector of double values and I'm searching for a way to limit the sorted result to certain min and max values. Let me provide an example -

```<code>std::vector<double> v;
v.push_back(2.5);
v.push_back(3.5);
v.push_back(4.5);
v.push_back(5.5);
v.push_back(6.5);
</code>```

In above example, if I execute limit(v, 4.0, 7.0); it should provide me indexes eg [2] to [4] or end or whatever. I tried searching for <algorithm> header but couldn't find one :/ I can use additional library too if the need arises.

答:
Kerrek SB's solution is great but implies that v is sorted.  If it is not sorted, use std::partition.

```<code>#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<double> v = { 4.5, 2.5, 5.5, 6.5, 3.5 };

  auto part = std::partition(v.begin(), v.end(), [](double d){return 4 < d && d < 7;});

  for (auto it = std::begin(v); it != part; ++it)
    std::cout << *it << "\n";
}
</code>```

Demo

Body:
I've a std::vector of double values and I'm searching for a way to limit the sorted result to certain min and max values. Let me provide an example -

std::vector<double> v;
v.push_back(2.5);
v.push_back(3.5);
v.push_back(4.5);
v.push_back(5.5);
v.push_back(6.5);

In above example, if I execute limit(v, 4.0, 7.0); it should provide me indexes eg [2] to [4] or end or whatever. I tried searching for <algorithm> header but couldn't find one :/ I can use additional library too if the need arises.

Body:
Kerrek SB's solution is great but implies that v is sorted.  If it is not sorted, use std::partition.

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<double> v = { 4.5, 2.5, 5.5, 6.5, 3.5 };

  auto part = std::partition(v.begin(), v.end(), [](double d){return 4 < d && d < 7;});

  for (auto it = std::begin(v); it != part; ++it)
    std::cout << *it << "\n";
}

Demo


问:
In-Memory Caching and Concurrency Issues
When requiring to cache files in memory, assuming the following action:

```<code>public IActionResult Article(int id) {
    String content = MemoryCache.Get<String>(id.ToString());

    if(content == null) {
       MemoryCache.Set<String>(id.ToString(), ReadFile(id), new MemoryCacheEntryOptions() {
                AbsoluteExpiration = DateTime.Now.AddHours(1)
        });

        content = MemoryCache.Get<String>(id.ToString());
     }

     return View(content);
}
</code>```

What happens if two or more requests hit the server at the same time? Would this result in the file being read and cached for many times, or would ASP.Net Core MVC handle this issue by default? If so, would it be safe to lock the caching block?

答:
MemoryCache is "threadsafe", but it doesn't mean that two processes can't both miss the cache one after the other (While the first is generating the cache).

Now using the Lock, this really depends on how heavy the function to generate the cache is and comparing that to how heavy a lock may be in your code.

How often are two threads going to be coming in looking for the same cache value? If the answer is not often, then it's probably not worth adding the overhead of locks if the majority of cases it's actually not needed.

Body:
When requiring to cache files in memory, assuming the following action:

public IActionResult Article(int id) {
    String content = MemoryCache.Get<String>(id.ToString());

    if(content == null) {
       MemoryCache.Set<String>(id.ToString(), ReadFile(id), new MemoryCacheEntryOptions() {
                AbsoluteExpiration = DateTime.Now.AddHours(1)
        });

        content = MemoryCache.Get<String>(id.ToString());
     }

     return View(content);
}

What happens if two or more requests hit the server at the same time? Would this result in the file being read and cached for many times, or would ASP.Net Core MVC handle this issue by default? If so, would it be safe to lock the caching block?


问:
Scroll to anchor JS not working
So what I try to achieve is as the title says. I've gone through quite many threads and websites so far, but just can not get it working.

I can somehow see different scripts working when they have the time it takes to scroll editable. It just doesn't scroll smoothly, it jumps to the anchor after that time.

What I am currently using:

<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">

Tervetuloa

Sivupohjia

Tilaa sivut

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Tervetuloa

Tekstiä

Sivupohjia

Tulossa

Tilaa

Tekstiä

© Marko Ahola

```

I simply have no idea where to go from here. I have no experience in this, I'm just a hobbyist. Any help is appreciated.

I have the website running on a Raspberry PI and Apache2.

答:
You forgot to add your class name scroll to your first three anchor tags that you want smooth scrolling

```<code>  <li><a href="#1" class="scroll">Tervetuloa</a></li>
    <li><a href="#2" class="scroll">Sivupohjia</a></li>
    <li><a href="#3" class="scroll">Tilaa sivut</a></li>
</code>```

Snippet below

<!DOCTYPE html>

  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">

Tervetuloa

Sivupohjia

Tilaa sivut

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Tervetuloa

Tekstiä

Sivupohjia

Tulossa

Tilaa

Tekstiä

© Marko Ahola

```

Title: Scroll to anchor JS not working

Body:
So what I try to achieve is as the title says. I've gone through quite many threads and websites so far, but just can not get it working.

I can somehow see different scripts working when they have the time it takes to scroll editable. It just doesn't scroll smoothly, it jumps to the anchor after that time.

What I am currently using:

<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">

Tervetuloa

Sivupohjia

Tilaa sivut

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Linkki

Tervetuloa

Tekstiä

Sivupohjia

Tulossa

Tilaa

Tekstiä

© Marko Ahola

I simply have no idea where to go from here. I have no experience in this, I'm just a hobbyist. Any help is appreciated.

I have the website running on a Raspberry PI and Apache2.

Body:
You forgot to add your class name scroll to your first three anchor tags that you want smooth scrolling

  <li><a href="#1" class="scroll">Tervetuloa</a></li>
    <li><a href="#2" class="scroll">Sivupohjia</a></li>
    <li><a href="#3" class="scroll">Tilaa sivut</a></li>

Snippet below

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      var hashTagActive = "";
      $(".scroll").click(function(event) {
        if (hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
          event.preventDefault();
          //calculate destination place
          var dest = 0;
          if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
            dest = $(document).height() - $(window).height();
          } else {
            dest = $(this.hash).offset().top;
          }
          //go to destination
          $('html,body').animate({
            scrollTop: dest
          }, 2000, 'swing', function() {
            hashTagActive = "";
          });
          hashTagActive = this.hash;
        }
      });
    });
  </script>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="navbar">
    <ul>
      <li><a href="#1" class="scroll">Tervetuloa</a></li>
      <li><a href="#2" class="scroll">Sivupohjia</a></li>
      <li><a href="#3" class="scroll">Tilaa sivut</a></li>
      <li><a href="etusivu.html#4">Linkki</a></li>
      <li><a href="etusivu.html#5">Linkki</a></li>
      <li><a href="etusivu.html#6">Linkki</a></li>
      <li><a href="etusivu.html#7">Linkki</a></li>
      <li><a href="etusivu.html#8">Linkki</a></li>
      <li><a href="etusivu.html#9">Linkki</a></li>
      <li><a href="etusivu.html#10">Linkki</a></li>
    </ul>
  </div>
  <div class="container">
    <div class="wrapper">
      <div class="content_primary">
        <a name="1" id="1"></a>
        <h3>Tervetuloa</h3>
        <p>Tekstiä</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="content_secondary">
        <a name="2" id="2"></a>
        <h3>Sivupohjia</h3>
        <p>Tulossa</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="content_primary">
        <a name="3" id="3"></a>
        <h3>Tilaa</h3>
        <p>Tekstiä</p>
      </div>
    </div>
  </div>
  <div class="footer">
    <p>&copy;&nbsp;Marko&nbsp;Ahola</p>
  </div>
</body>

</html>


问:
Bug creating a grid of view components using react native flexbox styling
I'm trying to create a 5x5 grid of boxes in react native using flexbox. Currently my code is only producing a single row of the grid and I don't know why.

Here's my code:

```<code>import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';

class Board extends Component {
  render () {
    return (
      <View style={styles.container}>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'flex-start',
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  box: {
    flex: 1,
    height: 60,
    backgroundColor: 'red',
    borderWidth: 2,
    borderColor: 'black',
  }
});

export default Board;
</code>```

Here's the output:

How can I make my code output a 5x5 grid of boxes?

Thank you

答: Removing flex: 1 from rowContainer fixed the problem though I'm not entirely sure why</p>

Body:
I'm trying to create a 5x5 grid of boxes in react native using flexbox. Currently my code is only producing a single row of the grid and I don't know why.

Here's my code:

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';

class Board extends Component {
  render () {
    return (
      <View style={styles.container}>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
          <View style={styles.box}></View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'flex-start',
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  box: {
    flex: 1,
    height: 60,
    backgroundColor: 'red',
    borderWidth: 2,
    borderColor: 'black',
  }
});

export default Board;

Here's the output:

How can I make my code output a 5x5 grid of boxes?

Thank you


问:
3D Touch static shortcuts
Hey guys so my 3D touch shortcuts that I put in my info.plist show up but when I select them only the one that appears first in my code takes me to the view controller stated. The others just don't work (take me to the view I stated). </p>

```<code>func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "com.amansk.software" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "sw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if shortcutItem.type == "com.amansk.hardware" {
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "hw")
            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()
        }
    }
}
</code>```

答:
The second if statement should be OUTSIDE of the first one

```<code>func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "com.amansk.software" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "sw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    } else if shortcutItem.type == "com.amansk.hardware" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "hw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }
</code>```

}

Title: 3D Touch static shortcuts

Body:
Hey guys so my 3D touch shortcuts that I put in my info.plist show up but when I select them only the one that appears first in my code takes me to the view controller stated. The others just don't work (take me to the view I stated).

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "com.amansk.software" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "sw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if shortcutItem.type == "com.amansk.hardware" {
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "hw")
            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()
        }
    }
}

Body:
The second if statement should be OUTSIDE of the first one

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "com.amansk.software" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "sw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    } else if shortcutItem.type == "com.amansk.hardware" {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "hw")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }

}


问:
Alignment in Html.fromHtml()
Is alignment working in HTML.fromHtml() in a TextView?

I tried

```<code><div align="center"><p>Test</p></div>
</code>```

and some variaties of this, including putting the alignment tabs without parenthesis to the paragraph tag, but none worked. The text is always left.

Thanks for any help!

Yours.

答: I believe is more easy use the property Gravity in a TextView for center the text...</p>

ContentLicense: CC BY-SA 2.5

Title: Alignment in Html.fromHtml()

Body:
Is alignment working in HTML.fromHtml() in a TextView?

I tried

Test

and some variaties of this, including putting the alignment tabs without parenthesis to the paragraph tag, but none worked. The text is always left.

Thanks for any help!

Yours.


问:
Conditional call to second async function, based on data collected before the first async function
I have some data in a array.

```<code>let data = ['firstData', 'secondData'];
</code>```

The first object (firstData) always exists, secondData could be null. So I always use that to call my async function like:

```<code>myAsyncFunction(data[0]).then(result => {
    //do something here
});
</code>```

If data[1] exists, I wanna call myAsyncFunction with data[1].

My current solution is with nested promises. Like this:

```<code>myAsyncFunction(data[0]).then(result => {
    return result;
}).then(result => {
    if(data[1] !== null){
        myAsyncFunction(data[1].then(resultTwo => {
        //dostuff with data
      });
    }
});
</code>```

I don't really like this solution, but it does work. It must be a better way tho. result is always a object. I tried Promise.all but it does not work. I think it's a problem with "race condition" of some sort (I am on thin ice here).

Is my current solution the only one?

Here is what myAsuncFunction looks like:

```<code>myAsyncFunction(personData){
    return new Promise<any> ((resolve, reject) => {

        //Assingen private variables

    secondAsyncFunction(somePersonData).then(result =>
     {

                    //Do some sync stuff

          return someNewData; //not a promise
     })
         .then(thirdAsyncFunction)
         .then(data => {
              resolve(data);
         })
         .catch(error => {
          reject(error);
     });
});
</code>```

答:
You could just simply do:

const stuffOnlyRelatedToSecondData = result2 => /*do something*/

myAsyncFunction(data[0]).then(result => {
    if (data[1] === null) {return null}
    return myAsyncFunction(data[1]).then(stuffOnlyRelatedToSecondData)
}).then(/*Anything to do after [1] or [1,2]*/)```
</div>
</div>
</p>

<p>This way you can use the same chain and the two possible cases will look like:</p>

```myAsyncFunction(data[0]) --> END
myAsyncFunction(data[0]) --> myAsyncFunction(data[1]) --> END
```

<h2>Edit:</h2>

<p>It seems that <code>myAsyncFunction</code> may have a promise leak, try using something like this instead:</p>

```const myAsyncFunction = personData => {
    //Assigning private variables
    return secondAsyncFunction(somePersonData).then(result => {
        //Do some sync stuff
        return someNewData; //not a promise
    })
    .then(thirdAsyncFunction)
}
```

We can write it this way because secondAsyncFunction kicks off a new Promise, hence we don't need another Promise wrapper around it. And the catch can be put in the parent Promise chain itself which executes myAsyncFunction

Body:
I have some data in a array.

let data = ['firstData', 'secondData'];

The first object (firstData) always exists, secondData could be null. So I always use that to call my async function like:

myAsyncFunction(data[0]).then(result => {
    //do something here
});

If data[1] exists, I wanna call myAsyncFunction with data[1].

My current solution is with nested promises. Like this:

myAsyncFunction(data[0]).then(result => {
    return result;
}).then(result => {
    if(data[1] !== null){
        myAsyncFunction(data[1].then(resultTwo => {
        //dostuff with data
      });
    }
});

I don't really like this solution, but it does work. It must be a better way tho. result is always a object. I tried Promise.all but it does not work. I think it's a problem with "race condition" of some sort (I am on thin ice here).

Is my current solution the only one?

Here is what myAsuncFunction looks like:

myAsyncFunction(personData){
    return new Promise<any> ((resolve, reject) => {

        //Assingen private variables

    secondAsyncFunction(somePersonData).then(result =>
     {

                    //Do some sync stuff

          return someNewData; //not a promise
     })
         .then(thirdAsyncFunction)
         .then(data => {
              resolve(data);
         })
         .catch(error => {
          reject(error);
     });
});

Body:
You could just simply do:

const stuffOnlyRelatedToSecondData = result2 => /*do something*/

myAsyncFunction(data[0]).then(result => {
    if (data[1] === null) {return null}
    return myAsyncFunction(data[1]).then(stuffOnlyRelatedToSecondData)
}).then(/*Anything to do after [1] or [1,2]*/)

This way you can use the same chain and the two possible cases will look like:

myAsyncFunction(data[0]) --> END
myAsyncFunction(data[0]) --> myAsyncFunction(data[1]) --> END

Edit:

It seems that myAsyncFunction may have a promise leak, try using something like this instead:

const myAsyncFunction = personData => {
    //Assigning private variables
    return secondAsyncFunction(somePersonData).then(result => {
        //Do some sync stuff
        return someNewData; //not a promise
    })
    .then(thirdAsyncFunction)
}

We can write it this way because secondAsyncFunction kicks off a new Promise, hence we don't need another Promise wrapper around it. And the catch can be put in the parent Promise chain itself which executes myAsyncFunction


问:
how to extract an attribute value of div using BeautifulSoup
I have a div whose id is "img-cont"

```<code><div class="img-cont-box" id="img-cont" style='background-image: url("http://example.com/example.jpg");'>
</code>```

I want to extract the url in background-image using beautiful soup.How can I do it?

答:
You can you find_all or find for the first match.

```<code>import re
soup = BeautifulSoup(html_str)
result = soup.find('div',attrs={'id':'img-cont','style':True})
if result is not None:
  url = re.findall('\("(http.*)"\)',result['style']) # return a list.
</code>```

Body:
I have a div whose id is "img-cont"

I want to extract the url in background-image using beautiful soup.How can I do it?

Body:
You can you find_all or find for the first match.

import re
soup = BeautifulSoup(html_str)
result = soup.find('div',attrs={'id':'img-cont','style':True})
if result is not None:
  url = re.findall('\("(http.*)"\)',result['style']) # return a list.


问:
JavaScript if statement from select box
I can't figure out where I'm going wrong - when "Europe" is selected nothing happens.

When I take away the if statement it works, so the output code is definitely okay. The problem seems to be with the if condition.

```<code> <script>

 function shipping_calc() {
    var val = document.getElementById.("country").value;
    if(val === "Europe") {
        document.getElementById("output").innerHTML = "£2.40";
    }
 }

</script>

<select id="country" onchange="shipping_calc()">
  <option value="United Kingdom">United Kingdom</option>
  <option value="Europe">Europe</option>
  <option value="Worldwide">Worldwide</option>
</select>

<p id="output"></p>
</code>```

答:
Try this...  </p>

```<code>var vall = document.getElementById("country");
var val = vall.options[vall.selectedIndex].value;

if (val === "Europe") {
  document.getElementById("output").innerHTML = "£2.40";
}
</code>```

Title: JavaScript if statement from select box

Body:
I can't figure out where I'm going wrong - when "Europe" is selected nothing happens.

When I take away the if statement it works, so the output code is definitely okay. The problem seems to be with the if condition.

<select id="country" onchange="shipping_calc()">
  <option value="United Kingdom">United Kingdom</option>
  <option value="Europe">Europe</option>
  <option value="Worldwide">Worldwide</option>
</select>

Body:
Try this...

var vall = document.getElementById("country");
var val = vall.options[vall.selectedIndex].value;

if (val === "Europe") {
  document.getElementById("output").innerHTML = "£2.40";
}


问:
TestBench license and Jenkins on AWS
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

```<code>License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.
</code>```

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

```<code>-Dvaadin.testbench.developer.license=<LICENSE>
</code>```

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?

答:
The issue was the user context that Jenkins was running in.  While I assumed that it was under the default user it was actually running as another, so that the license needed to be in a different home directory to be detected.

However, this still fails to explain why the Java -D switch failed to load the license.  Maybe an issue here with Maven jobs on Jenkins passing arguments to TestBench?

Title: TestBench license and Jenkins on AWS

Body:
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

-Dvaadin.testbench.developer.license=<LICENSE>

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?


问:
How in Deploy configuration to create an artifact dependency? And prescribe a rule for artifacts?
I have two Build Configurations: 1. Bulid. 2. Deploy. In Build pointed folder with artifacts (http://prntscr.com/enws67). And in Deploy the dist folder is taken and moved to the server using rsync (the bash script is already written: http://prntscr.com/enwtzr).

( When I created the build steps from the same Build configuration, in the step where I needed to just deploy the site using the script I specified in the Command Line: C: \ cygwin64 \ bin \ bash.exe / cygdrive / c / cygwin64 / home / Team / Startsync.bash )

The idea is that the rules are set in the configuration, which generates artifacts (Build) and the configuration that consumes them (Deploy)
And thus one configuration can transfer other files.

How in Deploy configuration to create an artifact dependency? And prescribe a rule for artifacts?
Thanks you !

答:
Build the configuration of the artifacts, at the end download them and they are displayed in artifacts

In the Deploy configuration, go to Edit Configuration Settings -> Dependencies -> Add new artifact dependency

Depend on: specify Build configuration

Artifacts rules: * write rules

+: One =>.
-: second
+: Says to include folder one for download to the folder checkout.directory/

-: - excludes second folder

= = Refers to checkout.directory


问:
Is the percentage of CPU utlized by the .NET garbage collector an indicator of anything?
As an explanation for the slowness of an application, someone reported that the garbage collector, during collection, was taking up 17% of the CPU. To me, that statistic sounded irrelevant since 17% is not too much to worry anyway. Besides, it is an arbitrary metric that tells me nothing about the constitution of the process' memory.

What would be more relevant data to me would be things like:

How many Gen 2 collections did we have?

Show me the memory dump and let me party with it and come back to you. Let me look at the heapstat (!dumpheap -stat from psscorX), syncblocks, etc.

Show me the CPU utilization during a heavy period of slowness so I know it's not an I/O bound issue that's begging the introduction of asynchrony into the desgin.

How many garbage collections did we have since we launched suspect operation and how many of them were full collections?

Show me the LOH heap fragmentation.

Show me the unmanaged heap, the free space in the process and the total space occupied by the managed heap.

Profile the code and see what's taking time. Then zero in on the operation that's taking the most amount of time.

But the CPU utilization held by a run of garbage collection? That doesn't seem like a relevant metric to me at all.

So, I ask for a confirmation.

Is that metric of CPU utilized by the GC, esp. when it is only 17%, a relevant indicator of problems in the application?

Is there an expected threshold CPU utilization that the GC should normally fit within so as to be considered a normal collection of a nice and healthy application?

We're talking about a process run on a workstation version of the CLR.

答:
Garbage collection is a by-product of memory allocation.
If garbage collection takes 17% of CPU time, that indicates that memory allocation overall takes a larger fraction, like maybe 34%.
(Of course, if your program is I/O bound, CPU% is less important.)

One common way for programs to be slow (or to put it in positive terms, a common way to speed up programs) has to do with memory allocations that could be avoided.
I use the random pausing method of pinpointing these opportunities.

This link explores one example where pooling and re-using objects, rather than always allocating new ones, was one of the large speedups.
What always seems to need to be said is that programs typically have more than one way to be made to go faster, so performance tuning can go in stages.
So, suppose you are spending 34 out of 100 seconds of time right now on memory allocation, and suppose you could remove 30 of those. Then the time shrinks to 70 seconds, for a speedup of 100/70 = 1.43x.
Now there is almost certainly something else (not necessarily memory allocation) taking 20 seconds. It was 20/100 = 20%, but after fixing the first problem it is more; it is 20/70 = 29%.
It got bigger proportionally by the first speedup.
Fixing it gives a speedup of 70/50 = 1.4x.
If you have multiple problems and you fix them one at a time, their speedup factors multiply together and can be quite dramatic.


问:
Formatting a date returned from an Observable array
I am trying to format a date value returned from a rest service as an observable. The createdOn and modifiedOn dates are being rendered in my HTML as /Date(1298937600000)/, I would like them formatted as dd/MM/yyyy. I have seen a few similar posts but none seem to point me in the right direction or are beyond my current understanding of Angular 2.

I am making a call to my API as such:

```<code>getUnLocationsList(): Observable<UnLocations[]> {

    var url = "http://localhost:5000/api/unlocations"
    return this._http.get(url)
        .map((response: Response) => <UnLocations[]>response.json().unLocations)
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
</code>```

From my Angular 2 Component I am then calling the getUnLocationsList() function, like this:

```<code>export class StandingDataComponent implements OnInit {

 pageTitle: string = 'UnLocation Codes';
 unLocationsList: UnLocations[];

 constructor(private _staticDataService: StaticDataService) { }

 ngOnInit() {
 this.getUnLocationsList();
 }
 getUnLocationsList() {
  this._staticDataService.getUnLocationsList().subscribe(unLocationsList => this.unLocationsList = unLocationsList),
  err => console.error(err),
  () => console.log("finished loading unlocations");
</code>```

}

finally I am using then using a simple *ngFor to display the data

```<code><tbody *ngFor="let unLocation of unLocationsList | paginate: {itemsPerPage: 30, currentPage:page, id: '1'}; let i = index">
    <td style="width:100px"> {{unLocation.code}} </td>
    <td style="width:200px"> {{unLocation.name}} </td>
    <td style="width:200px">{{unLocation.isActive}}</td>
    <td style="width:200px">{{unLocation.createdOn }}</td>
     <td style="width:200px">{{unLocation.modifiedOn }}</td>
  </tbody>
</code>```

答:
Finally got this working. Pipes did not seem to work, however, iterating over each item in the list (as suggested) did the trick. Here's my code </p>

```<code>private extractData(res: Response) {
    var data = res.json().unLocations || [];
    data.forEach((d) => {
        d.createdOn = new Date(parseInt(d.createdOn.substr(6)));

        if (d.modifiedOn != null)
            d.modifiedOn = new Date(parseInt(d.modifiedOn.substr(6)));
    });
    return data;
}
</code>```

Body:
I am trying to format a date value returned from a rest service as an observable. The createdOn and modifiedOn dates are being rendered in my HTML as /Date(1298937600000)/, I would like them formatted as dd/MM/yyyy. I have seen a few similar posts but none seem to point me in the right direction or are beyond my current understanding of Angular 2.

I am making a call to my API as such:

getUnLocationsList(): Observable<UnLocations[]> {

    var url = "http://localhost:5000/api/unlocations"
    return this._http.get(url)
        .map((response: Response) => <UnLocations[]>response.json().unLocations)
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

From my Angular 2 Component I am then calling the getUnLocationsList() function, like this:

export class StandingDataComponent implements OnInit {

 pageTitle: string = 'UnLocation Codes';
 unLocationsList: UnLocations[];

 constructor(private _staticDataService: StaticDataService) { }

 ngOnInit() {
 this.getUnLocationsList();
 }
 getUnLocationsList() {
  this._staticDataService.getUnLocationsList().subscribe(unLocationsList => this.unLocationsList = unLocationsList),
  err => console.error(err),
  () => console.log("finished loading unlocations");

}

finally I am using then using a simple *ngFor to display the data

     {{unLocation.code}}
     {{unLocation.name}}
    {{unLocation.isActive}}
    {{unLocation.createdOn }}
     {{unLocation.modifiedOn }}

Body:
Finally got this working. Pipes did not seem to work, however, iterating over each item in the list (as suggested) did the trick. Here's my code

private extractData(res: Response) {
    var data = res.json().unLocations || [];
    data.forEach((d) => {
        d.createdOn = new Date(parseInt(d.createdOn.substr(6)));

        if (d.modifiedOn != null)
            d.modifiedOn = new Date(parseInt(d.modifiedOn.substr(6)));
    });
    return data;
}


问:
Why can't I get my script tag src's to work?
I have been coding up a localhost, and I made the localhost by using of course a JavaScript file to do so, and I then made it reference an HTML file. However, I noticed that when I am using localhost to serve up the HTML file I get this error:

```<code>"GET http://localhost:3333/filetesting.js"
</code>```

The filetesting.js is that js file, there are also other things I'm referencing too, like websites. I'm referencing it by using script tag src.

I looked at the network on developer tools of it and it says it's a 404 error not found. I'm trying to figure out how to reference my script tag src's without having localhost:3333 go before it.

When I run the HTML file without using the localhost, it works just fine when it comes to the script tag src's. If you do not entirely understand what I'm asking for, just ask.

答:
Assuming that your script will always reside in the root level of your website, you can simply target it with the root-relative prefix /:

```<code><script src="/filetesting.js"></script>
</code>```

This will load your script from the root, regardless of the site the file is hosted on. For example, on http://localhost:3333/ it will load the file from http://localhost:3333/filetesting.js, and from http://localhost:3333/folder/, it will attempt to load the file from the same location.

If you move your files over to a proper website, it will still work the same way: www.example.com will look for the file at www.example.com/filetesting.js, and www.example.com/folder/ will look for the same file at www.example.com/filetesting.js.

Hope this helps! :)

Body:
I have been coding up a localhost, and I made the localhost by using of course a JavaScript file to do so, and I then made it reference an HTML file. However, I noticed that when I am using localhost to serve up the HTML file I get this error:

"GET http://localhost:3333/filetesting.js"

The filetesting.js is that js file, there are also other things I'm referencing too, like websites. I'm referencing it by using script tag src.

I looked at the network on developer tools of it and it says it's a 404 error not found. I'm trying to figure out how to reference my script tag src's without having localhost:3333 go before it.

When I run the HTML file without using the localhost, it works just fine when it comes to the script tag src's. If you do not entirely understand what I'm asking for, just ask.

Body:
Assuming that your script will always reside in the root level of your website, you can simply target it with the root-relative prefix /:

<script src="/filetesting.js"></script>

This will load your script from the root, regardless of the site the file is hosted on. For example, on http://localhost:3333/ it will load the file from http://localhost:3333/filetesting.js, and from http://localhost:3333/folder/, it will attempt to load the file from the same location.

If you move your files over to a proper website, it will still work the same way: www.example.com will look for the file at www.example.com/filetesting.js, and www.example.com/folder/ will look for the same file at www.example.com/filetesting.js.

Hope this helps! :)


问:
Trying to get an average using the contents of two files
So I have two files in my directory that contain a number in each of them. I want to make a script that calculates the average of these two numbers. How would I write it? Would this be correct?</p>

```<code>avg=$((${<file1.txt}-${<file2.txt})/2)
</code>```

答:
Your example does not work. Furthermore, your formula is probably incorrect. Here are two options without unnecessary cat:

```<code>avg=$(( (`<file1.txt` + `<file2.txt`) / 2 ))
</code>```

or

```<code>avg=$(( ($(<file1.txt) + $(<file2.txt)) / 2 ))
</code>```

I find the first one more readable though. Also be warned: this trivial approach will cause problems when your files contain more than just the plain numbers.

EDIT:

I should have noted that the first syntactical/legacy option which uses the backticks (` `) is no longer recommended and should be avoided. You can read more about the WHY here. Thanks at mklement0 for the link!

EDIT2:

According to Eric, the values are floating point numbers. You can't do this directly in bash because only integer numbers are supported. You have to use a little helper:

```<code>avg=$(bc <<< "( $(<file1.txt) + $(<file2.txt) ) / 2")
</code>```

or maybe easier to understand

```<code>avg=$(echo "( $(<file1.txt) + $(<file2.txt) ) / 2" | bc)
</code>```

For those who might wonder what bc is (see man bc):

bc  is  a  language that supports arbitrary precision numbers with
  interactive execution of statements.

Here is another alternative since perl is usually installed by default:

```<code>avg=$(perl -e 'print( ($ARGV[0] + $ARGV[1]) / 2 )' -- $(<file1.txt) $(<file2.txt))
</code>```

Body:
So I have two files in my directory that contain a number in each of them. I want to make a script that calculates the average of these two numbers. How would I write it? Would this be correct?

avg=$((${<file1.txt}-${<file2.txt})/2)

Body:
Your example does not work. Furthermore, your formula is probably incorrect. Here are two options without unnecessary cat:

avg=$(( (`<file1.txt` + `<file2.txt`) / 2 ))

or

avg=$(( ($(<file1.txt) + $(<file2.txt)) / 2 ))

I find the first one more readable though. Also be warned: this trivial approach will cause problems when your files contain more than just the plain numbers.

EDIT:

I should have noted that the first syntactical/legacy option which uses the backticks (` `) is no longer recommended and should be avoided. You can read more about the WHY here. Thanks at mklement0 for the link!

EDIT2:

According to Eric, the values are floating point numbers. You can't do this directly in bash because only integer numbers are supported. You have to use a little helper:

avg=$(bc <<< "( $(<file1.txt) + $(<file2.txt) ) / 2")

or maybe easier to understand

avg=$(echo "( $(<file1.txt) + $(<file2.txt) ) / 2" | bc)

For those who might wonder what bc is (see man bc):

bc  is  a  language that supports arbitrary precision numbers with
  interactive execution of statements.

Here is another alternative since perl is usually installed by default:

avg=$(perl -e 'print( ($ARGV[0] + $ARGV[1]) / 2 )' -- $(<file1.txt) $(<file2.txt))


问:
javax.el.PropertyNotFoundException: The class 'PureJavaClasses.employeeClass' does not have the property 'Id'
I have been trying to print a ResultSet inside a JSP with the help of a Servlet through an ArrayList.The JDBC part seems all right.The ArrayList can be obtained inside the JSP and can be printed.But when I want to iterate the list passed onto the JSP with the <c:forEach> tag,the it is saying that my bean class 'PureJavaClasses.employeeClass' doesn't have the attribute 'Id'. I have tried a bunch of different solutions posted on SO but all in vain.I am out of ideas about what to do.I am a total beginner in JavaEE.

Here is my Bean class:

```<code>public class employeeClass implements java.io.Serializable {
private int id;
private String name;
private String job;
private int subjectId;
private int salary;

public employeeClass() {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public int getSubjectid() {
    return subjectId;
}

public void setSubjectid(int subjectId) {
    this.subjectId = subjectId;
}

public int getSalary() {
    return salary;
}

public void setSalary(int salary) {
    this.salary = salary;
}

@Override
public String toString() {
    return  "id=" + id +
            ", name=" + name +
            ", job=" + job +
            ", subjectId=" + subjectId +
            ", salary=" + salary;
}
}
</code>```

Here is the servlet:

```<code>private void show_table(HttpServletRequest request,HttpServletResponse response){
    Connection connection = ServletLogin.connection;
    String query = "SELECT * FROM `dog`.`employee`";
    ArrayList<employeeClass> list = new ArrayList<>();
    try {
        PreparedStatement pst = connection.prepareStatement(query);
        ResultSet rs = pst.executeQuery();
        while(rs.next()){
            employeeClass obj2 = new employeeClass();
            obj2.setId(rs.getInt("ID"));
            obj2.setName(rs.getString("Name"));
            obj2.setJob(rs.getString("Job_Designation"));
            obj2.setSubjectid(rs.getInt("Subject ID"));
            obj2.setSalary(rs.getInt("Salary"));
            list.add(obj2);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    request.setAttribute("listEmp",list);
    try {
        request.getRequestDispatcher("/Pages/EmployeeTable.jsp").forward(request,response);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Here is my EmployeeTable.jsp :

```<code>    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.util.ArrayList"%>
<html>

<head>
    <title>Employee List</title>
</head>
<body>
<% ArrayList list1 =(ArrayList) request.getAttribute("listEmp"); %>
<%=list1%>
    <table>
        <th>ID</th>
        <th>Name</th>
        <th>Job Designation</th>
        <th>Subject ID</th>
        <th>Salary</th>
        <c:forEach items="${listEmp}" var="list">
            <tr>
                <td><c:out value="${list.Id}"/></td>
                <td><c:out value="${list.name}"/></td>
                <td><c:out value="${list.job}"/></td>
                <td><c:out value="${list.subjectId}"/></td>
                <td><c:out value="${list.salary}"/></td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
</code>```

Here is my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>ServletLogin</servlet-name>
        <servlet-class>ServletLogin</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ServletEmployee</servlet-name>
        <servlet-class>ServletEmployee</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletLogin</servlet-name>
        <url-pattern>/ServletLogin</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ServletEmployee</servlet-name>
        <url-pattern>/ServletEmployee</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

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

答:
I think you need to fix by providing correct names. Like use id instead of Id, etc. That should solve it.</p>

```<code><td><c:out value="${list.id}"/></td>
</code>```

Body:
I have been trying to print a ResultSet inside a JSP with the help of a Servlet through an ArrayList.The JDBC part seems all right.The ArrayList can be obtained inside the JSP and can be printed.But when I want to iterate the list passed onto the JSP with the <c:forEach> tag,the it is saying that my bean class 'PureJavaClasses.employeeClass' doesn't have the attribute 'Id'. I have tried a bunch of different solutions posted on SO but all in vain.I am out of ideas about what to do.I am a total beginner in JavaEE.

Here is my Bean class:

public class employeeClass implements java.io.Serializable {
private int id;
private String name;
private String job;
private int subjectId;
private int salary;

public employeeClass() {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public int getSubjectid() {
    return subjectId;
}

public void setSubjectid(int subjectId) {
    this.subjectId = subjectId;
}

public int getSalary() {
    return salary;
}

public void setSalary(int salary) {
    this.salary = salary;
}

@Override
public String toString() {
    return  "id=" + id +
            ", name=" + name +
            ", job=" + job +
            ", subjectId=" + subjectId +
            ", salary=" + salary;
}
}

Here is the servlet:

private void show_table(HttpServletRequest request,HttpServletResponse response){
    Connection connection = ServletLogin.connection;
    String query = "SELECT * FROM `dog`.`employee`";
    ArrayList<employeeClass> list = new ArrayList<>();
    try {
        PreparedStatement pst = connection.prepareStatement(query);
        ResultSet rs = pst.executeQuery();
        while(rs.next()){
            employeeClass obj2 = new employeeClass();
            obj2.setId(rs.getInt("ID"));
            obj2.setName(rs.getString("Name"));
            obj2.setJob(rs.getString("Job_Designation"));
            obj2.setSubjectid(rs.getInt("Subject ID"));
            obj2.setSalary(rs.getInt("Salary"));
            list.add(obj2);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    request.setAttribute("listEmp",list);
    try {
        request.getRequestDispatcher("/Pages/EmployeeTable.jsp").forward(request,response);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Here is my EmployeeTable.jsp :

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.util.ArrayList"%>

    <title>Employee List</title>

<% ArrayList list1 =(ArrayList) request.getAttribute("listEmp"); %>
<%=list1%>

        ID
        Name
        Job Designation
        Subject ID
        Salary
        <c:forEach items="${listEmp}" var="list">

                <c:out value="${list.Id}"/>
                <c:out value="${list.name}"/>
                <c:out value="${list.job}"/>
                <c:out value="${list.subjectId}"/>
                <c:out value="${list.salary}"/>

        </c:forEach>

Here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>ServletLogin</servlet-name>
        <servlet-class>ServletLogin</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ServletEmployee</servlet-name>
        <servlet-class>ServletEmployee</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletLogin</servlet-name>
        <url-pattern>/ServletLogin</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ServletEmployee</servlet-name>
        <url-pattern>/ServletEmployee</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

</web-app>

Body:
I think you need to fix by providing correct names. Like use id instead of Id, etc. That should solve it.

<td><c:out value="${list.id}"/></td>


答:
Promise.all is designed to be used when you have a dynamic number of promises in an array, and you want to combine them into a promise which resolves when all of the promises in the array have resolved.

According to your use case, you should be able to use it like this:

```<code>data = data.filter(x => x !== null);

Promise.all(data.map(myAsyncFunction)).then((results) => {
    const [resultOne, resultTwo] = results;
    if (resultTwo) {
        // handle resultTwo
    }
    // handle resultOne
});
</code>```

Title: Conditional call to second async function, based on data collected before the first async function

Body:
Promise.all is designed to be used when you have a dynamic number of promises in an array, and you want to combine them into a promise which resolves when all of the promises in the array have resolved.

According to your use case, you should be able to use it like this:

data = data.filter(x => x !== null);

Promise.all(data.map(myAsyncFunction)).then((results) => {
    const [resultOne, resultTwo] = results;
    if (resultTwo) {
        // handle resultTwo
    }
    // handle resultOne
});


答:
You had an extra . in your javascript. This works.

function shipping_calc() {

  var val = document.getElementById("country").value;

  if (val === "Europe") {
    document.getElementById("output").innerHTML = "£2.40";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="country" onchange="shipping_calc()">
  <option value="United Kingdom">United Kingdom</option>
  <option value="Europe">Europe</option>
  <option value="Worldwide">Worldwide</option>
</select>

<p id="output"></p></code>```

You had document.getElementById.("country") and it should have been document.getElementById("country").

Title: JavaScript if statement from select box

Body:
You had an extra . in your javascript. This works.

function shipping_calc() {

  var val = document.getElementById("country").value;

  if (val === "Europe") {
    document.getElementById("output").innerHTML = "£2.40";
  }
}

<select id="country" onchange="shipping_calc()">
  <option value="United Kingdom">United Kingdom</option>
  <option value="Europe">Europe</option>
  <option value="Worldwide">Worldwide</option>
</select>

<p id="output"></p>

You had document.getElementById.("country") and it should have been document.getElementById("country").


问:
Mock GPS routes in android emulator
How can I simulate movement of the emulator in a program that is tracking speed using the GPS?
I understand that the general way to go about it is to go into the DDMS perspective, and then under emulator control upload a gpx file and press play to simulate that track.  However, my code is not detecting the movement... and I am not sure if it is because of something wrong with my code or something wrong with the simulated emulator gpx.  My code is simply

```<code>public void onLocationChanged(Location myLocal) {
    float mySpeed=-1;
            if(myLocal.hasSpeed()){
                    mySpeed = myLocal.getSpeed();
            }
    ...
}
</code>```

I have uploaded my gpx file and have pressed play, but no call to onLocationChanged occurs.  If someone would be able to suggest a method to determine where the problem may lie it would be much appreciated.

Update 1 : I've found that the onLocationChanged method does get called when I use a real phone and not the emulator.

答: I had some issues with this some time ago. I'd recommend repeating the experiment using google maps or another equivalent app to isolate the issue to your code or to the emulator.</p>

Title: Mock GPS routes in android emulator

Body:
How can I simulate movement of the emulator in a program that is tracking speed using the GPS?
I understand that the general way to go about it is to go into the DDMS perspective, and then under emulator control upload a gpx file and press play to simulate that track.  However, my code is not detecting the movement... and I am not sure if it is because of something wrong with my code or something wrong with the simulated emulator gpx.  My code is simply

public void onLocationChanged(Location myLocal) {
    float mySpeed=-1;
            if(myLocal.hasSpeed()){
                    mySpeed = myLocal.getSpeed();
            }
    ...
}

I have uploaded my gpx file and have pressed play, but no call to onLocationChanged occurs.  If someone would be able to suggest a method to determine where the problem may lie it would be much appreciated.

Update 1 : I've found that the onLocationChanged method does get called when I use a real phone and not the emulator.


问:
How to add a mouseEntered event for each element of a JList
I have a program and I want to add a mouseEntered event for each element in the JList. When the cursor is on an element (not clicking) of the JList, this has to change it format so you know wich element will you select. I read about a ListCellRendered but I couldn't solve it.</p>

答:
you just try it with mouse event of Mouse Entered.
but without clicking on the list view it's not possible to find the position.
because the JList is on the ScrollView so it the position of the mouse could not identify the where it standing on the List.</p>


答:
Here's a fiddle: https://jsfiddle.net/6dvgbjr0/

You had an error in your code, with an extra period:

```<code>var val = document.getElementById.("country").value;
</code>```

Title: JavaScript if statement from select box

Body:
Here's a fiddle: https://jsfiddle.net/6dvgbjr0/

You had an error in your code, with an extra period:

var val = document.getElementById.("country").value;


问:
Bluebird Promise.all doesn't get called
I have a url which returns a list of other urls
For each url, I want to do stuff and then use Promise.all to tell me that it finished.

For some reason, it does process all urls, but the Promise.all doesn't seem to be called (Bluebird)

What am I doing wrong?

```<code>var rp = require("request-promise");
var Promise = require("bluebird");

var promrequests = [];
rp(
 {
  url: url_of_list_of_urls,
  json: true,
 },
 function(error, response, body) {
  if (!error && response.statusCode === 200) {
   let urls = [];
   for (var i in body) {
    urls.push(body[i]);
   }

   for (let j in urls) {
    let url = urls[j];

    promrequests.push(
     rp(
      { url: url, followAllRedirects: true },
      function(error, response, body) {
       console.log("working on " + url);
       // do stuff
      }
     )
    );
   }

   Promise.all(promrequests).then(function() {
    console.log("finished all");
   });
  }
 }
);
</code>```

答:
There's no need to use callbacks with the request-promise library, the example code is a mixture of the original request callback API and the request-promise API.

Bluebird also has a .map helper to make working with arrays easier.

Dropping all the callbacks and returning promises throughout the chain gives you something like (untested):

```<code>requestOptionsUrls = {
  url: url_of_list_of_urls,
  json: true,
}
rp(requestOptionsUrls).then(function(urls){
  return Promise.map(urls, function(url){
    return rp({ url: url, followAllRedirects: true })
      .then(function(body){
        console.log("working on " + url);
        // work
      })
  })
})
.then(function(){
  console.log("finished all");
})
.catch(function(error){
  console.error(error)
})
</code>```

request-promise will do 2XX checking for you unless you set the simple request option to false.

It also only resolves the body of the request unless you set the resolveWithFullResponse to true, say if you wanted to do more complex checks on the status code of the response.

Title: Bluebird Promise.all doesn't get called

Body:
I have a url which returns a list of other urls
For each url, I want to do stuff and then use Promise.all to tell me that it finished.

For some reason, it does process all urls, but the Promise.all doesn't seem to be called (Bluebird)

What am I doing wrong?

var rp = require("request-promise");
var Promise = require("bluebird");

var promrequests = [];
rp(
 {
  url: url_of_list_of_urls,
  json: true,
 },
 function(error, response, body) {
  if (!error && response.statusCode === 200) {
   let urls = [];
   for (var i in body) {
    urls.push(body[i]);
   }

   for (let j in urls) {
    let url = urls[j];

    promrequests.push(
     rp(
      { url: url, followAllRedirects: true },
      function(error, response, body) {
       console.log("working on " + url);
       // do stuff
      }
     )
    );
   }

   Promise.all(promrequests).then(function() {
    console.log("finished all");
   });
  }
 }
);

Body:
There's no need to use callbacks with the request-promise library, the example code is a mixture of the original request callback API and the request-promise API.

Bluebird also has a .map helper to make working with arrays easier.

Dropping all the callbacks and returning promises throughout the chain gives you something like (untested):

requestOptionsUrls = {
  url: url_of_list_of_urls,
  json: true,
}
rp(requestOptionsUrls).then(function(urls){
  return Promise.map(urls, function(url){
    return rp({ url: url, followAllRedirects: true })
      .then(function(body){
        console.log("working on " + url);
        // work
      })
  })
})
.then(function(){
  console.log("finished all");
})
.catch(function(error){
  console.error(error)
})

request-promise will do 2XX checking for you unless you set the simple request option to false.

It also only resolves the body of the request unless you set the resolveWithFullResponse to true, say if you wanted to do more complex checks on the status code of the response.


问:
unable to install or run C# application on client PC
I have developed a desktop application in c# & SQL server 2012 using Visual Studio 2013. I have included the reference for Microsoft.VisualStudio.DebuggerVisualizers and set copy local : true.
The application runs perfectly on client systems with windows 8, 10.
But its showing this error while installing on a windows 7 system.
- OS Windows 7 Ultimate
- already installed .NET Framework 4.5
- installed Report Viewer.exe 2012
- installed report viewer.msi 2010
- installed sqlclr types
- the system doesnt have any microsoft c++ redistributable , i am not sure whether it has any impact.
I checked in the assembly folder, but couldnt find the  Microsoft.VisualStudio.DebuggerVisualizers.dll
Am I missing any prerequisites here? How to solve this issue so that i can install the application

Error Message

答:
Unintentionally the Microsoft.VisualStudio.DebuggerVisualizers.dll had been included in the project reference. And in the client system the specified dll could not be found even after trying to install it. Hence I removed it from reference and then it worked perfectly fine without any issues. I guess instead of report visualizer i have included debuggervisualizer. It was a manual error.
Thank you for your support</p>


问:
Rails, joining two tables with where clauses on each tabe
I'm new to web development and rails, and I'm trying to construct a query object for my first time. I have a table Players, and a table DefensiveStats, which has a foriegn-key player_id, so each row in this table belongs to a player. Players have a field api_player_number, which is an id used by a 3rd party that I'm referencing. A DefensiveStats object has two fields that are relevant for this query - a season_number integer and a week_number integer. What I'd like to do is build a single query that takes 3 parameters: an api_player_number, season_number, and week_number, and it should return the DefensiveStats object with the corresponding season and week numbers, that belongs to the player with api_player_number = passed in api_player_number.

Here is what I have attempted:

```<code>class DefensiveStatsWeekInSeasonQuery
def initialize(season_number, week_number, api_player_number)
    @season_number = season_number
    @week_number = week_number
    @api_player_number = api_player_number
end

# data method always returns an object or list of object, not a relation
def data
    defensive_stats = Player.where(api_player_number: @api_player_number)
    .joins(:defensive_stats)
    .where(season_number:@season_number, week_number: @week_number)
    if defensive_stats.nil?
        defensive_stats = DefensiveStats.new
    end
    defensive_stats
end
</code>```

end

However, this does not work, as it performs the second where clause on the Player class, and not the DefensiveStats class -> specifically, "SQLite3::SQLException: no such column: players.season_number"

How can I construct this query? Thank you!!!

答:
```<code>Player.joins(:defensive_stats).where(players: {api_player_number: @api_player_number}, defensive_stats: {season_number: @season_number, week_number: @week_number})
</code>```

OR

```<code>Player.joins(:defensive_stats).where("players.api_player_number = ? and defensive_stats.season_number = ? and defensive_stats.week_number = ?", @api_player_number, @season_number, @week_number)
</code>```

Body:
I'm new to web development and rails, and I'm trying to construct a query object for my first time. I have a table Players, and a table DefensiveStats, which has a foriegn-key player_id, so each row in this table belongs to a player. Players have a field api_player_number, which is an id used by a 3rd party that I'm referencing. A DefensiveStats object has two fields that are relevant for this query - a season_number integer and a week_number integer. What I'd like to do is build a single query that takes 3 parameters: an api_player_number, season_number, and week_number, and it should return the DefensiveStats object with the corresponding season and week numbers, that belongs to the player with api_player_number = passed in api_player_number.

Here is what I have attempted:

class DefensiveStatsWeekInSeasonQuery
def initialize(season_number, week_number, api_player_number)
    @season_number = season_number
    @week_number = week_number
    @api_player_number = api_player_number
end

# data method always returns an object or list of object, not a relation
def data
    defensive_stats = Player.where(api_player_number: @api_player_number)
    .joins(:defensive_stats)
    .where(season_number:@season_number, week_number: @week_number)
    if defensive_stats.nil?
        defensive_stats = DefensiveStats.new
    end
    defensive_stats
end

end

However, this does not work, as it performs the second where clause on the Player class, and not the DefensiveStats class -> specifically, "SQLite3::SQLException: no such column: players.season_number"

How can I construct this query? Thank you!!!

Body:
Player.joins(:defensive_stats).where(players: {api_player_number: @api_player_number}, defensive_stats: {season_number: @season_number, week_number: @week_number})

OR

Player.joins(:defensive_stats).where("players.api_player_number = ? and defensive_stats.season_number = ? and defensive_stats.week_number = ?", @api_player_number, @season_number, @week_number)