问:
Find specific table using BeautifulSoup with specific caption
I am attempting to locate the specific table below in the given HTML:

```<code><table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
                        <caption>Tennessee Tech<span class="hide"> - Pitching Stats</span></caption>
</code>```

My approach was to find the caption, then proceed to find the parent table, from which I will iterate through the rows to find my desired text (I can accomplish this part on my own). I believe my error is buried in the fact that the caption text continues into the span tag, however not sure if this is the case. My code to do so is given below, however it continues to return None because it cannot locate the table (something with my syntax is likely incorrect):

```<code>from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

test = soup.find('caption', text = 'Tennessee Tech').find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})
</code>```

答:
Do:

```<code>from bs4 import BeautifulSoup

html = """
<table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
<caption>
Tennessee Tech
<span class="hide"> - Pitching Stats</span>
</caption>
</table>
"""

soup = BeautifulSoup(html, 'html.parser')

table = soup.find('table', {'class': 'sidearm-table'})

print(table.contents)
</code>```

Output:

```<code>['\n', <caption>
Tennessee Tech
<span class="hide"> - Pitching Stats</span>
</caption>, '\n']
</code>```

But your URL is not found (timeout) :

http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117

Body:
I am attempting to locate the specific table below in the given HTML:

Tennessee Tech - Pitching Stats

My approach was to find the caption, then proceed to find the parent table, from which I will iterate through the rows to find my desired text (I can accomplish this part on my own). I believe my error is buried in the fact that the caption text continues into the span tag, however not sure if this is the case. My code to do so is given below, however it continues to return None because it cannot locate the table (something with my syntax is likely incorrect):

from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

test = soup.find('caption', text = 'Tennessee Tech').find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})

Body:
Do:

from bs4 import BeautifulSoup

html = """
<table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
<caption>
Tennessee Tech
<span class="hide"> - Pitching Stats</span>
</caption>
</table>
"""

soup = BeautifulSoup(html, 'html.parser')

table = soup.find('table', {'class': 'sidearm-table'})

print(table.contents)

Output:

['\n', <caption>
Tennessee Tech
<span class="hide"> - Pitching Stats</span>
</caption>, '\n']

But your URL is not found (timeout) :

http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117


来源: stackexchange

问:
How to go over angular collection
I have the following structure in Component:

```<code>const Data = {
"java : [{text: "question", answer: "yes"},
    {text: "some question", answer: "yes"}],
"python":[{text: "some question", answer: "yes"},
        {text: "some question", answer: "no"}],
}
}
</code>```

And now I want to go over this collection and output questions with answers in the list. I am doing that like this:

```<code> <p *ngFor="let line of currentComponent" class="center">
    {{line.text}}
    {{line.answer}}
 </p>
</code>```

But this code doesn't show anything. If I try to display currentComponent it displays

[object Object],[object Object]

currentComponent is deffined:

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

  @Input() title:string;

  currentComponent:ThisComponent;

  line:string;

  ngOnInit() {
    this.currentComponent = this.thisServise.getCourse(this.title);
  }

}
</code>```

What is wrong?

答:
Change this currentComponent: CourseComponent; to

currentComponent: Array<{ text: string, answer: string }>;

ContentLicense: CC BY-SA 3.0

Title: How to go over angular collection

Body:
I have the following structure in Component:

const Data = {
"java : [{text: "question", answer: "yes"},
    {text: "some question", answer: "yes"}],
"python":[{text: "some question", answer: "yes"},
        {text: "some question", answer: "no"}],
}
}

And now I want to go over this collection and output questions with answers in the list. I am doing that like this:

    {{line.text}}
    {{line.answer}}

But this code doesn't show anything. If I try to display currentComponent it displays

[object Object],[object Object]

currentComponent is deffined:

export class ThisComponent implements OnInit {

  @Input() title:string;

  currentComponent:ThisComponent;

  line:string;

  ngOnInit() {
    this.currentComponent = this.thisServise.getCourse(this.title);
  }

}

What is wrong?


问:
Given only vector of dates, expand data in between (unequal) date points
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

```<code>dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))
</code>```

I would like the data to look like this:

```<code>dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))
</code>```

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

答:
Here is a really fast pure base R solution:

```<code>ExpandDates <- function(df, lastColRepeat) {
    myDiff <- diff(df$date)
    dfOut <- data.frame(df$date[1] + 0:(sum(myDiff) + lastColRepeat - 1L),
                     stringsAsFactors=FALSE)
    myDiff <- c(myDiff, lastColRepeat)
    for (i in 2:3) {dfOut[,i] <- rep(df[ ,i], times = myDiff)}
    names(dfOut) <- names(df)
    dfOut
}
</code>```

The last argument is to determine the number of times the last value should be repeated. As it stands, there is nothing in the original data.frame that would give this value.  I'm also assuming that the "date" field is actually a date as pointed out by @Scarabee.

Here is some test data:

```<code>set.seed(123)
workVec <- sample(5000, 3000)
testDF <- data.frame(date = as.Date(sort(sample(12000, 3000)),
                                    origin = "1970-01-01"), work = workVec,
                                                    cumwork = cumsum(workVec))

DplyrTest <- function(dd) {  ## from @Scarabee
    v <- data.frame(date = seq(min(dd$date), max(dd$date), by="day"))
    v %>%
        left_join(dd, by = "date") %>%
        na.locf
}

a <- ExpandDates(testDF, 1)
b <- DplyrTest(testDF)
</code>```

Test for equality:

```<code>identical(a$cumwork, as.integer(b$cumwork))
[1] TRUE
identical(a$work, as.integer(b$work))
[1] TRUE
identical(a$date, as.Date(b$date))
[1] TRUE
</code>```

Benchmarks:

```<code>library(microbenchmark)
microbenchmark(DplyrTest(testDF), ExpandDates(testDF,1))
Unit: milliseconds
                  expr       min        lq      mean    median        uq       max neval cld
     DplyrTest(testDF) 80.909303 84.337006 91.315057 86.320883 88.818739 173.69395   100   b
ExpandDates(testDF, 1)  1.122384  1.208184  2.521693  1.355564  1.486317  72.23444   100  a
</code>```

Body:
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))

I would like the data to look like this:

dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

Body:
Here is a really fast pure base R solution:

ExpandDates <- function(df, lastColRepeat) {
    myDiff <- diff(df$date)
    dfOut <- data.frame(df$date[1] + 0:(sum(myDiff) + lastColRepeat - 1L),
                     stringsAsFactors=FALSE)
    myDiff <- c(myDiff, lastColRepeat)
    for (i in 2:3) {dfOut[,i] <- rep(df[ ,i], times = myDiff)}
    names(dfOut) <- names(df)
    dfOut
}

The last argument is to determine the number of times the last value should be repeated. As it stands, there is nothing in the original data.frame that would give this value.  I'm also assuming that the "date" field is actually a date as pointed out by @Scarabee.

Here is some test data:

set.seed(123)
workVec <- sample(5000, 3000)
testDF <- data.frame(date = as.Date(sort(sample(12000, 3000)),
                                    origin = "1970-01-01"), work = workVec,
                                                    cumwork = cumsum(workVec))

DplyrTest <- function(dd) {  ## from @Scarabee
    v <- data.frame(date = seq(min(dd$date), max(dd$date), by="day"))
    v %>%
        left_join(dd, by = "date") %>%
        na.locf
}

a <- ExpandDates(testDF, 1)
b <- DplyrTest(testDF)

Test for equality:

identical(a$cumwork, as.integer(b$cumwork))
[1] TRUE
identical(a$work, as.integer(b$work))
[1] TRUE
identical(a$date, as.Date(b$date))
[1] TRUE

Benchmarks:

library(microbenchmark)
microbenchmark(DplyrTest(testDF), ExpandDates(testDF,1))
Unit: milliseconds
                  expr       min        lq      mean    median        uq       max neval cld
     DplyrTest(testDF) 80.909303 84.337006 91.315057 86.320883 88.818739 173.69395   100   b
ExpandDates(testDF, 1)  1.122384  1.208184  2.521693  1.355564  1.486317  72.23444   100  a


问:
"Uncaught TypeError: csv.replace is not a function" when using csv jquery plugin, how do I fix this?
In the following code:

```<code>  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);
</code>```

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
</code>```

答:
First thing's first, you're not using XMLHttpRequest right. Reference this site to see how to use it. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Secondly, you can't do this without a web server to host your csv file. The file:// protocol isn't supported with XMLHttpRequest. There's tons of ways to set up a webserver, but a quick an easy way is to use this chrome extension..
Then edit the url of your file to be relative to your js file. (The same way you'd include css in html).

You could also use the Fetch API like someone else commented, but some browsers (mainly Internet Explorer) don't support it, so keep that in mind.

var rawFile = new XMLHttpRequest();
  rawFile.addEventListener("load", reqListener);
  rawFile.open("GET", "/csvFileName.csv", true);
  rawFile.send();
  function reqListener(){
    var csvText = this.responseText;
    console.log(csvText);
  }```

Body:
In the following code:

  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:


问:
Finding the actual source for an error message from a template instantiation / type deduction
I am getting some error in a templated function of some 3rd party library that I am trying to build.

MSVC points to the function and told me that I am doing something wrong for a specific call. How can I know at which call exactly the error happens?

If it matters, this is the function:

```<code>template <typename T>
std::string ToString(T number) {
    std::ostringstream ss;
    ss << std::setprecision(NUM_TO_STRING_PRECISION);
    ss << number;
    return ss.str();
}
</code>```

The error is:

Error C2088   '<<': illegal for class

答:
How can I know at which call exactly the error happens?

Not really with visual-studio, but let's look at a simple example:

```<code>#include <vector>

struct Foo {
    Foo() = delete;
};

int main() {
    std::vector<Foo> vfoo(15);
    (void)vfoo;
}
</code>```

GCC g++ outputs these error messages:

```<code>In file included from /usr/local/include/c++/7.1.0/vector:63:0,
                 from main.cpp:1:
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h: In instantiation of 'static _ForwardIterator std::__uninitialized_default_n_1<true>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Foo*; _Size = long unsigned int]':
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:583:20:   required from '_ForwardIterator std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Foo*; _Size = long unsigned int]'
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:645:44:   required from '_ForwardIterator std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with _ForwardIterator = Foo*; _Size = long unsigned int; _Tp = Foo]'
/usr/local/include/c++/7.1.0/bits/stl_vector.h:1347:36:   required from 'void std::vector<_Tp, _Alloc>::_M_default_initialize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Foo; _Alloc = std::allocator<Foo>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/usr/local/include/c++/7.1.0/bits/stl_vector.h:285:30:   required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const allocator_type&) [with _Tp = Foo; _Alloc = std::allocator<Foo>; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Foo>]'
main.cpp:9:29:   required from here
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:548:37: error: use of deleted function 'Foo::Foo()'
    return std::fill_n(__first, __n, _ValueType());
                                     ^~~~~~~~~~~~
main.cpp:4:5: note: declared here
     Foo() = delete;
     ^~~
</code>```

IIRC it's very similar in visual studio. Just open the raw output tab, and go to the very last note, which probably contains the real source of the error.

MSVC results with rextester. Again the very last notes for source_file.cpp point to the real source of the error.

Body:
I am getting some error in a templated function of some 3rd party library that I am trying to build.

MSVC points to the function and told me that I am doing something wrong for a specific call. How can I know at which call exactly the error happens?

If it matters, this is the function:

template <typename T>
std::string ToString(T number) {
    std::ostringstream ss;
    ss << std::setprecision(NUM_TO_STRING_PRECISION);
    ss << number;
    return ss.str();
}

The error is:

Error C2088   '<<': illegal for class

Body:
How can I know at which call exactly the error happens?

Not really with visual-studio, but let's look at a simple example:

#include <vector>

struct Foo {
    Foo() = delete;
};

int main() {
    std::vector<Foo> vfoo(15);
    (void)vfoo;
}

GCC g++ outputs these error messages:

In file included from /usr/local/include/c++/7.1.0/vector:63:0,
                 from main.cpp:1:
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h: In instantiation of 'static _ForwardIterator std::__uninitialized_default_n_1<true>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Foo*; _Size = long unsigned int]':
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:583:20:   required from '_ForwardIterator std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Foo*; _Size = long unsigned int]'
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:645:44:   required from '_ForwardIterator std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with _ForwardIterator = Foo*; _Size = long unsigned int; _Tp = Foo]'
/usr/local/include/c++/7.1.0/bits/stl_vector.h:1347:36:   required from 'void std::vector<_Tp, _Alloc>::_M_default_initialize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Foo; _Alloc = std::allocator<Foo>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/usr/local/include/c++/7.1.0/bits/stl_vector.h:285:30:   required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const allocator_type&) [with _Tp = Foo; _Alloc = std::allocator<Foo>; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Foo>]'
main.cpp:9:29:   required from here
/usr/local/include/c++/7.1.0/bits/stl_uninitialized.h:548:37: error: use of deleted function 'Foo::Foo()'
    return std::fill_n(__first, __n, _ValueType());
                                     ^~~~~~~~~~~~
main.cpp:4:5: note: declared here
     Foo() = delete;
     ^~~

IIRC it's very similar in visual studio. Just open the raw output tab, and go to the very last note, which probably contains the real source of the error.

MSVC results with rextester. Again the very last notes for source_file.cpp point to the real source of the error.


问:
Avoiding type conflicts with dplyr::case_when
I am trying to use dplyr::case_when within dplyr::mutate to create a new variable where I set some values to missing and recode other values simultaneously.

However, if I try to set values to NA, I get an error saying that we cannot create the variable new because NAs are logical:

Error in mutate_impl(.data, dots) :

    Evaluation error: must be type double, not logical.

Is there a way to set values to NA in a non-logical vector in a data frame using this?

```<code>library(dplyr)

# Create data
df <- data.frame(old = 1:3)

# Create new variable
df <- df %>% dplyr::mutate(new = dplyr::case_when(old == 1 ~ 5,
                                                  old == 2 ~ NA,
                                                  TRUE ~ old))

# Desired output
c(5, NA, 3)
</code>```

答:
Try this ? </p>

```<code>df %>% dplyr::mutate(new = dplyr::case_when(.$old == 1 ~ 5,
                                                  .$old == 2 ~ NA_real_,
                                                  TRUE~.$old))

> df
  old new
1   1   5
2   2  NA
3   3   3
</code>```

Body:
I am trying to use dplyr::case_when within dplyr::mutate to create a new variable where I set some values to missing and recode other values simultaneously.

However, if I try to set values to NA, I get an error saying that we cannot create the variable new because NAs are logical:

Error in mutate_impl(.data, dots) :

    Evaluation error: must be type double, not logical.

Is there a way to set values to NA in a non-logical vector in a data frame using this?

library(dplyr)

# Create data
df <- data.frame(old = 1:3)

# Create new variable
df <- df %>% dplyr::mutate(new = dplyr::case_when(old == 1 ~ 5,
                                                  old == 2 ~ NA,
                                                  TRUE ~ old))

# Desired output
c(5, NA, 3)

Body:
Try this ?

df %>% dplyr::mutate(new = dplyr::case_when(.$old == 1 ~ 5,
                                                  .$old == 2 ~ NA_real_,
                                                  TRUE~.$old))

> df
  old new
1   1   5
2   2  NA
3   3   3


问:
How to use scatter chart with complex data?
I trying to implement scatter chart by example.

In example we can see creating dimension:

```<code>runDimension = ndx.dimension(function(d) {return [+d.Expt, +d.Run]; });
</code>```

Example's data:

```<code>Expt Run Speed
1    1   850
1    2   740
1    3   900
</code>```

I want to use same chart, but I have my data in next format:

```<code>[
 {
  "Timestamp":"2016-12-15T17:29:53Z",
  "idgame":"euro",
  "users":{
    "Jo": {
      "energy":200,
      "jump_height":0.5
     },
    "Bob": {
      "energy":220,
      "jump_height":0.35
     }
  }
 },
 {
  "Timestamp":"2016-12-15T17:29:55Z",
  "idgame":"euro",
  "users":{
    "Jo": {
      "energy":120,
      "jump_height":0.15
     },
    "Bob": {
      "energy":240,
      "jump_height":0.75
     }
  }
 }
]
</code>```

I need to build next chart, where x-axis is timestamp and y-axis is jump_height:

My data is allready in crossfilter, so I can't change it.
How can I create good dimension with current format?

答:
I'm still not convinced this is worth the effort, versus biting the bullet and flattening your data and fixing up the other charts. If your data isn't flat you will be fighting crossfilter and dc.js every step of the way.

That said, as usual, it's possible!

We can't use the series chart, because that requires all the data to be present in one group. But since you want to produce multiple symbols from each row of data, an ordinary crossfilter group can't produce the data you need.

Maybe we could use a fake group, but that would be complicated. Instead, let's produce a dimension and group for each user, and then sew them together using a composite chart.

First, we need to parse those timestamps:

```<code>data.forEach(function(d) {
  d.Timestamp = new Date(d.Timestamp);
});
</code>```

Next, we'll retrieve a list of all users, by pulling the user keys from each event (timestamp), concatenating them, and then using a d3.set to unique them:

```<code>// retrieve all users from all events
var users = data.reduce(function(p, event) {
  return p.concat(Object.keys(event.users));
}, []);
users = d3.set(users).values();
</code>```

In the rest of the code, we'll assume there are the same users for each event. It's possible for them to be different, but it adds extra complexity, and this answer is complicated enough. Just ping me me if you need that feature!

We'll create the chart, crossfilter, and a scale which will assign symbols to users:

```<code>var chart = dc.compositeChart("#test");
var ndx = crossfilter(data);
var symbolScale = d3.scale.ordinal().range(d3.svg.symbolTypes);
</code>```

Now we can create the composite chart. (We'll add the scatter subcharts in the next step.)

```<code>chart
  .width(768)
  .height(480)
  .x(d3.time.scale())
  .xUnits(d3.time.seconds)
  .elasticX(true)
  .elasticY(true)
  .brushOn(false)
  .clipPadding(10)
  .shareTitle(false) // allow default scatter title to work
  .shareColors(true) // but use different colors for subcharts
  .legend(dc.legend().x(350).y(350).itemHeight(13)
          .gap(5).horizontal(1).legendWidth(140).itemWidth(70));
</code>```

We set up the X axis with a time scale, with a resolution of seconds. Both axes have elastic. We need to share colors so that each subchart will be assigned its own color. (The legend is perhaps overspecified - I copied this from another example.)

Finally we get to the meat of it. For each user, we'll create a subchart, and we'll tell the composite chart to compose all of them:

```<code>chart.compose(users.map(function(user) {
  var userDimension = ndx.dimension(function(d) {
    return [d.Timestamp, d.users[user].jump_height];
  })
  var jumpGroup = userDimension.group();
  console.log(user, jumpGroup.all());
  var scatter = dc.scatterPlot(chart)
    .symbol(symbolScale(user))
    .dimension(userDimension)
    .group(jumpGroup)
    .colorAccessor(function() { return user; })
    .symbolSize(8)
    .highlightedSize(10);
  return scatter;
}))
</code>```

We're creating a new dimension for each chart. This is because the dc.js scatter plot expects the keys to include both X and Y coordinates, and we can only access the Y coordinate (jump_height) once we know the user. Once we get past that, the group is simple.

The chart will assign the symbol and color based on the user key. These both work the same; an ordinal scale will assign a new value from the range for each new value it encounters in the domain. The only difference is that we're using the default color scale, whereas we had to specify our own symbol scale.

Here's a fiddle: https://jsfiddle.net/gordonwoodhull/3m4mv3xf/19/

Body:
I trying to implement scatter chart by example.

In example we can see creating dimension:

runDimension = ndx.dimension(function(d) {return [+d.Expt, +d.Run]; });

Example's data:

Expt Run Speed
1    1   850
1    2   740
1    3   900

I want to use same chart, but I have my data in next format:

[
 {
  "Timestamp":"2016-12-15T17:29:53Z",
  "idgame":"euro",
  "users":{
    "Jo": {
      "energy":200,
      "jump_height":0.5
     },
    "Bob": {
      "energy":220,
      "jump_height":0.35
     }
  }
 },
 {
  "Timestamp":"2016-12-15T17:29:55Z",
  "idgame":"euro",
  "users":{
    "Jo": {
      "energy":120,
      "jump_height":0.15
     },
    "Bob": {
      "energy":240,
      "jump_height":0.75
     }
  }
 }
]

I need to build next chart, where x-axis is timestamp and y-axis is jump_height:

My data is allready in crossfilter, so I can't change it.
How can I create good dimension with current format?

Body:
I'm still not convinced this is worth the effort, versus biting the bullet and flattening your data and fixing up the other charts. If your data isn't flat you will be fighting crossfilter and dc.js every step of the way.

That said, as usual, it's possible!

We can't use the series chart, because that requires all the data to be present in one group. But since you want to produce multiple symbols from each row of data, an ordinary crossfilter group can't produce the data you need.

Maybe we could use a fake group, but that would be complicated. Instead, let's produce a dimension and group for each user, and then sew them together using a composite chart.

First, we need to parse those timestamps:

data.forEach(function(d) {
  d.Timestamp = new Date(d.Timestamp);
});

Next, we'll retrieve a list of all users, by pulling the user keys from each event (timestamp), concatenating them, and then using a d3.set to unique them:

// retrieve all users from all events
var users = data.reduce(function(p, event) {
  return p.concat(Object.keys(event.users));
}, []);
users = d3.set(users).values();

In the rest of the code, we'll assume there are the same users for each event. It's possible for them to be different, but it adds extra complexity, and this answer is complicated enough. Just ping me me if you need that feature!

We'll create the chart, crossfilter, and a scale which will assign symbols to users:

var chart = dc.compositeChart("#test");
var ndx = crossfilter(data);
var symbolScale = d3.scale.ordinal().range(d3.svg.symbolTypes);

Now we can create the composite chart. (We'll add the scatter subcharts in the next step.)

chart
  .width(768)
  .height(480)
  .x(d3.time.scale())
  .xUnits(d3.time.seconds)
  .elasticX(true)
  .elasticY(true)
  .brushOn(false)
  .clipPadding(10)
  .shareTitle(false) // allow default scatter title to work
  .shareColors(true) // but use different colors for subcharts
  .legend(dc.legend().x(350).y(350).itemHeight(13)
          .gap(5).horizontal(1).legendWidth(140).itemWidth(70));

We set up the X axis with a time scale, with a resolution of seconds. Both axes have elastic. We need to share colors so that each subchart will be assigned its own color. (The legend is perhaps overspecified - I copied this from another example.)

Finally we get to the meat of it. For each user, we'll create a subchart, and we'll tell the composite chart to compose all of them:

chart.compose(users.map(function(user) {
  var userDimension = ndx.dimension(function(d) {
    return [d.Timestamp, d.users[user].jump_height];
  })
  var jumpGroup = userDimension.group();
  console.log(user, jumpGroup.all());
  var scatter = dc.scatterPlot(chart)
    .symbol(symbolScale(user))
    .dimension(userDimension)
    .group(jumpGroup)
    .colorAccessor(function() { return user; })
    .symbolSize(8)
    .highlightedSize(10);
  return scatter;
}))

We're creating a new dimension for each chart. This is because the dc.js scatter plot expects the keys to include both X and Y coordinates, and we can only access the Y coordinate (jump_height) once we know the user. Once we get past that, the group is simple.

The chart will assign the symbol and color based on the user key. These both work the same; an ordinal scale will assign a new value from the range for each new value it encounters in the domain. The only difference is that we're using the default color scale, whereas we had to specify our own symbol scale.

Here's a fiddle: https://jsfiddle.net/gordonwoodhull/3m4mv3xf/19/


问:
How to write (<*>) using (=<<) in Haskell
Could someone explain why the following representation of (<*>)  with (=<<) works:

```<code>f <*> a = (\f' -> return . f' =<< a) =<< f
</code>```

答:
The use of names f and a is extremely confusing, because names are suggestive ("f" evokes "function", but isn't). Primed names can be confusing as well. Parens shouldn't be omitted while you're still learning and are unsure about the default operator precedences. Same goes for do's optional curly braces and semicolons.

The two names should have been  fs and as. Changing them could be part of the expected answer. Thus you have

```<code>fs <*> as = (\f -> (return . f) =<< as) =<< fs
          = fs >>= (\f ->
            as >>= (return . f))                -- by definition of >>= and =<<
          = fs >>= (\f ->
            as >>= (\a -> (return . f) a))      -- by "eta expansion"
          = fs >>= (\f ->
            as >>= (\a -> return (f a)))        -- by `(.)` reduction
          = do { f <- fs
               ; a <- as
               ; return (f a) }                 -- by `do` syntax definition
</code>```

because that's how the do syntax is defined. And that is the definition of ap, which <*> is supposed to be a stand-in for.

It goes without saying that this works only for a type which is not just an Applicative, but a Monad as well.

With monad comprehensions, the last one is written

```<code>          = [f a | f <- fs, a <- as]
</code>```

which is pretty clear in itself.

Body:
Could someone explain why the following representation of (<*>)  with (=<<) works:

f <*> a = (\f' -> return . f' =<< a) =<< f

Body:
The use of names f and a is extremely confusing, because names are suggestive ("f" evokes "function", but isn't). Primed names can be confusing as well. Parens shouldn't be omitted while you're still learning and are unsure about the default operator precedences. Same goes for do's optional curly braces and semicolons.

The two names should have been  fs and as. Changing them could be part of the expected answer. Thus you have

fs <*> as = (\f -> (return . f) =<< as) =<< fs
          = fs >>= (\f ->
            as >>= (return . f))                -- by definition of >>= and =<<
          = fs >>= (\f ->
            as >>= (\a -> (return . f) a))      -- by "eta expansion"
          = fs >>= (\f ->
            as >>= (\a -> return (f a)))        -- by `(.)` reduction
          = do { f <- fs
               ; a <- as
               ; return (f a) }                 -- by `do` syntax definition

because that's how the do syntax is defined. And that is the definition of ap, which <*> is supposed to be a stand-in for.

It goes without saying that this works only for a type which is not just an Applicative, but a Monad as well.

With monad comprehensions, the last one is written

          = [f a | f <- fs, a <- as]

which is pretty clear in itself.


问:
what is PAT (Pre Acceptance Testing)?
What is exactly PAT, When we will do the pre acceptance testing?</p>

答:
There's no standardised meaning for the term - often it depends on your process-  be it Agile or Extreme Programming etc.

Generally however, there are a number of tests done by developers or testing in a developer test environment.  This can be unit tests, developer tests, sanity regression tests, performance tests - ie tests that the QA team wants done before they'll even look at it.  At a bare minimum, it might be just testing that the software builds (although it's frightening how often I've had a developer fail to even check this).

ContentLicense: CC BY-SA 2.5

Title: what is PAT (Pre Acceptance Testing)?


问:
jquery stomp websockets server reconnection reinitialization
I have a websocket app that connects to my Java backend via stomp.js file.

```<code>function connect() {

            var socket = new SockJS('<?php echo $rootbasename;?>wsconnect');
            stompClient = Stomp.over(socket);
            stompClient.debug = null;
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                console.log('/queue/messages/' + widgetId + "/" + $.cookie(cookiename));
                stompClient.subscribe('/queue/messages/' + widgetId + "/" + $.cookie(cookiename), function (result) {
                    //code here

                }, {userToken: $.cookie(cookiename), widgetId: widgetId});

                stompClient.subscribe('/queue/makereadresult/' + widgetId + '/' + $.cookie(cookiename), function (result) {

});
</code>```

But, what if my java backend server will reboot? I want customers not to notice any change. Is there a way to auto-reconnect on connection lost? Or any way to make it smooth for clients?

答:
When you are connecting you can pass in error callback. In there you could have reconnect logic.
For example stomp has this method

```<code>client.connect(login, passcode, connectCallback, errorCallback);
</code>```

and in errorCallback just call connectCallback.

Body:
I have a websocket app that connects to my Java backend via stomp.js file.

function connect() {

            var socket = new SockJS('<?php echo $rootbasename;?>wsconnect');
            stompClient = Stomp.over(socket);
            stompClient.debug = null;
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                console.log('/queue/messages/' + widgetId + "/" + $.cookie(cookiename));
                stompClient.subscribe('/queue/messages/' + widgetId + "/" + $.cookie(cookiename), function (result) {
                    //code here

                }, {userToken: $.cookie(cookiename), widgetId: widgetId});

                stompClient.subscribe('/queue/makereadresult/' + widgetId + '/' + $.cookie(cookiename), function (result) {

});

But, what if my java backend server will reboot? I want customers not to notice any change. Is there a way to auto-reconnect on connection lost? Or any way to make it smooth for clients?

Body:
When you are connecting you can pass in error callback. In there you could have reconnect logic.
For example stomp has this method

client.connect(login, passcode, connectCallback, errorCallback);

and in errorCallback just call connectCallback.


问:
Unable to resolve this dependecy for curl in solaris 10
i am trying to install curl on solaris 10.

I have installed the curl packages with other dependencies as

```<code>application SMCcurl                          curl
application SMClgcc346                       libgcc
application SMClibidn                        libidn
application SMCliconv                        libiconv
application SMClintl                         libintl
application SMClssh2                         libssh2
application SMCossl                          openssl
application SMCzlib                          zlib
</code>```

When I tried to run the curl i am getting error as

```<code>/usr/local/bin # ./curl --version
ld.so.1: curl: fatal: libidn.so.11: version `LIBIDN_1.0' not found (required by file /usr/local/lib/libcurl.so.4)
ld.so.1: curl: fatal: libidn.so.11: open failed: No such file or directory
Killed
</code>```

Searched for its solution, but no luck.

Ouput of the ldd curl command is

```<code>        libcurl.so.4 =>  /usr/local/lib/libcurl.so.4
        libidn.so.11 =>  /usr/local/lib/libidn.so.11
        libintl.so.8 =>  /usr/local/lib/libintl.so.8
        libsec.so.1 =>   /usr/lib/libsec.so.1
        libc.so.1 =>     /usr/lib/libc.so.1
        libiconv.so.2 =>         /usr/local/lib/libiconv.so.2
        libnsl.so.1 =>   /usr/lib/libnsl.so.1
        libdl.so.1 =>    /usr/lib/libdl.so.1
        libssh2.so.1 =>  /usr/local/lib/libssh2.so.1
        libssl.so.1.0.0 =>       /usr/local/ssl/lib/libssl.so.1.0.0
        libcrypto.so.1.0.0 =>    /usr/local/ssl/lib/libcrypto.so.1.0.0
        libsocket.so.1 =>        /usr/lib/libsocket.so.1
        librt.so.1 =>    /usr/lib/librt.so.1
        libz.so =>       /usr/local/lib/libz.so
        libgcc_s.so.1 =>         /usr/local/lib/libgcc_s.so.1
        libidn.so.11 (LIBIDN_1.0) =>     (version not found)
        libavl.so.1 =>   /lib/libavl.so.1
        libmp.so.2 =>    /lib/libmp.so.2
        libmd.so.1 =>    /lib/libmd.so.1
        libscf.so.1 =>   /lib/libscf.so.1
        libaio.so.1 =>   /lib/libaio.so.1
        libdoor.so.1 =>  /lib/libdoor.so.1
        libuutil.so.1 =>         /lib/libuutil.so.1
        libgen.so.1 =>   /lib/libgen.so.1
        libm.so.2 =>     /lib/libm.so.2
        /platform/SUNW,Netra-440/lib/libc_psr.so.1
        /platform/SUNW,Netra-440/lib/libmd_psr.so.1
</code>```

Can somebody please tell me how can resolve these dependency?

答:
Yo have to install "libidn-1.11-sol10-sparc-local"

http://ftp.ntua.gr/mirror/sun-freeware/sparc/10/

Body:
i am trying to install curl on solaris 10.

I have installed the curl packages with other dependencies as

application SMCcurl                          curl
application SMClgcc346                       libgcc
application SMClibidn                        libidn
application SMCliconv                        libiconv
application SMClintl                         libintl
application SMClssh2                         libssh2
application SMCossl                          openssl
application SMCzlib                          zlib

When I tried to run the curl i am getting error as

/usr/local/bin # ./curl --version
ld.so.1: curl: fatal: libidn.so.11: version `LIBIDN_1.0' not found (required by file /usr/local/lib/libcurl.so.4)
ld.so.1: curl: fatal: libidn.so.11: open failed: No such file or directory
Killed

Searched for its solution, but no luck.

Ouput of the ldd curl command is

        libcurl.so.4 =>  /usr/local/lib/libcurl.so.4
        libidn.so.11 =>  /usr/local/lib/libidn.so.11
        libintl.so.8 =>  /usr/local/lib/libintl.so.8
        libsec.so.1 =>   /usr/lib/libsec.so.1
        libc.so.1 =>     /usr/lib/libc.so.1
        libiconv.so.2 =>         /usr/local/lib/libiconv.so.2
        libnsl.so.1 =>   /usr/lib/libnsl.so.1
        libdl.so.1 =>    /usr/lib/libdl.so.1
        libssh2.so.1 =>  /usr/local/lib/libssh2.so.1
        libssl.so.1.0.0 =>       /usr/local/ssl/lib/libssl.so.1.0.0
        libcrypto.so.1.0.0 =>    /usr/local/ssl/lib/libcrypto.so.1.0.0
        libsocket.so.1 =>        /usr/lib/libsocket.so.1
        librt.so.1 =>    /usr/lib/librt.so.1
        libz.so =>       /usr/local/lib/libz.so
        libgcc_s.so.1 =>         /usr/local/lib/libgcc_s.so.1
        libidn.so.11 (LIBIDN_1.0) =>     (version not found)
        libavl.so.1 =>   /lib/libavl.so.1
        libmp.so.2 =>    /lib/libmp.so.2
        libmd.so.1 =>    /lib/libmd.so.1
        libscf.so.1 =>   /lib/libscf.so.1
        libaio.so.1 =>   /lib/libaio.so.1
        libdoor.so.1 =>  /lib/libdoor.so.1
        libuutil.so.1 =>         /lib/libuutil.so.1
        libgen.so.1 =>   /lib/libgen.so.1
        libm.so.2 =>     /lib/libm.so.2
        /platform/SUNW,Netra-440/lib/libc_psr.so.1
        /platform/SUNW,Netra-440/lib/libmd_psr.so.1

Can somebody please tell me how can resolve these dependency?


问:
Splitting a string in Make rule
I am trying to split a string with colon separated values in Make target.

When i try to split the string in a target recipe using for loop, eval, shell i get the blank values. Where as when i do use the shell command to split the string outside the target result is positive.

Can any one help me fixing the target recipe.

Below is the snippet.

```<code>notebooks=new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd
j=new:e7e45d89-94cc-4783-86c5-2236d9904a24
f1=$(shell echo $j | cut -d: -f 1)
test1:
    @for i in $(notebooks); \
    do \
        $(eval f=$(shell echo $i | cut -d: -f 1))  \
        $(eval fid=$(shell echo $i | cut -d: -f 2)) \
        echo $(f) $(fid) $(f1) ;\
    done
</code>```

Output is

```<code>new
new
</code>```

Whereas desired output is

```<code>new e7e45d89-94cc-4783-86c5-2236d9904a24 new
test 2af1d689-98c3-48f2-984d-2ea21c5135dd new
</code>```

答:
This is the most common confusion about makefiles it seems: the distinction between the recipe which is written in shell syntax, and make constructs.

The way make works is that ALL make constructs (variables and functions) in the recipe are first evaluated by make, then the resulting expanded string is passed to the shell and the shell executes it.

In your example you're trying to have a shell script loop that contains make variables and functions: that cannot work (how can the shell, which is a new process that make forked, ask make to re-expand some value based on a shell variable?)

When make wants to run this recipe:

```<code>@for i in $(notebooks); \
do \
    $(eval f=$(shell echo $i | cut -d: -f 1))  \
    $(eval fid=$(shell echo $i | cut -d: -f 2)) \
    echo $(f) $(fid) $(f1) ;\
done
</code>```

it first expands all the makefile variables and functions.  Remember it's just expanding a string here, it's NOT running a shell so no shell commands are invoked.  The first two lines expand like this:

```<code>@for i in new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd; \
do \
</code>```

Then the next line is expanded:

```<code>    $(eval f=$(shell echo $i | cut -d: -f 1))  \
</code>```

Here $i is just a make variable i, which you've never set, so it's empty.  So make runs this shell command:

```<code>echo | cut -d: -f 1
</code>```

which yields nothing, so $(eval f=) is expanded and the make variable f is set to the empty string.

Similarly this line:

```<code>    $(eval fid=$(shell echo $i | cut -d: -f 2)) \
</code>```

sets fid to the empty string.

Then this line is expanded

```<code>    echo $(f) $(fid) $(f1) ;\
</code>```

which expands to:

```<code>    echo   new ;\
</code>```

because only f1 has any value here.  Finally the last line:

```<code>done
</code>```

So, after all that expansion, the string that is passed to the shell to be run is:

```<code>@for i in new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd; \
do \
    echo   new; \
done
</code>```

There's absolutely no point to using $(shell ...) inside the recipe; you're already in a shell so why do you need another one?  Similarly, you don't need eval to set make variables, you need to use shell variables.

Write your recipe like this:

```<code>@for i in $(notebooks); \
do \
    f=`echo $$i | cut -d: -f 1`;  \
    fid=`echo $$i | cut -d: -f 2`; \
    echo $$f $$fid $(f1) ;\
done
</code>```

Title: Splitting a string in Make rule

Body:
I am trying to split a string with colon separated values in Make target.

When i try to split the string in a target recipe using for loop, eval, shell i get the blank values. Where as when i do use the shell command to split the string outside the target result is positive.

Can any one help me fixing the target recipe.

Below is the snippet.

notebooks=new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd
j=new:e7e45d89-94cc-4783-86c5-2236d9904a24
f1=$(shell echo $j | cut -d: -f 1)
test1:
    @for i in $(notebooks); \
    do \
        $(eval f=$(shell echo $i | cut -d: -f 1))  \
        $(eval fid=$(shell echo $i | cut -d: -f 2)) \
        echo $(f) $(fid) $(f1) ;\
    done

Output is

new
new

Whereas desired output is

new e7e45d89-94cc-4783-86c5-2236d9904a24 new
test 2af1d689-98c3-48f2-984d-2ea21c5135dd new

Body:
This is the most common confusion about makefiles it seems: the distinction between the recipe which is written in shell syntax, and make constructs.

The way make works is that ALL make constructs (variables and functions) in the recipe are first evaluated by make, then the resulting expanded string is passed to the shell and the shell executes it.

In your example you're trying to have a shell script loop that contains make variables and functions: that cannot work (how can the shell, which is a new process that make forked, ask make to re-expand some value based on a shell variable?)

When make wants to run this recipe:

@for i in $(notebooks); \
do \
    $(eval f=$(shell echo $i | cut -d: -f 1))  \
    $(eval fid=$(shell echo $i | cut -d: -f 2)) \
    echo $(f) $(fid) $(f1) ;\
done

it first expands all the makefile variables and functions.  Remember it's just expanding a string here, it's NOT running a shell so no shell commands are invoked.  The first two lines expand like this:

@for i in new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd; \
do \

Then the next line is expanded:

    $(eval f=$(shell echo $i | cut -d: -f 1))  \

Here $i is just a make variable i, which you've never set, so it's empty.  So make runs this shell command:

echo | cut -d: -f 1

which yields nothing, so $(eval f=) is expanded and the make variable f is set to the empty string.

Similarly this line:

    $(eval fid=$(shell echo $i | cut -d: -f 2)) \

sets fid to the empty string.

Then this line is expanded

    echo $(f) $(fid) $(f1) ;\

which expands to:

    echo   new ;\

because only f1 has any value here.  Finally the last line:

done

So, after all that expansion, the string that is passed to the shell to be run is:

@for i in new:e7e45d89-94cc-4783-86c5-2236d9904a24 test:2af1d689-98c3-48f2-984d-2ea21c5135dd; \
do \
    echo   new; \
done

There's absolutely no point to using $(shell ...) inside the recipe; you're already in a shell so why do you need another one?  Similarly, you don't need eval to set make variables, you need to use shell variables.

Write your recipe like this:

@for i in $(notebooks); \
do \
    f=`echo $$i | cut -d: -f 1`;  \
    fid=`echo $$i | cut -d: -f 2`; \
    echo $$f $$fid $(f1) ;\
done


问:
What is the correct isolation level for Order header - Order lines transactions?
Lets say we have a usual situation with Order_Header and Order_LineItems tables.
Also, lets say we have transactions for creating, updating and selecting Orders. Like:

Create:

```<code>BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show update dependant on select
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE OrderDate > '1-1-2017'

UPDATE Order_Headers
SET SomeValue = @SomeVar
WHERE Id = @Id

COMMIT

END TRANSACTION
</code>```

On the other hand, we have transaction for getting Orders base on some criteria, for simplicity, lets say last 10:

```<code>SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC
</code>```

Could someone please say what would be correct isolation level for each transaction and shortly explain why?

[UPDATE]

I want to make sure that no other session can insert rows matching
WHERE OrderDate > '1-1-2017'

I also want to make sure that second transaction (pure selecting orders) never pick up rows that are not fully 'done' in first transaction. Meaning those that are created in transactions INSERT part but not yet updated in UPDATE part. (i guess that is covered by READ COMMITED being default, right?)

[UPDATE 2]

i want

```<code>WHERE OrderDate > '1-1-2017'
</code>```

to be the value at the begining of the transaction.

答:
First make sure your database has enabled snapshot isolation

```<code>ALTER DATABASE YOURDB
SET ALLOW_SNAPSHOT_ISOLATION ON
</code>```

First transaction requires SNAPSHOT isolation

```<code>SET TRANSACTION ISOLATION LEVEL SNAPSHOT
</code>```

Second Transaction requires READ COMMITTED isolation

```<code> SET TRANSACTION ISOLATION LEVEL READ COMMITTED
</code>```

Body:
Lets say we have a usual situation with Order_Header and Order_LineItems tables.
Also, lets say we have transactions for creating, updating and selecting Orders. Like:

Create:

BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show update dependant on select
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE OrderDate > '1-1-2017'

UPDATE Order_Headers
SET SomeValue = @SomeVar
WHERE Id = @Id

COMMIT

END TRANSACTION

On the other hand, we have transaction for getting Orders base on some criteria, for simplicity, lets say last 10:

SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC

Could someone please say what would be correct isolation level for each transaction and shortly explain why?

[UPDATE]

I want to make sure that no other session can insert rows matching
WHERE OrderDate > '1-1-2017'

I also want to make sure that second transaction (pure selecting orders) never pick up rows that are not fully 'done' in first transaction. Meaning those that are created in transactions INSERT part but not yet updated in UPDATE part. (i guess that is covered by READ COMMITED being default, right?)

[UPDATE 2]

i want

WHERE OrderDate > '1-1-2017'

to be the value at the begining of the transaction.

Body:
First make sure your database has enabled snapshot isolation

ALTER DATABASE YOURDB
SET ALLOW_SNAPSHOT_ISOLATION ON

First transaction requires SNAPSHOT isolation

SET TRANSACTION ISOLATION LEVEL SNAPSHOT

Second Transaction requires READ COMMITTED isolation

 SET TRANSACTION ISOLATION LEVEL READ COMMITTED


问:
Disable color and paging for mercurial
New versions of mercurial will apply colors to the output of most commands and will pipe commands with long output to a pager. How do I restore the old behavior to not color output and never use a pager?</p>

答:
Add the following to your .hgrc:</p>

```<code>[ui]
color = never
paginate = never
</code>```

Title: Disable color and paging for mercurial

Body:
Add the following to your .hgrc:

[ui]
color = never
paginate = never


问:
How to apply softmax on an array/vector with huge positive and negative values in TensorFlow?
I train a convolutional neural network (CNN) with MNIST data set in TensorFlow. I calculate the accuracy for each image from the MNIST test images and looking for the values of the ten output-nodes. I use the following line of code to get it (see all code here: How to get the value from each output-node during eval MNIST testdata in TensorFlow?):

```<code>pred=prediction.eval(feed_dict={ x: testSet[0], y: testSet[1]})
</code>```

The output of this line of code is for example this:

```<code>[[ -13423.92773438 -27312.79296875 20629.26367188 42987.953125
-34635.8203125 3714.84619141 -60946.6328125 106193.8828125
-20936.08789062 3940.52636719]]
</code>```

When I try to apply the tf.nn.softmax() function at this vector/array with the following code:

```<code>pred_softmax = tf.nn.softmax(pred)
print(pred_softmax_new.eval())
</code>```

I get for example this output:

```<code>[[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]
</code>```

But I am looking for results like this:

```<code>[[ 0.001 0.207 0.001 0.001 0.002 0.001 0.001 0.9723 0.001 0.001]]
</code>```

I test this code:

```<code>test_a = tf.nn.softmax([31.0,23.0])
print(test_a.eval())
</code>```

get this output:

```<code>[ 9.99664664e-01 3.35350138e-04]
</code>```

But if I increase the value like:

```<code>test_a = tf.nn.softmax([45631.0,65423.0])
</code>```

I get this output:

```<code>[ 0. 1.]
</code>```

So my question is there a way to get good readable outputs for the ten output-nodes like for example this:

```<code>[[ 0.001 0.207 0.001 0.001 0.002 0.001 0.001 0.9723 0.001 0.001]]
</code>```

答: This seems like an issue of numerical stability mentioned here. I don't think that the answer mentioned in the link will help in your case though, as the differences between your numbers are extremely large. Basically, it seems that your model predict the value of 7 with probability 0.999999999....</p>

Body:
I train a convolutional neural network (CNN) with MNIST data set in TensorFlow. I calculate the accuracy for each image from the MNIST test images and looking for the values of the ten output-nodes. I use the following line of code to get it (see all code here: How to get the value from each output-node during eval MNIST testdata in TensorFlow?):

pred=prediction.eval(feed_dict={ x: testSet[0], y: testSet[1]})

The output of this line of code is for example this:

[[ -13423.92773438 -27312.79296875 20629.26367188 42987.953125
-34635.8203125 3714.84619141 -60946.6328125 106193.8828125
-20936.08789062 3940.52636719]]

When I try to apply the tf.nn.softmax() function at this vector/array with the following code:

pred_softmax = tf.nn.softmax(pred)
print(pred_softmax_new.eval())

I get for example this output:

[[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]

But I am looking for results like this:

[[ 0.001 0.207 0.001 0.001 0.002 0.001 0.001 0.9723 0.001 0.001]]

I test this code:

test_a = tf.nn.softmax([31.0,23.0])
print(test_a.eval())

get this output:

[ 9.99664664e-01 3.35350138e-04]

But if I increase the value like:

test_a = tf.nn.softmax([45631.0,65423.0])

I get this output:

[ 0. 1.]

So my question is there a way to get good readable outputs for the ten output-nodes like for example this:

[[ 0.001 0.207 0.001 0.001 0.002 0.001 0.001 0.9723 0.001 0.001]]


问:
I keep getting a 404 error when I try to add a background image to a div in jQuery
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

```<code>function appendToDom(poster) {
    var aPoster = $('<div>');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);
</code>```

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.

答: The browser doesn't understand the ~ in the file path ~/desktop/MyMovies/public/js/images/1425663956-outline.png. It only has meaning in a shell with access to your local filesystem. You need to use the URL where that image file is being served.

Body:
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

function appendToDom(poster) {
    var aPoster = $('
');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.


问:
Issues using regular expression match in the IF statement in powershell
Input File content is at the bottom. The image shows better the file format.

As you can see from my input file it comes with lots of lines that I don´t need, so I´m trying to tell Powershell to read the content when line matches this pattern (see below). But it´s returning False and not doing what I´d like which is to copy all the content between the regex and the - sign which indicates where the block ends.

Any idea of what I´m doing wrong?

```<code>$InputFile = gc "D:\input_file.txt"
$Dest = "D:\Desktop\Final_file.txt"

#PATTERN I´M LOOKING FOR:
 0000 00XKDPMBBRAXXX00000
 1965 81PWSLKDTRUGXX00000

#REGEX I´VE CREATED BASED ON ABOVE CONTENT
$re = [regex]'(\d{4}\s\d{2}\[a-z]{12}\d{5})'

$file_line_num = 0
$mesg_line_num = 0
$Dest_count     = 0

foreach ($line in $Input_File) {
  $file_line_num = $file_line_num + 1

  # Find where message starts, any other lines are ignored
  if ($line -match $re) {

     [void]$foreach.MoveNext() # skip lines not needed

     $msg_line_num = 0

     do {
        [void]$foreach.MoveNext()
        $line = $foreach.current
        $msg_line_num = $msg_line_num + 1

        if ($msg_line_num -lt 3) {

           $header = $line.substring(7,8) + $line.substring(16, 3)
           add-content $Dest $header

        } else {
           add-content $Dest $line
        }

     } until ($line -eq "-" -or $line -eq $null)
  }
}
Exit
</code>```

```<code>text
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++
</code>```

答:
\[a-z] should be [A-Z] - the slash is not needed because it produces a literal [, also [regex] class is case-sensitive unlike the usual -match operator.

Anyway, it's possible to shorten the code (PowerShell 3.0 and newer):

```<code>$all = ([regex]'(?s)(?<=(\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2})(.*?)(?=\r?\n-\r?\n)').
    Matches((Get-Content source.txt -raw)).Value
</code>```

Or PowerShell 2.0:

```<code>$all = ([regex]'(?s)(?<=(\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2})(.*?)(?=\r?\n-\r?\n)').
    Matches([IO.File]::ReadAllText('r:\source.txt')) | Select -expand Value
</code>```

To copy including the boundary lines too change the groups in the regexp:

'(?s)(?:\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2}.*?\r?\n-\r?\n'

Body:
Input File content is at the bottom. The image shows better the file format.

As you can see from my input file it comes with lots of lines that I don´t need, so I´m trying to tell Powershell to read the content when line matches this pattern (see below). But it´s returning False and not doing what I´d like which is to copy all the content between the regex and the - sign which indicates where the block ends.

Any idea of what I´m doing wrong?

$InputFile = gc "D:\input_file.txt"
$Dest = "D:\Desktop\Final_file.txt"

#PATTERN I´M LOOKING FOR:
 0000 00XKDPMBBRAXXX00000
 1965 81PWSLKDTRUGXX00000

#REGEX I´VE CREATED BASED ON ABOVE CONTENT
$re = [regex]'(\d{4}\s\d{2}\[a-z]{12}\d{5})'

$file_line_num = 0
$mesg_line_num = 0
$Dest_count     = 0

foreach ($line in $Input_File) {
  $file_line_num = $file_line_num + 1

  # Find where message starts, any other lines are ignored
  if ($line -match $re) {

     [void]$foreach.MoveNext() # skip lines not needed

     $msg_line_num = 0

     do {
        [void]$foreach.MoveNext()
        $line = $foreach.current
        $msg_line_num = $msg_line_num + 1

        if ($msg_line_num -lt 3) {

           $header = $line.substring(7,8) + $line.substring(16, 3)
           add-content $Dest $header

        } else {
           add-content $Dest $line
        }

     } until ($line -eq "-" -or $line -eq $null)
  }
}
Exit

text
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

TEXTHERE TEXTHERE TEXTHERE
TEXTHERE
.TEXTHERE TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
0000 00XKDPMBBRAXXX00000
1965 81PWSLKDTRUGXX00000
123 99
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE//TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
TEXTHERE TEXTHERE
-
=TEXTHERE TEXTHERE
=TEXTHERE TEXTHERE

NNNN++++++++++++++++++++++++++++++++++++
+                                      +
+     -- =TEXTHERE TEXTHERE            +
+      =TEXTHERE TEXTHERE              +
+                                      +
++++++++++++++++++++++++++++++++++++++++

Body:
\[a-z] should be [A-Z] - the slash is not needed because it produces a literal [, also [regex] class is case-sensitive unlike the usual -match operator.

Anyway, it's possible to shorten the code (PowerShell 3.0 and newer):

$all = ([regex]'(?s)(?<=(\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2})(.*?)(?=\r?\n-\r?\n)').
    Matches((Get-Content source.txt -raw)).Value

Or PowerShell 2.0:

$all = ([regex]'(?s)(?<=(\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2})(.*?)(?=\r?\n-\r?\n)').
    Matches([IO.File]::ReadAllText('r:\source.txt')) | Select -expand Value

To copy including the boundary lines too change the groups in the regexp:

'(?s)(?:\d{4}\s\d{2}[a-zA-Z]{12}\d{5}\r?\n){2}.*?\r?\n-\r?\n'


问:
Spring-WS Service returns wrong Content-Type ("text/xml" instead of "application/xop+xml")
I have a Spring-WS web service (SOAP 1.2 MTOM) deployed as part of a large application (on Weblogic) returning incorrect Content-Type  (Consumer doesn't like it). The Content-Type is

```<code>Content-Type: multipart/related;boundary="----=_Part_1_4569975.1498510764791";type="text/xml";start="<soapPart>"
</code>```

I have another lean model service that I have deployed on TomEE returning it this way (Consumer likes it) -

```<code>Content-Type: Multipart/Related; boundary="----=_Part_4_1924421953.1498510734751"; type="application/xop+xml"; start-info="application/soap+xml"
</code>```

What could be wrong on the first service. Where is the configuration that ensures the right Content-Type?

Update (after 5 days) -

I have narrowed it down to the same exact WAR file returning content-type "text/xml" on Weblogic (10.3.6) and "application/xop+xml" on TomEE 1.7.4. Anyone can tell me what could be the difference between these environments? How can I make the application return the right content type on Weblogic?

答: The difference between these two environments will be the SAAJ implementation. TomEE will likely use the one in the JRE, while Weblogic has its own SAAJ implementation. Instead of using Spring-WS with SAAJ, you may want to try configuring it with Axiom.</p>

Body:
I have a Spring-WS web service (SOAP 1.2 MTOM) deployed as part of a large application (on Weblogic) returning incorrect Content-Type  (Consumer doesn't like it). The Content-Type is

Content-Type: multipart/related;boundary="----=_Part_1_4569975.1498510764791";type="text/xml";start="<soapPart>"

I have another lean model service that I have deployed on TomEE returning it this way (Consumer likes it) -

Content-Type: Multipart/Related; boundary="----=_Part_4_1924421953.1498510734751"; type="application/xop+xml"; start-info="application/soap+xml"

What could be wrong on the first service. Where is the configuration that ensures the right Content-Type?

Update (after 5 days) -

I have narrowed it down to the same exact WAR file returning content-type "text/xml" on Weblogic (10.3.6) and "application/xop+xml" on TomEE 1.7.4. Anyone can tell me what could be the difference between these environments? How can I make the application return the right content type on Weblogic?


问:
Retrieving large amount of records under multiple limitations, without causing an out-of-memory exception
I've got the following situation:

There are two related types. For this question, I'll use the following simple types:

```<code>public class Person
{
     public Guid Id {get; set;}
     public int status {get; set;}
}

public class Account
{
     public Guid AccountId {get; set;}
     public decimal Amount { get; set; }
     public Guid PersonId { get; set; }
}
</code>```

So that one Person might have multiple Accounts (i.e., multiple Accounts would reference the same PersonId).

In our database, there are tens of thousands of persons, and each have 5-10 accounts on average.

I need to retrieve each person's accounts, assuming they fulfill certain requirements. Afterwards, I need to see if all of this person's accounts, together, fulfill another condition.

In this example, let's say I need every account with amount < 100, and that after retrieving one person's accounts, I need to check if their sum is larger than 1000.

Using a LINQ query is desirable, but can't be done using group-by-into keywords, because the Linq-Provider (LINQ-to-CRM) doesn't support it.

In addition, doing the following simple LINQ query to implement listing 3 requirements is also not possible (please read the inlined comment):

```<code>var query = from p in personList
            join a in accountList on p.Id equals a.PersonId
            where a.Amount < 100
            select a;
var groups = query.GroupBy(a => a.PersonId);
// and now, run in bulks on x groups
// (let x be the groups amount that won't cause an out-of-memory exception)
</code>```

It is not possible for 2 reasons:

a. The Linq-Provider force a call to ToList() before using GroupBy().

b. Trying to actually call ToList() before using GroupBy() results in an
   out-of-memory exception - since there are tens of thousands of accounts.

For efficiency reasons, I don't want to do the following, since it means tens of thousands retrievals:

a. Retrieve all persons.

b. Loop through them and retrieve each person's accounts on each iteration.

Will be glad for efficient ideas.

答:
I would order by the GUID and then process in blocks:</p>

```<code>var basep = (from p in personList select p.Id).OrderBy(id => id);

int basepCount = personList.Count();
int blocksize = 1000;
int numblocks = (basepCount / blocksize) + (basepCount % blocksize == 0 ? 0 : 1);
for (var block = 0; block < numblocks; ++block) {
    var firstPersonId = basep.Skip(block * blocksize).First();
    var lastPersonId = basep.Skip(Math.Min(basepCount-1, block*blocksize+blocksize-1)).First();

    var query = from p in personList.Where(ps => firstPersonId.CompareTo(ps.Id) <= 0 && ps.Id.CompareTo(lastPersonId) <= 0)
                join a in accountList on p.Id equals a.PersonId
                where a.Amount < 100
                select a;
    var groups = query.GroupBy(a => a.PersonId);
    // work on groups
}
</code>```

Body:
I've got the following situation:

There are two related types. For this question, I'll use the following simple types:

public class Person
{
     public Guid Id {get; set;}
     public int status {get; set;}
}

public class Account
{
     public Guid AccountId {get; set;}
     public decimal Amount { get; set; }
     public Guid PersonId { get; set; }
}

So that one Person might have multiple Accounts (i.e., multiple Accounts would reference the same PersonId).

In our database, there are tens of thousands of persons, and each have 5-10 accounts on average.

I need to retrieve each person's accounts, assuming they fulfill certain requirements. Afterwards, I need to see if all of this person's accounts, together, fulfill another condition.

In this example, let's say I need every account with amount < 100, and that after retrieving one person's accounts, I need to check if their sum is larger than 1000.

Using a LINQ query is desirable, but can't be done using group-by-into keywords, because the Linq-Provider (LINQ-to-CRM) doesn't support it.

In addition, doing the following simple LINQ query to implement listing 3 requirements is also not possible (please read the inlined comment):

var query = from p in personList
            join a in accountList on p.Id equals a.PersonId
            where a.Amount < 100
            select a;
var groups = query.GroupBy(a => a.PersonId);
// and now, run in bulks on x groups
// (let x be the groups amount that won't cause an out-of-memory exception)

It is not possible for 2 reasons:

a. The Linq-Provider force a call to ToList() before using GroupBy().

b. Trying to actually call ToList() before using GroupBy() results in an
   out-of-memory exception - since there are tens of thousands of accounts.

For efficiency reasons, I don't want to do the following, since it means tens of thousands retrievals:

a. Retrieve all persons.

b. Loop through them and retrieve each person's accounts on each iteration.

Will be glad for efficient ideas.

Body:
I would order by the GUID and then process in blocks:

var basep = (from p in personList select p.Id).OrderBy(id => id);

int basepCount = personList.Count();
int blocksize = 1000;
int numblocks = (basepCount / blocksize) + (basepCount % blocksize == 0 ? 0 : 1);
for (var block = 0; block < numblocks; ++block) {
    var firstPersonId = basep.Skip(block * blocksize).First();
    var lastPersonId = basep.Skip(Math.Min(basepCount-1, block*blocksize+blocksize-1)).First();

    var query = from p in personList.Where(ps => firstPersonId.CompareTo(ps.Id) <= 0 && ps.Id.CompareTo(lastPersonId) <= 0)
                join a in accountList on p.Id equals a.PersonId
                where a.Amount < 100
                select a;
    var groups = query.GroupBy(a => a.PersonId);
    // work on groups
}


问:
Angular 2: default radio button selection
I have two radio buttons (they're not dynamically generated):

```<code><input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending<br>
<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['-recordStartDate']">Descending
</code>```

How do I make one of the radio buttons checked by default?

Thank you!

Edit

The button's values are being passed through this pipe (i.e. not a component, per se...not sure this is worth mentioning?). The app is pretty simple, and the radio buttons are just hardcoded into app.component. Is the pipe the correct place to initialize which radio button is checked by default?

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class OrderByPipe implements PipeTransform {

static _OrderByPipeComparator(a:any, b:any):number{

  if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
    //Isn't a number so lowercase the string to properly compare
    if(a.toLowerCase() < b.toLowerCase()) return -1;
    if(a.toLowerCase() > b.toLowerCase()) return 1;
  }
  else{
    //Parse strings as numbers to compare properly
    if(parseFloat(a) < parseFloat(b)) return -1;
    if(parseFloat(a) > parseFloat(b)) return 1;
  }

  return 0; //equal each other
}

transform(input:any, [config = '+']): any{

    if(!Array.isArray(input)) return input;

    if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
        var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
        var desc = propertyToCheck.substr(0, 1) == '-';

        //Basic array
        if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
            return !desc ? input.sort() : input.sort().reverse();
        }
        else {
            var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                ? propertyToCheck.substr(1)
                : propertyToCheck;

            return input.sort(function(a:any,b:any){
                return !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);
            });
        }
    }
    else {
        //Loop over property of the array in order and sort
        return input.sort(function(a:any,b:any){
            for(var i:number = 0; i < config.length; i++){
                var desc = config[i].substr(0, 1) == '-';
                var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                    ? config[i].substr(1)
                    : config[i];

                var comparison = !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);

                //Don't return 0 yet in case of needing to sort by next property
                if(comparison != 0) return comparison;
            }

            return 0; //equal each other
        });
    }
 }
</code>```

Edit 2

So in component.app.ts I've edited my export class AppComponent{ to the following:

```<code>export class AppComponent {
  artists = ARTISTS;
  currentArtist: Artist;
  orderbydescending = ['-recordStartDate'];

showArtist(item) {
  this.currentArtist = item;
</code>```

}
 }

This works in terms of preventing the previous errors, but it doesn't actually make the radio button selected. It still appears as though it's unselected - even though it functions as though it is. Does this make sense?

答:
If you're doing this in Angular 2+ with 2 way binding, in the component where this HTML is being used, you could just try initializing the value associated with the input.

```<code>// in your component ts file
orderbydescending: boolean = true;
</code>```

and you could leave the HTML the same. Although, you seem to have 2 radio buttons associated with the same data value, orderbydescending. I don't know if that's what you intend, but it looks like it could cause problems.

Here's some code from my personal side project to give you a better idea.

```<code>@Component({
  selector: 'gmu-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  // here you would put your variables
  myFlag: boolean = true;
  constructor() { }
  ngOnInit() {
  }
}
</code>```

Body:
I have two radio buttons (they're not dynamically generated):

<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending

<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['-recordStartDate']">Descending

How do I make one of the radio buttons checked by default?

Thank you!

Edit

The button's values are being passed through this pipe (i.e. not a component, per se...not sure this is worth mentioning?). The app is pretty simple, and the radio buttons are just hardcoded into app.component. Is the pipe the correct place to initialize which radio button is checked by default?

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class OrderByPipe implements PipeTransform {

static _OrderByPipeComparator(a:any, b:any):number{

  if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
    //Isn't a number so lowercase the string to properly compare
    if(a.toLowerCase()  b.toLowerCase()) return 1;
  }
  else{
    //Parse strings as numbers to compare properly
    if(parseFloat(a) < parseFloat(b)) return -1;
    if(parseFloat(a) > parseFloat(b)) return 1;
  }

  return 0; //equal each other
}

transform(input:any, [config = '+']): any{

    if(!Array.isArray(input)) return input;

    if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
        var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
        var desc = propertyToCheck.substr(0, 1) == '-';

        //Basic array
        if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
            return !desc ? input.sort() : input.sort().reverse();
        }
        else {
            var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                ? propertyToCheck.substr(1)
                : propertyToCheck;

            return input.sort(function(a:any,b:any){
                return !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);
            });
        }
    }
    else {
        //Loop over property of the array in order and sort
        return input.sort(function(a:any,b:any){
            for(var i:number = 0; i < config.length; i++){
                var desc = config[i].substr(0, 1) == '-';
                var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                    ? config[i].substr(1)
                    : config[i];

                var comparison = !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);

                //Don't return 0 yet in case of needing to sort by next property
                if(comparison != 0) return comparison;
            }

            return 0; //equal each other
        });
    }
 }

Edit 2

So in component.app.ts I've edited my export class AppComponent{ to the following:

export class AppComponent {
  artists = ARTISTS;
  currentArtist: Artist;
  orderbydescending = ['-recordStartDate'];

showArtist(item) {
  this.currentArtist = item;

}
 }

This works in terms of preventing the previous errors, but it doesn't actually make the radio button selected. It still appears as though it's unselected - even though it functions as though it is. Does this make sense?

Body:
If you're doing this in Angular 2+ with 2 way binding, in the component where this HTML is being used, you could just try initializing the value associated with the input.

// in your component ts file
orderbydescending: boolean = true;

and you could leave the HTML the same. Although, you seem to have 2 radio buttons associated with the same data value, orderbydescending. I don't know if that's what you intend, but it looks like it could cause problems.

Here's some code from my personal side project to give you a better idea.

@Component({
  selector: 'gmu-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  // here you would put your variables
  myFlag: boolean = true;
  constructor() { }
  ngOnInit() {
  }
}


问:
getting oEmbed to work on my non-WordPress (static) website
I have a test page setup with several "oembed"-style links in different formats because I was trying to see what worked:
http://dev2.ohlone.edu/people/clambert/testoembed.html

None of them work. I have searched and searched Google and found nothing to indicate that I have to include a javascript file or anything else on the HTML page.

The server is running Apache on MS Windows Server. I do not manage the server and am unfamiliar with its setup.

This is a static web page - i.e., not generated using WordPress or any other CMS.

What am I missing?
Thank you,
-Cheryl Lambert
Web Designer, Ohlone College

答:
You have added links to oembed provider links in your html. To unfurl it and make visible the content in your html all you have to do is

Invoke oEmbed api which you have added as a XML http request

you should do some thing like this

Then you could get response something like this

<oembed>
 <type>photo</type>
 <flickr_type>photo</flickr_type>
 <title>Bacon Lollys</title>
 <author_name>bees</author_name>
 <author_url>https://www.flickr.com/photos/bees/</author_url>
 <width>1024</width>
 <height>768</height>
 <url>
  https://farm4.staticflickr.com/3040/2362225867_4a87ab8baf_b.jpg
 </url>
 <web_page>https://www.flickr.com/photos/bees/2362225867/</web_page>
 <thumbnail_url>
  https://farm4.staticflickr.com/3040/2362225867_4a87ab8baf_q.jpg
 </thumbnail_url>
 <thumbnail_width>150</thumbnail_width>
 <thumbnail_height>150</thumbnail_height>
 <web_page_short_url>https://flic.kr/p/4AK2sc</web_page_short_url>
 <license>All Rights Reserved</license>
 <license_id>0</license_id>

 <version>1.0</version>
 <cache_age>3600</cache_age>
 <provider_name>Flickr</provider_name>
 <provider_url>https://www.flickr.com/</provider_url>
</oembed>```

Parse the response content and construct a div content which could contain

File name

Author name

Provider name

Description or

Embed video content

And finally add the content to your HTML page.

Body:
You have added links to oembed provider links in your html. To unfurl it and make visible the content in your html all you have to do is

Invoke oEmbed api which you have added as a XML http request

you should do some thing like this

Then you could get response something like this

<oembed>
 <type>photo</type>
 <flickr_type>photo</flickr_type>
 <title>Bacon Lollys</title>
 <author_name>bees</author_name>
 <author_url>https://www.flickr.com/photos/bees/</author_url>
 <width>1024</width>
 <height>768</height>
 <url>
  https://farm4.staticflickr.com/3040/2362225867_4a87ab8baf_b.jpg
 </url>
 <web_page>https://www.flickr.com/photos/bees/2362225867/</web_page>
 <thumbnail_url>
  https://farm4.staticflickr.com/3040/2362225867_4a87ab8baf_q.jpg
 </thumbnail_url>
 <thumbnail_width>150</thumbnail_width>
 <thumbnail_height>150</thumbnail_height>
 <web_page_short_url>https://flic.kr/p/4AK2sc</web_page_short_url>
 <license>All Rights Reserved</license>
 <license_id>0</license_id>
 <html>
  <a data-flickr-embed="true" href="https://www.flickr.com/photos/bees/2362225867/" title="Bacon Lollys by bees, on Flickr"><img src="https://farm4.staticflickr.com/3040/2362225867_4a87ab8baf_b.jpg" width="1024" height="768" alt="Bacon Lollys"></a><script async src="https://embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>
 </html>
 <version>1.0</version>
 <cache_age>3600</cache_age>
 <provider_name>Flickr</provider_name>
 <provider_url>https://www.flickr.com/</provider_url>
</oembed>

Parse the response content and construct a div content which could contain

File name

Author name

Provider name

Description or

Embed video content

And finally add the content to your HTML page.


问:
Show only results in query with more then 2 hits
didnt find a solution yet... ;-)

suppose this is the result of a query:

```<code>ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .
</code>```

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

答: SELECT * FROM test WHERE id IN (SELECT id FROM test GROUP BY id HAVING COUNT(id) > 1);

Body:
didnt find a solution yet... ;-)

suppose this is the result of a query:

ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?


问:
jQuery ajax posting to wrong url in rails app
```<code>$.ajax({
 type: "POST",
 url: "analytics/test",
 data: 'correct=' + correct_or_incorrect + '&id=' + correctCharacter[3] + "'"
 });
</code>```

I'm using this to post some information to a rails app. Problem is that it is just posting to the application controller.

How can I get it so that the url is positing to :controller => 'analytics', :action => 'test'

答:
The path to your url (analytics/test) is relative, meaning it will be appended to the "directory" of the url you are working in. E.g. if you are calling this from http://yourhost.com/analytics/demo, you will call http://yourhost.com/analytics/analytics/test, which you probably do not want.

Add a slash to the beginning (so you get /analytics/test) and you're fine.

```<code>$.ajax({
    type: "POST",
    url: "/analytics/test",
    data: 'correct=' + correct_or_incorrect + '&id=' + correctCharacter[3] + "'"
});
</code>```

Body:
$.ajax({
 type: "POST",
 url: "analytics/test",
 data: 'correct=' + correct_or_incorrect + '&id=' + correctCharacter[3] + "'"
 });

I'm using this to post some information to a rails app. Problem is that it is just posting to the application controller.

How can I get it so that the url is positing to :controller => 'analytics', :action => 'test'

Body:
The path to your url (analytics/test) is relative, meaning it will be appended to the "directory" of the url you are working in. E.g. if you are calling this from http://yourhost.com/analytics/demo, you will call http://yourhost.com/analytics/analytics/test, which you probably do not want.

Add a slash to the beginning (so you get /analytics/test) and you're fine.

$.ajax({
    type: "POST",
    url: "/analytics/test",
    data: 'correct=' + correct_or_incorrect + '&id=' + correctCharacter[3] + "'"
});


问:
I want to know what exactly sys.exit(-1) returns in python?
My code goes like this:

```<code>if (not Y):
    print ("Can't print")
    sys.exit(-1)
</code>```

I am unable to understand what does the argument (-1) returns?

答:
The call sys.exit(n) tells the interpreter to stop the execution and return n to the OS. What this value is depends on the operating system.

For example on UNIX ($? is the last exit status):

```<code>$ python -c "import sys; sys.exit(-1)"
$ echo $?
255
</code>```

This is because it treats the return value as an unsigned 8bit value (see here). On Windows the value would be an unsigned 32bit value (from here) and thus be 4294967295.

As you can see in the first link, the convention is to return 0 on a successful exit and a non-zero value otherwise. Sometimes you'll see that an application has a certain convention for its status codes.

For example the program wget has a section in its man page that tells you why an error occurred:

```<code>EXIT STATUS
       Wget may return one of several error codes if it encounters problems.

       0   No problems occurred.

       1   Generic error code.

       2   Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...

       3   File I/O error.

       4   Network failure.

       5   SSL verification failure.

       6   Username/password authentication failure.

       7   Protocol errors.

       8   Server issued an error response.
</code>```

The convention of returning 0 on a success is very helpful for writing scripts:

```<code>$ if python -c "import sys; sys.exit(-1)"; then echo "Everything fine"; else echo "Not good"; fi
Not good
$ if python -c "import sys; sys.exit(0)"; then echo "Everything fine"; else echo "Not good"; fi
Everything fine
</code>```

Body:
My code goes like this:

if (not Y):
    print ("Can't print")
    sys.exit(-1)

I am unable to understand what does the argument (-1) returns?

Body:
The call sys.exit(n) tells the interpreter to stop the execution and return n to the OS. What this value is depends on the operating system.

For example on UNIX ($? is the last exit status):

$ python -c "import sys; sys.exit(-1)"
$ echo $?
255

This is because it treats the return value as an unsigned 8bit value (see here). On Windows the value would be an unsigned 32bit value (from here) and thus be 4294967295.

As you can see in the first link, the convention is to return 0 on a successful exit and a non-zero value otherwise. Sometimes you'll see that an application has a certain convention for its status codes.

For example the program wget has a section in its man page that tells you why an error occurred:

EXIT STATUS
       Wget may return one of several error codes if it encounters problems.

       0   No problems occurred.

       1   Generic error code.

       2   Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...

       3   File I/O error.

       4   Network failure.

       5   SSL verification failure.

       6   Username/password authentication failure.

       7   Protocol errors.

       8   Server issued an error response.

The convention of returning 0 on a success is very helpful for writing scripts:

$ if python -c "import sys; sys.exit(-1)"; then echo "Everything fine"; else echo "Not good"; fi
Not good
$ if python -c "import sys; sys.exit(0)"; then echo "Everything fine"; else echo "Not good"; fi
Everything fine


问:
STM32 uploading application/software over ethernet
Is there a way to upload applications to an STM32 board over the ethernet?

I need to be able to upload code to ~200 Nucleo F429ZI boards that are only connected together with a PC via a LAN.

答: You can find example codes for STM324xG_EVAL and STM324x9I_EVAL board on STMCubeF4 under LWIP_IAP folder and you can follow the documents UM1709 and AN3968. You should adapt example codes according to your board. </p>

ContentLicense: CC BY-SA 4.0


问:
Trying to make a footer with buttons floated to the left and right
I would like this code to resemble the bottom of Google's homepage. It is still listing vertically, even with "inline". I want each three "lists" to be next to each other horizontally on the left and right side of the screen.</p>

```<code>#HTML
<footer>
<div class="footer">
<ul style="width:10%; float:left;list-style-type:none;">
      <li>Advertising</li>
      <li>Business</li>
      <li>About</li>
   </ul>

   <ul style="width:10%; float:right;list-style-type:none;">
      <li>Privacy</li>
      <li>Terms</li>
      <li>Settings</li>
   </ul>
</div>
</footer>

#CSS

.footer li{
  display:inline;
}
</code>```

答: You should remove the width on your uls. See this codepen. Floating elements will take the width of all their children. By wrapping them in an element that take 10% of the width, they don't have enough space to stay on the same row.

Body:
I would like this code to resemble the bottom of Google's homepage. It is still listing vertically, even with "inline". I want each three "lists" to be next to each other horizontally on the left and right side of the screen.

#HTML

Advertising

Business

About

Privacy

Terms

Settings

#CSS

.footer li{
  display:inline;
}


问:
Angular 2/4 img src
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

```<code><img [src]={{imgUrl}} />
<img [src]="imgUrl" />

<img src={{imgUrl}} />
<img src="imgUrl" />

<img ng-src="imgUrl" />

<img src="assets/images/img.jpg" />
<!-- and a few more -->
</code>```

With .ts file like:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}
</code>```

Project structure:

```<code>src
--app
----home
------ts-files
--assets
----images
------img.jpg
</code>```

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

```<code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

答:
Answer provided by @J.D. in the comments section.

In .angular-cli.json add the name of your directory containing images to assets. Ex: directory to add is images  "assets": ["assets", "images" ]

As @stealththeninja noticed, ur angular.cli.json misses images. Try add it - "assets": [ "assets", "images"

Title: Angular 2/4 img src

Body:
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

With .ts file like:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}

Project structure:

src
--app
----home
------ts-files
--assets
----images
------img.jpg

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}