问:
scale_fill in ggplot2 - Make a gradient color for every plot in a list of ggplots
I make a list of ggplots stored in an object called g.a, Here's the code to reproduce the plots (data is provided at the bottom).

Worth to note that I am probably missing something simple and over-complicated the problem.

```<code>RCfitter <- function(w,h,a,b){(a * ((w + h)^b))}

fillfactor <- lapply(seq_len(length(dat.a)), function(i) {
              as.factor((gsub("-.*","",dat.a[[i]]$Date)))}) #I tried as.integer as well

set.seed(92)
lin.a <- lapply(seq_len(length(dat.a)), function(i) {
                          data.frame(x = runif(100, -dB.coef.a[3,i],
                          max(dat.a[[i]]$WL)+diff(0.2*range(dat.a[[i]]$Q))))})

library(ggplot2)

g.a <- lapply(seq_len(length(dat.a)), function(i) {
ggplot() +
geom_point(data=dat.a[[i]], aes(x=WL,y=Q, tltip = Date,
fill =fillfactor[[i]]),
colour = NA, pch=21) +

scale_fill_manual(breaks = mybreaks, values = myfills)+

geom_line(data = lin.a[[i]],
          aes(x=x,y= RCfitter(x,dB.coef.a[3,i],dB.coef.a[1,i],dB.coef.a[2,i])),colour="red")+

xlab("WL") +
ylab("Q") +
ggtitle(paste("pLot ",i)) +
ylim(c(0,(max(dat.a[[i]]$Q)+diff(0.2*range(dat.a[[i]]$Q))))) +
xlim(c(0,(max(dat.a[[i]]$WL)+diff(0.2*range(dat.a[[i]]$WL))))) +
theme(legend.position="none")
                              })
</code>```

If I ignore the scale_fill I can plot them and I will get the "colorful" plot. But with that I get this warning:

```<code>g.a[[2]]

##  Warning messages:
##  1: Removed 6 rows containing missing values (geom_point).
##  2: Removed 64 rows containing missing values (geom_path).
</code>```

Which means geom_point does not plot anything.

I used scale_fill_discrete, scale_fill_continuous, etc. and they give me errors like discrete value to continuous scale or vice versa or.

What I really want is to make a gradient color for years, let's say from blue to red, so I can distinguish between the years while seeing if there's a chunk of similar years (e.g. 60s) around the same spot.

P.S. At the end, I am using ggplotly() (e.g. ggplotly(g.a[[2]],tooltip = c("x","y","tltip")). So, if that would change the behavior of scale_fill (which is, for example, some of the colors that I have specified are invalid for plotly) , please have that in mind.

Sample Data:

dat.a

```<code> dat.a <- list(structure(list(Date = c("1974-02-14", "1974-02-16", "1974-02-28",
     "1974-02-28", "1974-02-28", "1974-02-28"), WL = c(0.24, 0.135,
     0.395, 0.26, 0.22, 0.31), Q = c(0.237, 0.04, 0.9, 0.36, 0.52,
     0.56), Velocity = c(0.3, 0.103, 0.367, 0.209, 0.34, 0.276), Area = c(0.79,
     0.388, 2.452, 1.722, 1.529, 2.029), Flag = c(NA_character_, NA_character_,
     NA_character_, NA_character_, NA_character_, NA_character_),
         Shift = c("/", "/", "/", "/", "/", "/"), date = structure(c(130032000,
         130204800, 131241600, 131241600, 131241600, 131241600), class = c("POSIXct",
         "POSIXt"), tzone = "UTC")), .Names = c("Date", "WL", "Q",
     "Velocity", "Area", "Flag", "Shift", "date"), row.names = c(NA,
     -6L), class = c("tbl_df", "tbl", "data.frame")), structure(list(
         Date = c("1965-01-29", "1965-01-29", "1965-04-25", "1966-11-29",
         "1967-01-24", "1967-11-12"), WL = c(0.439, 0.439, 0.482,
         0.463, 0.427, 0.475), Q = c(0.252, 0.269, 0.403, 0.314, 0.199,
         0.4), Velocity = c(0.23, 0.232, 0.316, 0.279, 0.249, 0.36
         ), Area = c(1.096, 1.159, 1.275, 1.125, 0.799, 1.111), Flag = c(NA_character_,
         NA_character_, NA_character_, NA_character_, NA_character_,
         NA_character_), Shift = c("/", "/", "/", "/", "/", "/"),
         date = structure(c(-155347200, -155347200, -147916800, -97545600,
         -92707200, -67478400), class = c("POSIXct", "POSIXt"), tzone = "UTC")),
        .Names = c("Date","WL", "Q", "Velocity", "Area", "Flag", "Shift", "date"),
        row.names = c(NA,-6L), class = c("tbl_df", "tbl", "data.frame")))
</code>```

dB.coef.a

```<code> dB.coef.a <- structure(c(-77.6915945552795, 0.594614568300253, 60.9718752625543,
     7.96297849987566, 2.69599957356069, -0.183937755444007), .Dim = c(3L,
     2L), .Dimnames = list(c("a", "b", "h"), NULL))
</code>```

mybreaks

```<code> mybreaks <- c(1955, 1956, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966,
     1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977,
     1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988,
     1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
     2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
     2011, 2012, 2013, 2014, 2015, 2016, 2017)
</code>```

myfills

```<code> myfills <- c("005ABF", "0358BC", "0757B9", "0A56B6", "0E54B3", "1153B0",
     "1552AD", "1851AA", "1C4FA7", "1F4EA4", "234DA2", "264B9F", "2A4A9C",
     "2D4999", "314896", "344693", "384590", "3B448D", "3F428A", "424187",
     "464085", "493F82", "4D3D7F", "503C7C", "543B79", "573976", "5B3873",
     "5E3770", "62366D", "65346A", "693368", "6D3265", "703062", "742F5F",
     "772E5C", "7B2D59", "7E2B56", "822A53", "852950", "89274D", "8C264B",
     "902548", "932445", "972242", "9A213F", "9E203C", "A11E39", "A51D36",
     "A81C33", "AC1B30", "AF192E", "B3182B", "B61728", "BA1525", "BD1422",
     "C1131F", "C4121C", "C81019", "CB0F16", "CF0E13", "D30D11")
</code>```

答:
A suggestion, if I correctly understood your problem :

1. I have an error message with colors (myfills) :

Error in grDevices::col2rgb(colour, TRUE)

# is missing :

```<code>mycolors <- paste0("#", myfills) # correct colors
names(mycolors ) <- mybreaks # name your colors
mycolors[names(mycolors) == "1965"] <- "#D30D11" # swapped color to red to check its ok
</code>```

2. If you really want no "color" with pch = 21 for geom_point, better use pch = 16, then forget fill aesthetics and use color instead :

```<code>g.a <- lapply(seq_len(length(dat.a)), function(i) {
    ggplot(data = dat.a[[i]], aes(x = WL, y = Q, color = fillfactor[[i]])) +
    geom_point(pch = 16) +
    scale_color_manual(values = mycolors) +
    geom_line(data = lin.a[[i]], aes(x = x, y = RCfitter(x, dB.coef.a[3,i], dB.coef.a[1,i], dB.coef.a[2,i])), colour = "red") +
    ggtitle(paste("pLot ",i)) +
    ylim(c(0,(max(dat.a[[i]]$Q) + diff(0.2*range(dat.a[[i]]$Q))))) +
    xlim(c(0,(max(dat.a[[i]]$WL) + diff(0.2*range(dat.a[[i]]$WL))))) +
    theme(legend.position="none")
 }
)
g.a[[2]]
</code>```

3. Warning message about geom_path is due to your xlim().

Body:
I make a list of ggplots stored in an object called g.a, Here's the code to reproduce the plots (data is provided at the bottom).

Worth to note that I am probably missing something simple and over-complicated the problem.

RCfitter <- function(w,h,a,b){(a * ((w + h)^b))}

fillfactor <- lapply(seq_len(length(dat.a)), function(i) {
              as.factor((gsub("-.*","",dat.a[[i]]$Date)))}) #I tried as.integer as well

set.seed(92)
lin.a <- lapply(seq_len(length(dat.a)), function(i) {
                          data.frame(x = runif(100, -dB.coef.a[3,i],
                          max(dat.a[[i]]$WL)+diff(0.2*range(dat.a[[i]]$Q))))})

library(ggplot2)

g.a <- lapply(seq_len(length(dat.a)), function(i) {
ggplot() +
geom_point(data=dat.a[[i]], aes(x=WL,y=Q, tltip = Date,
fill =fillfactor[[i]]),
colour = NA, pch=21) +

scale_fill_manual(breaks = mybreaks, values = myfills)+

geom_line(data = lin.a[[i]],
          aes(x=x,y= RCfitter(x,dB.coef.a[3,i],dB.coef.a[1,i],dB.coef.a[2,i])),colour="red")+

xlab("WL") +
ylab("Q") +
ggtitle(paste("pLot ",i)) +
ylim(c(0,(max(dat.a[[i]]$Q)+diff(0.2*range(dat.a[[i]]$Q))))) +
xlim(c(0,(max(dat.a[[i]]$WL)+diff(0.2*range(dat.a[[i]]$WL))))) +
theme(legend.position="none")
                              })

If I ignore the scale_fill I can plot them and I will get the "colorful" plot. But with that I get this warning:

g.a[[2]]

##  Warning messages:
##  1: Removed 6 rows containing missing values (geom_point).
##  2: Removed 64 rows containing missing values (geom_path).

Which means geom_point does not plot anything.

I used scale_fill_discrete, scale_fill_continuous, etc. and they give me errors like discrete value to continuous scale or vice versa or.

What I really want is to make a gradient color for years, let's say from blue to red, so I can distinguish between the years while seeing if there's a chunk of similar years (e.g. 60s) around the same spot.

P.S. At the end, I am using ggplotly() (e.g. ggplotly(g.a[[2]],tooltip = c("x","y","tltip")). So, if that would change the behavior of scale_fill (which is, for example, some of the colors that I have specified are invalid for plotly) , please have that in mind.

Sample Data:

dat.a

 dat.a <- list(structure(list(Date = c("1974-02-14", "1974-02-16", "1974-02-28",
     "1974-02-28", "1974-02-28", "1974-02-28"), WL = c(0.24, 0.135,
     0.395, 0.26, 0.22, 0.31), Q = c(0.237, 0.04, 0.9, 0.36, 0.52,
     0.56), Velocity = c(0.3, 0.103, 0.367, 0.209, 0.34, 0.276), Area = c(0.79,
     0.388, 2.452, 1.722, 1.529, 2.029), Flag = c(NA_character_, NA_character_,
     NA_character_, NA_character_, NA_character_, NA_character_),
         Shift = c("/", "/", "/", "/", "/", "/"), date = structure(c(130032000,
         130204800, 131241600, 131241600, 131241600, 131241600), class = c("POSIXct",
         "POSIXt"), tzone = "UTC")), .Names = c("Date", "WL", "Q",
     "Velocity", "Area", "Flag", "Shift", "date"), row.names = c(NA,
     -6L), class = c("tbl_df", "tbl", "data.frame")), structure(list(
         Date = c("1965-01-29", "1965-01-29", "1965-04-25", "1966-11-29",
         "1967-01-24", "1967-11-12"), WL = c(0.439, 0.439, 0.482,
         0.463, 0.427, 0.475), Q = c(0.252, 0.269, 0.403, 0.314, 0.199,
         0.4), Velocity = c(0.23, 0.232, 0.316, 0.279, 0.249, 0.36
         ), Area = c(1.096, 1.159, 1.275, 1.125, 0.799, 1.111), Flag = c(NA_character_,
         NA_character_, NA_character_, NA_character_, NA_character_,
         NA_character_), Shift = c("/", "/", "/", "/", "/", "/"),
         date = structure(c(-155347200, -155347200, -147916800, -97545600,
         -92707200, -67478400), class = c("POSIXct", "POSIXt"), tzone = "UTC")),
        .Names = c("Date","WL", "Q", "Velocity", "Area", "Flag", "Shift", "date"),
        row.names = c(NA,-6L), class = c("tbl_df", "tbl", "data.frame")))

dB.coef.a

 dB.coef.a <- structure(c(-77.6915945552795, 0.594614568300253, 60.9718752625543,
     7.96297849987566, 2.69599957356069, -0.183937755444007), .Dim = c(3L,
     2L), .Dimnames = list(c("a", "b", "h"), NULL))

mybreaks

 mybreaks <- c(1955, 1956, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966,
     1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977,
     1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988,
     1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
     2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
     2011, 2012, 2013, 2014, 2015, 2016, 2017)

myfills

 myfills <- c("005ABF", "0358BC", "0757B9", "0A56B6", "0E54B3", "1153B0",
     "1552AD", "1851AA", "1C4FA7", "1F4EA4", "234DA2", "264B9F", "2A4A9C",
     "2D4999", "314896", "344693", "384590", "3B448D", "3F428A", "424187",
     "464085", "493F82", "4D3D7F", "503C7C", "543B79", "573976", "5B3873",
     "5E3770", "62366D", "65346A", "693368", "6D3265", "703062", "742F5F",
     "772E5C", "7B2D59", "7E2B56", "822A53", "852950", "89274D", "8C264B",
     "902548", "932445", "972242", "9A213F", "9E203C", "A11E39", "A51D36",
     "A81C33", "AC1B30", "AF192E", "B3182B", "B61728", "BA1525", "BD1422",
     "C1131F", "C4121C", "C81019", "CB0F16", "CF0E13", "D30D11")

Body:
A suggestion, if I correctly understood your problem :

1. I have an error message with colors (myfills) :

Error in grDevices::col2rgb(colour, TRUE)

# is missing :

mycolors <- paste0("#", myfills) # correct colors
names(mycolors ) <- mybreaks # name your colors
mycolors[names(mycolors) == "1965"] <- "#D30D11" # swapped color to red to check its ok

2. If you really want no "color" with pch = 21 for geom_point, better use pch = 16, then forget fill aesthetics and use color instead :

g.a <- lapply(seq_len(length(dat.a)), function(i) {
    ggplot(data = dat.a[[i]], aes(x = WL, y = Q, color = fillfactor[[i]])) +
    geom_point(pch = 16) +
    scale_color_manual(values = mycolors) +
    geom_line(data = lin.a[[i]], aes(x = x, y = RCfitter(x, dB.coef.a[3,i], dB.coef.a[1,i], dB.coef.a[2,i])), colour = "red") +
    ggtitle(paste("pLot ",i)) +
    ylim(c(0,(max(dat.a[[i]]$Q) + diff(0.2*range(dat.a[[i]]$Q))))) +
    xlim(c(0,(max(dat.a[[i]]$WL) + diff(0.2*range(dat.a[[i]]$WL))))) +
    theme(legend.position="none")
 }
)
g.a[[2]]

3. Warning message about geom_path is due to your xlim().


来源: stackexchange

问:
Vagrant, Docker, Puppet, Chef
I don't understand even the basic difference between the services in the title. Do these services just provide software to help you configure/organize/manage your VM's, or do they also provide physical infrastructure for your VM's to run on? In other words, are they just convenient interfaces between developers and AWS, Rackspace, and Azure?</p>

答:
Chef : Chef is an automation platform to transform your infrastructure into code. It is generally called, Configuration Management Software. You can define the state with different parameters as your config files, s/w, tools, access types and resource types, etc. Also, you can configure different machines with different functionality based on your need.

Puppet : Puppet is a tool that allows you to abstract specific concepts of the target machine and make the configuration process more operating system agnostic. It allows to install a package or run a background service on startup independently. Define a command, packages those need to installed, step dependencies, file content, and other things you would need to get machine up and running without problems.

Vagrant : Vagrant is a project that helps the spawning of virtual machines. It started as an command line of VirtualBox, something similar to Gemfile for VM's. You can choose the base image to start with, network, IP, share folders and put it all in a file that anyone can reuse to spawn the same configured machine. Vagrant has different extensions, provisioning options and VM providers. You can run a VirtualBox, VMware and it is extensible enough to be able to create instances on EC2.

Docker : Docker, allows to package an application with all of its dependencies into a standardized unit of software development. So, it reduces a friction between developer, QA and testing. It dynamically change your application, adding new capabilities every single day, scaling out services to quickly changing the problem areas. Docker is putting itself in an excited place as the interface to PaaS be it networking, discovery and service discovery with applications not having to care about underlying infrastructure. Yes, their are still issues with docker in production(thought all major companies already migrated their infrastructure to docker), but, hopefully, we'll see the solutions to those problems, as docker team and contributors working hard on those issues. As Docker Volume driver allows third-party container data management solutions to provide data volumes for containers which operate on data, such as database, key-value stores, and other stateful applications. As you can see one, rexray, as volume plugin and provides advanced storage functionality. emccode/rexray We're finally starting to agree on more than just images and runtime.

ContentLicense: CC BY-SA 3.0

Title: Vagrant, Docker, Puppet, Chef


问:
d3.js - area chart vertical overflow if y.domain doesn't start at 0
How do I limit the contents of an area chart to stay inside the area determined by the two axes?

Here's the situation. If I set the vertical domain to be between 0 and the maximum of my data set, I don't have a problem:

```<code>y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
</code>```

However, sometimes I can't start from 0. When I need to start from the smallest number in the data set, the problem emerges:

```<code>y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
</code>```

As you see, the blue area of the chart flows over the bottom horizontal axis, and that's just ugly and messy. I could switch to a line chart to avoid this problem, but I'd much rather keep an area chart and resolve the issue. Any solutions?

EDIT This is the full code I'm using. If the full parameter is true, then the chart starts at 0. If not, then it starts at the data minimum.

```<code>function create_area_chart(data, full){
    var svg = d3.select(".chart-holder").append("svg").attr("width","800").attr("height", "400")
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y-%m-%d")
        bisectDate = d3.bisector(function(d) { return d.date; }).left;

    var x = d3.scaleTime()
        .rangeRound([0, width]);

    var y = d3.scaleLinear()
        .rangeRound([height, 0]);

    var area = d3.area()
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.value); });

    data.forEach(function(d) {
        d.date = parseTime(d.date);
        d.value = +d.value;
    });

    x.domain(d3.extent(data, function(d) { return d.date; }));
    if(full)
        y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    else
        y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));

    g.append("path")
        .datum(data)
        .attr("fill", "steelblue")
        .attr("d", area);

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    svg.append("rect")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);
}
</code>```

答:
You need to set the floor for the area chart by changing y0

```<code>if(full){
    y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));
} else {
    y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0.91*d3.min(data, function(d) { return d.value; })));
}
</code>```

see the docs: https://github.com/d3/d3/blob/master/API.md#areas

EDIT

Reproducing the Problem

Consider this area chart which OP's code is adapted from.

I run the code in the example and get the following plot:

Everything is as expected. The y domain and y0 are set as follows:

```<code>y.domain([0, d3.max(data, function(d) { return d.close; })]);
area.y0(y(0));
</code>```

Now, if I change the y domain to:

```<code>y.domain([
    0.91*d3.min(data, function(d) { return d.close; }),
    d3.max(data, function(d) { return d.close; })
]);
</code>```

I get the following plot:

We get the overflow, but if I now change the y0() to match the new y domain to:

```<code>area.y0(y(0.91*d3.min(data, function(d) { return d.close; })));
</code>```

which plots:

The overflow has now been corrected.

Body:
How do I limit the contents of an area chart to stay inside the area determined by the two axes?

Here's the situation. If I set the vertical domain to be between 0 and the maximum of my data set, I don't have a problem:

y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);

However, sometimes I can't start from 0. When I need to start from the smallest number in the data set, the problem emerges:

y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);

As you see, the blue area of the chart flows over the bottom horizontal axis, and that's just ugly and messy. I could switch to a line chart to avoid this problem, but I'd much rather keep an area chart and resolve the issue. Any solutions?

EDIT This is the full code I'm using. If the full parameter is true, then the chart starts at 0. If not, then it starts at the data minimum.

function create_area_chart(data, full){
    var svg = d3.select(".chart-holder").append("svg").attr("width","800").attr("height", "400")
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y-%m-%d")
        bisectDate = d3.bisector(function(d) { return d.date; }).left;

    var x = d3.scaleTime()
        .rangeRound([0, width]);

    var y = d3.scaleLinear()
        .rangeRound([height, 0]);

    var area = d3.area()
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.value); });

    data.forEach(function(d) {
        d.date = parseTime(d.date);
        d.value = +d.value;
    });

    x.domain(d3.extent(data, function(d) { return d.date; }));
    if(full)
        y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    else
        y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));

    g.append("path")
        .datum(data)
        .attr("fill", "steelblue")
        .attr("d", area);

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    svg.append("rect")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);
}

Body:
You need to set the floor for the area chart by changing y0

if(full){
    y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));
} else {
    y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0.91*d3.min(data, function(d) { return d.value; })));
}

see the docs: https://github.com/d3/d3/blob/master/API.md#areas

EDIT

Reproducing the Problem

Consider this area chart which OP's code is adapted from.

I run the code in the example and get the following plot:

Everything is as expected. The y domain and y0 are set as follows:

y.domain([0, d3.max(data, function(d) { return d.close; })]);
area.y0(y(0));

Now, if I change the y domain to:

y.domain([
    0.91*d3.min(data, function(d) { return d.close; }),
    d3.max(data, function(d) { return d.close; })
]);

I get the following plot:

We get the overflow, but if I now change the y0() to match the new y domain to:

area.y0(y(0.91*d3.min(data, function(d) { return d.close; })));

which plots:

The overflow has now been corrected.


问:
How can I call a command with non-value (InputOption::VALUE_NONE) param from other command?
If I execute from command line:
php bin/console doctrine:migrations:migrate -n --em=views

everything work well.

However, when I try to execute this command from another command, I don't know how to put the InputOption::VALUE_NONE params into the ArrayInput.

```<code>private function executeMigrate($connection = null) {
    $theCommandStr = 'doctrine:migrations:migrate';
    $command = $this->getApplication()->find($theCommandStr) ;
    if ($command)
    {
        $arguments = [];
        $arguments['-n'] = null; //<-- THE PROBLEM IS HERE!
        $arguments['--em'] = 'views';

        $input = new ArrayInput($arguments);
        $output = new BufferedOutput();
        $returnCode = $command->run($input, $output);

        if($returnCode == 0) {
            echo "OK";
        } else {
            echo "KO";
        }
    }
}
</code>```

I've tested (without luck):
$arguments['-n'] = null;
$arguments['-n'] = "";

With the two options, the command was executed but the -n modifier was ignored.

I'm using Symfony v.3.3.

答:
Solved. If you want use --no-interaction or -n modifier in a command inside other command, you must use ArrayInput::setInteractive method:

Previous code would look like:

```<code>private function executeMigrate($connection = null) {
    $theCommandStr = 'doctrine:migrations:migrate';
    $command = $this->getApplication()->find($theCommandStr) ;
    if ($command)
    {
        $arguments = [];
        $arguments['--em'] = 'views';

        $input = new ArrayInput($arguments);
        $input->setInteractive(false);
        $output = new BufferedOutput();
        $returnCode = $command->run($input, $output);

        if($returnCode == 0) {
            echo "OK";
        } else {
            echo "KO";
        }
    }
}
</code>```

Otherwise, it won't work.

Body:
If I execute from command line:
php bin/console doctrine:migrations:migrate -n --em=views

everything work well.

However, when I try to execute this command from another command, I don't know how to put the InputOption::VALUE_NONE params into the ArrayInput.

private function executeMigrate($connection = null) {
    $theCommandStr = 'doctrine:migrations:migrate';
    $command = $this->getApplication()->find($theCommandStr) ;
    if ($command)
    {
        $arguments = [];
        $arguments['-n'] = null; //<-- THE PROBLEM IS HERE!
        $arguments['--em'] = 'views';

        $input = new ArrayInput($arguments);
        $output = new BufferedOutput();
        $returnCode = $command->run($input, $output);

        if($returnCode == 0) {
            echo "OK";
        } else {
            echo "KO";
        }
    }
}

I've tested (without luck):
$arguments['-n'] = null;
$arguments['-n'] = "";

With the two options, the command was executed but the -n modifier was ignored.

I'm using Symfony v.3.3.

Body:
Solved. If you want use --no-interaction or -n modifier in a command inside other command, you must use ArrayInput::setInteractive method:

Previous code would look like:

private function executeMigrate($connection = null) {
    $theCommandStr = 'doctrine:migrations:migrate';
    $command = $this->getApplication()->find($theCommandStr) ;
    if ($command)
    {
        $arguments = [];
        $arguments['--em'] = 'views';

        $input = new ArrayInput($arguments);
        $input->setInteractive(false);
        $output = new BufferedOutput();
        $returnCode = $command->run($input, $output);

        if($returnCode == 0) {
            echo "OK";
        } else {
            echo "KO";
        }
    }
}

Otherwise, it won't work.


问:
GroovyCastException while running java code containing new line "\n" with groovy script engine(GroovyClassLoader)
Currently I am working on a way to run java code in string form. So here is how I did it.

```<code>import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;

public class GroovyStackOverflow {

    public static void main(String[] args) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        String codeSnippet = "double calculatedAnswer = (Double)"
                + "contextMap.get(\"doubleValue\") * (Double)contextMap.get(\"doubleValue\");"
                + " calculatedAnswer = Math.sqrt(calculatedAnswer); "
                + "calculatedAnswer = calculatedAnswer * calculatedAnswer;"
                + "System.out.println(calculatedAnswer);"
                + " return calculatedAnswer;";
        StringBuilder sb = new StringBuilder();
        sb.append("public class ScriptImplementor implements ScriptEvaluator { public Object evaluate(Map contextMap) {");
        sb.append(codeSnippet);
        sb.append("} }");
        Class<?> clazz = gcl.parseClass(sb.toString());
        ScriptEvaluator scriptEvaluator = null;
        double calculatedAnswer = 100.0;
        try {
            Map contextMap = new HashMap();
            contextMap.put("doubleValue", (double)100.0);
            contextMap.put("threadId", "thread"+100);
            contextMap.put("hashCode", 100);
            scriptEvaluator = (ScriptEvaluator) clazz.newInstance();
            scriptEvaluator.evaluate(contextMap);;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

public interface ScriptEvaluator {
    public Object evaluate(Map contextMap);
}
</code>```

Problem is that it fails in following case.

```<code>import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;

public class GroovyStackOverflow {

    public static void main(String[] args) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        String codeSnippet = "double calculatedAnswer = (Double)"
                + "\n "
                + "contextMap.get(\"doubleValue\") * (Double)contextMap.get(\"doubleValue\");"
                + " calculatedAnswer = Math.sqrt(calculatedAnswer); "
                + "calculatedAnswer = calculatedAnswer * calculatedAnswer;"
                + "System.out.println(calculatedAnswer);"
                + " return calculatedAnswer;";
        StringBuilder sb = new StringBuilder();
        sb.append("public class ScriptImplementor implements ScriptEvaluator { public Object evaluate(Map contextMap) {");
        //sb.append(codeSnippet.replaceAll("\n", " "));
        sb.append(codeSnippet);
        sb.append("} }");
        Class<?> clazz = gcl.parseClass(sb.toString());
        ScriptEvaluator scriptEvaluator = null;
        double calculatedAnswer = 100.0;
        try {
            Map contextMap = new HashMap();
            contextMap.put("doubleValue", (double)100.0);
            contextMap.put("threadId", "thread"+100);
            contextMap.put("hashCode", 100);
            scriptEvaluator = (ScriptEvaluator) clazz.newInstance();
            scriptEvaluator.evaluate(contextMap);;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
public interface ScriptEvaluator {
    public Object evaluate(Map contextMap);
}
</code>```

I don't understand why it fails and what this error message means-

```<code>Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class java.lang.Double' with class 'java.lang.Class' to class 'double'
    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToNumber(DefaultTypeTransformation.java:163)
    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.doubleUnbox(DefaultTypeTransformation.java:88)
    at ScriptImplementor.evaluate(script15126616543572010791987.groovy:1)
    at GroovyStackOverflow.main(GroovyStackOverflow.java:33)
</code>```

After uncommenting this code //sb.append(codeSnippet.replaceAll("\n", " ")); it works. But please suggest a better way to handle it. Also why it does not give error while parsing class?
And what other surprises I can expect like this?

答:
You hit a difference between Java and Groovy.

In Java a statement is ended by a semicolon.

In Groovy a satement is ended by a semicolon, or by a linebreak if the statement already is a complete statement.

In your case this means the code

```<code>double calculatedAnswer = (Double)
contextMap.get("doubleValue") * (Double)contextMap.get("doubleValue")
</code>```

is two statements.

The first of these statements is double calculatedAnswer = (Double).

In Groovy you can also omit .class to reference a class, so Double.class can be written as Double.

So what you do in that statement is, that you assign the Double class object to a double variable. The parentheses are just no-ops here.

This of course fails like the message says, as the Double class object cannot be case automatically to a double.

You can explicitly escape a linebreak to make it not end a statement like in

```<code>double calculatedAnswer = (Double)\
contextMap.get("doubleValue") * (Double)contextMap.get("doubleValue")
</code>```

which would work like you expected.

But there can of course be other cases where Groovy and Java are different.

Always remember, the Groovy syntax is close to the Java syntax, yet not identical.

Afair each valid Java code is also valid Groovy code, but not necessarily with the exact same meaning as you can see in this example.

Body:
Currently I am working on a way to run java code in string form. So here is how I did it.

import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;

public class GroovyStackOverflow {

    public static void main(String[] args) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        String codeSnippet = "double calculatedAnswer = (Double)"
                + "contextMap.get(\"doubleValue\") * (Double)contextMap.get(\"doubleValue\");"
                + " calculatedAnswer = Math.sqrt(calculatedAnswer); "
                + "calculatedAnswer = calculatedAnswer * calculatedAnswer;"
                + "System.out.println(calculatedAnswer);"
                + " return calculatedAnswer;";
        StringBuilder sb = new StringBuilder();
        sb.append("public class ScriptImplementor implements ScriptEvaluator { public Object evaluate(Map contextMap) {");
        sb.append(codeSnippet);
        sb.append("} }");
        Class<?> clazz = gcl.parseClass(sb.toString());
        ScriptEvaluator scriptEvaluator = null;
        double calculatedAnswer = 100.0;
        try {
            Map contextMap = new HashMap();
            contextMap.put("doubleValue", (double)100.0);
            contextMap.put("threadId", "thread"+100);
            contextMap.put("hashCode", 100);
            scriptEvaluator = (ScriptEvaluator) clazz.newInstance();
            scriptEvaluator.evaluate(contextMap);;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

public interface ScriptEvaluator {
    public Object evaluate(Map contextMap);
}

Problem is that it fails in following case.

import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;

public class GroovyStackOverflow {

    public static void main(String[] args) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        String codeSnippet = "double calculatedAnswer = (Double)"
                + "\n "
                + "contextMap.get(\"doubleValue\") * (Double)contextMap.get(\"doubleValue\");"
                + " calculatedAnswer = Math.sqrt(calculatedAnswer); "
                + "calculatedAnswer = calculatedAnswer * calculatedAnswer;"
                + "System.out.println(calculatedAnswer);"
                + " return calculatedAnswer;";
        StringBuilder sb = new StringBuilder();
        sb.append("public class ScriptImplementor implements ScriptEvaluator { public Object evaluate(Map contextMap) {");
        //sb.append(codeSnippet.replaceAll("\n", " "));
        sb.append(codeSnippet);
        sb.append("} }");
        Class<?> clazz = gcl.parseClass(sb.toString());
        ScriptEvaluator scriptEvaluator = null;
        double calculatedAnswer = 100.0;
        try {
            Map contextMap = new HashMap();
            contextMap.put("doubleValue", (double)100.0);
            contextMap.put("threadId", "thread"+100);
            contextMap.put("hashCode", 100);
            scriptEvaluator = (ScriptEvaluator) clazz.newInstance();
            scriptEvaluator.evaluate(contextMap);;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
public interface ScriptEvaluator {
    public Object evaluate(Map contextMap);
}

I don't understand why it fails and what this error message means-

Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class java.lang.Double' with class 'java.lang.Class' to class 'double'
    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToNumber(DefaultTypeTransformation.java:163)
    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.doubleUnbox(DefaultTypeTransformation.java:88)
    at ScriptImplementor.evaluate(script15126616543572010791987.groovy:1)
    at GroovyStackOverflow.main(GroovyStackOverflow.java:33)

After uncommenting this code //sb.append(codeSnippet.replaceAll("\n", " ")); it works. But please suggest a better way to handle it. Also why it does not give error while parsing class?
And what other surprises I can expect like this?

Body:
You hit a difference between Java and Groovy.

In Java a statement is ended by a semicolon.

In Groovy a satement is ended by a semicolon, or by a linebreak if the statement already is a complete statement.

In your case this means the code

double calculatedAnswer = (Double)
contextMap.get("doubleValue") * (Double)contextMap.get("doubleValue")

is two statements.

The first of these statements is double calculatedAnswer = (Double).

In Groovy you can also omit .class to reference a class, so Double.class can be written as Double.

So what you do in that statement is, that you assign the Double class object to a double variable. The parentheses are just no-ops here.

This of course fails like the message says, as the Double class object cannot be case automatically to a double.

You can explicitly escape a linebreak to make it not end a statement like in

double calculatedAnswer = (Double)\
contextMap.get("doubleValue") * (Double)contextMap.get("doubleValue")

which would work like you expected.

But there can of course be other cases where Groovy and Java are different.

Always remember, the Groovy syntax is close to the Java syntax, yet not identical.

Afair each valid Java code is also valid Groovy code, but not necessarily with the exact same meaning as you can see in this example.


问:
Vectorising a Matlab code to pick specific indices of a matrix
I have a matrix A in Matlab of dimension Nx(N-1), e.g.

```<code>N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20];
</code>```

I want to rearrange the elements of A in a certain way. Specifically I want to create a matrix B of dimension (N-1)xN such that:

for i=1,...,N,

B(:,i) collects

1) the first i-1 elements of the i-1th column of A and

2) the last N-i elements of the ith column of A.

Notice that for i=1 the i-1th column of A does not exist and therefore 1) is skipped; similarly,  for i=N theith column of A does not exist and therefore 2) is skipped.

In the example above

```<code>B=[5  1  2  3  4
   9  10 6  7  8
   13 14 15 11 12
   17 18 19 20 16];
</code>```

This code does what I want. I am asking your help to vectorise it in an efficient way.

```<code>B=zeros(N-1,N);
for i=1:N
    if i>1 && i<N
    step1=A(1:i-1,i-1);
    step2=A(i+1:N,i);
    B(:,i)=[step1;step2];
    elseif i==1
    B(:,i)=A(i+1:N,i);
    elseif i==N
    B(:,i)=A(1:i-1,i-1);
    end
end
</code>```

答:
Extract the lower and upper triangular matrices of A. Then reassemble them with a "diagonal shift":

```<code>u = triu(A);
l = tril(A,-1);
B = padarray(u(1:end-1,:),[0 1],'pre') + padarray(l(2:end,:),[0 1],'post');
</code>```

Body:
I have a matrix A in Matlab of dimension Nx(N-1), e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20];

I want to rearrange the elements of A in a certain way. Specifically I want to create a matrix B of dimension (N-1)xN such that:

for i=1,...,N,

B(:,i) collects

1) the first i-1 elements of the i-1th column of A and

2) the last N-i elements of the ith column of A.

Notice that for i=1 the i-1th column of A does not exist and therefore 1) is skipped; similarly,  for i=N theith column of A does not exist and therefore 2) is skipped.

In the example above

B=[5  1  2  3  4
   9  10 6  7  8
   13 14 15 11 12
   17 18 19 20 16];

This code does what I want. I am asking your help to vectorise it in an efficient way.

B=zeros(N-1,N);
for i=1:N
    if i>1 && i<N
    step1=A(1:i-1,i-1);
    step2=A(i+1:N,i);
    B(:,i)=[step1;step2];
    elseif i==1
    B(:,i)=A(i+1:N,i);
    elseif i==N
    B(:,i)=A(1:i-1,i-1);
    end
end

Body:
Extract the lower and upper triangular matrices of A. Then reassemble them with a "diagonal shift":

u = triu(A);
l = tril(A,-1);
B = padarray(u(1:end-1,:),[0 1],'pre') + padarray(l(2:end,:),[0 1],'post');


问:
OpenSSL on Mac OS X for SHA-256 signature algorithm
I want to create a self-signed certificate (root ca) with OpenSSL. The signature algorithm needs to be a ECDSA signature with SHA-256 hash.
On my Mac OS X (Yosemite), I have OpenSSL version 0.9.8zc (from Oct 15, 2014) installed. When I call openssl ciphers -v on the command line, it seems that my current OpenSSL version does not support SHA2 (with SHA-256 etc.).

```<code>DHE-RSA-AES256-SHA      SSLv3 Kx=DH       Au=RSA  Enc=AES(256)  Mac=SHA1
DHE-DSS-AES256-SHA      SSLv3 Kx=DH       Au=DSS  Enc=AES(256)  Mac=SHA1
AES256-SHA              SSLv3 Kx=RSA      Au=RSA  Enc=AES(256)  Mac=SHA1
EDH-RSA-DES-CBC3-SHA    SSLv3 Kx=DH       Au=RSA  Enc=3DES(168) Mac=SHA1
EDH-DSS-DES-CBC3-SHA    SSLv3 Kx=DH       Au=DSS  Enc=3DES(168) Mac=SHA1
DES-CBC3-SHA            SSLv3 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=SHA1
DES-CBC3-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=MD5
DHE-RSA-AES128-SHA      SSLv3 Kx=DH       Au=RSA  Enc=AES(128)  Mac=SHA1
DHE-DSS-AES128-SHA      SSLv3 Kx=DH       Au=DSS  Enc=AES(128)  Mac=SHA1
AES128-SHA              SSLv3 Kx=RSA      Au=RSA  Enc=AES(128)  Mac=SHA1
DHE-RSA-SEED-SHA        SSLv3 Kx=DH       Au=RSA  Enc=SEED(128) Mac=SHA1
DHE-DSS-SEED-SHA        SSLv3 Kx=DH       Au=DSS  Enc=SEED(128) Mac=SHA1
SEED-SHA                SSLv3 Kx=RSA      Au=RSA  Enc=SEED(128) Mac=SHA1
RC2-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=RC2(128)  Mac=MD5
RC4-SHA                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=SHA1
RC4-MD5                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5
RC4-MD5                 SSLv2 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5
EDH-RSA-DES-CBC-SHA     SSLv3 Kx=DH       Au=RSA  Enc=DES(56)   Mac=SHA1
EDH-DSS-DES-CBC-SHA     SSLv3 Kx=DH       Au=DSS  Enc=DES(56)   Mac=SHA1
DES-CBC-SHA             SSLv3 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=SHA1
DES-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=MD5
EXP-EDH-RSA-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=RSA  Enc=DES(40)   Mac=SHA1 export
EXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=DSS  Enc=DES(40)   Mac=SHA1 export
EXP-DES-CBC-SHA         SSLv3 Kx=RSA(512) Au=RSA  Enc=DES(40)   Mac=SHA1 export
EXP-RC2-CBC-MD5         SSLv3 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
EXP-RC2-CBC-MD5         SSLv2 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
EXP-RC4-MD5             SSLv3 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
EXP-RC4-MD5             SSLv2 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
</code>```

The latest version of OpenSSL seems to be 1.0.2, but the source available at https://www.openssl.org/source/ does not seem to be compilable for OS X, since the file "Install.MacOS" says right at the beginning:

"Thanks to Roy Wood  initial support for Mac OS (pre
X) is now provided."

My try to install it nevertheless resulted in some errors on the command line.

Can anyone tell me if it is somehow possible to use the SHA-256 signature algorithm with an OpenSSL installation on Yosemite? It seems odd to me if this would not be possible, but I am no expert in this field.
Hoping for a good hint!

答:
On OSX El Capitan

Install homebrew (see http://brew.sh/index.html)

Install newest openssl version with command brew install openssl

Run /usr/local/opt/openssl/bin/openssl sha256

Brew now refuses to link openssh to /usr/local/bin even if you use the --force option so you have to run openssh from the brew install location or link to it yourself.

Body:
I want to create a self-signed certificate (root ca) with OpenSSL. The signature algorithm needs to be a ECDSA signature with SHA-256 hash.
On my Mac OS X (Yosemite), I have OpenSSL version 0.9.8zc (from Oct 15, 2014) installed. When I call openssl ciphers -v on the command line, it seems that my current OpenSSL version does not support SHA2 (with SHA-256 etc.).

DHE-RSA-AES256-SHA      SSLv3 Kx=DH       Au=RSA  Enc=AES(256)  Mac=SHA1
DHE-DSS-AES256-SHA      SSLv3 Kx=DH       Au=DSS  Enc=AES(256)  Mac=SHA1
AES256-SHA              SSLv3 Kx=RSA      Au=RSA  Enc=AES(256)  Mac=SHA1
EDH-RSA-DES-CBC3-SHA    SSLv3 Kx=DH       Au=RSA  Enc=3DES(168) Mac=SHA1
EDH-DSS-DES-CBC3-SHA    SSLv3 Kx=DH       Au=DSS  Enc=3DES(168) Mac=SHA1
DES-CBC3-SHA            SSLv3 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=SHA1
DES-CBC3-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=MD5
DHE-RSA-AES128-SHA      SSLv3 Kx=DH       Au=RSA  Enc=AES(128)  Mac=SHA1
DHE-DSS-AES128-SHA      SSLv3 Kx=DH       Au=DSS  Enc=AES(128)  Mac=SHA1
AES128-SHA              SSLv3 Kx=RSA      Au=RSA  Enc=AES(128)  Mac=SHA1
DHE-RSA-SEED-SHA        SSLv3 Kx=DH       Au=RSA  Enc=SEED(128) Mac=SHA1
DHE-DSS-SEED-SHA        SSLv3 Kx=DH       Au=DSS  Enc=SEED(128) Mac=SHA1
SEED-SHA                SSLv3 Kx=RSA      Au=RSA  Enc=SEED(128) Mac=SHA1
RC2-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=RC2(128)  Mac=MD5
RC4-SHA                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=SHA1
RC4-MD5                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5
RC4-MD5                 SSLv2 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5
EDH-RSA-DES-CBC-SHA     SSLv3 Kx=DH       Au=RSA  Enc=DES(56)   Mac=SHA1
EDH-DSS-DES-CBC-SHA     SSLv3 Kx=DH       Au=DSS  Enc=DES(56)   Mac=SHA1
DES-CBC-SHA             SSLv3 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=SHA1
DES-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=MD5
EXP-EDH-RSA-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=RSA  Enc=DES(40)   Mac=SHA1 export
EXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=DSS  Enc=DES(40)   Mac=SHA1 export
EXP-DES-CBC-SHA         SSLv3 Kx=RSA(512) Au=RSA  Enc=DES(40)   Mac=SHA1 export
EXP-RC2-CBC-MD5         SSLv3 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
EXP-RC2-CBC-MD5         SSLv2 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
EXP-RC4-MD5             SSLv3 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
EXP-RC4-MD5             SSLv2 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export

The latest version of OpenSSL seems to be 1.0.2, but the source available at https://www.openssl.org/source/ does not seem to be compilable for OS X, since the file "Install.MacOS" says right at the beginning:

"Thanks to Roy Wood  initial support for Mac OS (pre
X) is now provided."

My try to install it nevertheless resulted in some errors on the command line.

Can anyone tell me if it is somehow possible to use the SHA-256 signature algorithm with an OpenSSL installation on Yosemite? It seems odd to me if this would not be possible, but I am no expert in this field.
Hoping for a good hint!


问:
Can I test my iPad app on someone else's iPad?
I'm developing an iPad app, and want to test it on a friend's iPad.  Before I buy the $99 developer account, I just want to make sure that this will work.

Does my friend's device have to use my apple ID in order to install the provisioning profile?  Is there anything that would change about his iPad (besides the ability to install my app, of course)?

Thanks!

答: maybe this could help, http://testflightapp.com/  Free OTA installation...  </p>

ContentLicense: CC BY-SA 2.5


问:
If input is not the specific type, print.. (Python)
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!

```<code>#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue

    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")
</code>```

答:
You can try a simple while loop that waits until the user has entered a digit. For example,

```<code>guess = input("Enter a number: ") # type(guess) gives "str"

while(not guess.isdigit()):  # Checks if the string is not a numeric digit
    guess = input("You did not enter a number. Please re-enter: ")
</code>```

That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).

You can then convert the digit to an integer as before:

```<code>guess = int(guess)
</code>```

For example, consider the following cases:

```<code>"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer
</code>```

Body:
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!

#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue

    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")

Body:
You can try a simple while loop that waits until the user has entered a digit. For example,

guess = input("Enter a number: ") # type(guess) gives "str"

while(not guess.isdigit()):  # Checks if the string is not a numeric digit
    guess = input("You did not enter a number. Please re-enter: ")

That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).

You can then convert the digit to an integer as before:

guess = int(guess)

For example, consider the following cases:

"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer


问:
Use FineUploader with Typescript (Angular2 project)
I'm facing a problem to use fineuploader library to my angular2 project. I Don't find a way to implement it without using fineuploader.js directly in the index html file. Is there an example of implementation for Typescript? Thank u

```<code>***Gulpfile***

    gulp.task('restore:fine-uploader', function () {
    gulp.src([
        'node_modules/fine-uploader/**/*.*'
    ]).pipe(gulp.dest(libs + 'fine-uploader'));
    });

    gulp.task('restore',
    [
    'restore:core-js',
    'restore:zone.js',
    'restore:reflect-metadata',
    'restore:systemjs',
    'restore:rxjs',
    'restore:angular-in-memory-web-api',
    'restore:angular',
    'restore:bootstrap',
    'restore:ng2-pagination',
    'restore:fine-uploader'
    ]);

***Systemjs.js***

    (function (global) {
    System.config({
        baseURL: "/",
        paths: {
            // paths serve as alias
            'npm:': './libs/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic':
                'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'ng2-pagination': 'npm:ng2-pagination',
            'fine-uploader': 'npm:fine-uploader',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            },
            fineUploader: {
                main: 'fine-uploader/fine-uploader.min',
                defaultExtension: 'js'
            },
}
    });
})(this);
</code>```

****upload.component.ts****

```<code>import { Component } from '@angular/core';
import { FineUploader } from 'fineUploader';
@Component({
    selector: 'app-upload',
    templateUrl: './app/upload/upload.component.html'
})
export class UploadComponent {

}
</code>```

答:
Official solution can be found on Fine Uploader page.

You just need to install the Fine Uploader via npm and initialize in your typescript file like this (for UI mode and traditional endpoints):

```<code>import { FineUploader } from 'fine-uploader';

let uploader = new FineUploader({...})
</code>```

Note that Fine Uploader template doesn't have to be in

Body:
I'm facing a problem to use fineuploader library to my angular2 project. I Don't find a way to implement it without using fineuploader.js directly in the index html file. Is there an example of implementation for Typescript? Thank u

***Gulpfile***

    gulp.task('restore:fine-uploader', function () {
    gulp.src([
        'node_modules/fine-uploader/**/*.*'
    ]).pipe(gulp.dest(libs + 'fine-uploader'));
    });

    gulp.task('restore',
    [
    'restore:core-js',
    'restore:zone.js',
    'restore:reflect-metadata',
    'restore:systemjs',
    'restore:rxjs',
    'restore:angular-in-memory-web-api',
    'restore:angular',
    'restore:bootstrap',
    'restore:ng2-pagination',
    'restore:fine-uploader'
    ]);

***Systemjs.js***

    (function (global) {
    System.config({
        baseURL: "/",
        paths: {
            // paths serve as alias
            'npm:': './libs/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic':
                'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'ng2-pagination': 'npm:ng2-pagination',
            'fine-uploader': 'npm:fine-uploader',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            },
            fineUploader: {
                main: 'fine-uploader/fine-uploader.min',
                defaultExtension: 'js'
            },
}
    });
})(this);

****upload.component.ts****

import { Component } from '@angular/core';
import { FineUploader } from 'fineUploader';
@Component({
    selector: 'app-upload',
    templateUrl: './app/upload/upload.component.html'
})
export class UploadComponent {

}

Body:
Official solution can be found on Fine Uploader page.

You just need to install the Fine Uploader via npm and initialize in your typescript file like this (for UI mode and traditional endpoints):

import { FineUploader } from 'fine-uploader';

let uploader = new FineUploader({...})

Note that Fine Uploader template doesn't have to be in <script> tags in index.html file. Adding a template inside <div hidden> tag with a specific id in any component would be enough.


问:
Rewrite foreach loops into linq query?
I tried to rewrite the following loops in one "elegant" linq query but no success!

```<code>foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }
</code>```

Could anyone suggest a query (if even possible)?

Thanks in advance

答:
i think it's gonna be something like that :

Obj1 obj1 = list1.SingleOrDefault(l => l.list2.(j => j.prop == 1))

Plus prop is attribute of the 2nd List not the 1st List.

You can found a great course of linq in this Link

Title: Rewrite foreach loops into linq query?

Body:
I tried to rewrite the following loops in one "elegant" linq query but no success!

foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }

Could anyone suggest a query (if even possible)?

Thanks in advance


答:
You can do something like below. Modify this query as per your need</p>

```<code>DECLARE @StartHash char(40) = 'bf75a42b88782b0dc084a5642cc98876ad3ef41d'
DECLARE @EndHash char(40) = 'b3052d0c950a731d7221bab8825ba5787a9eb372'

    ;WITH CTE AS
    (
        SELECT *, ROW_NUMBER() OVER(ORDER BY H.HashDate) N
        FROM HASHTABLE H
    )
    SELECT [Hash], [HashDate]
    FROM CTE
    WHERE EXISTS(SELECT 1 FROM CTE CMAX WHERE CMAX.[Hash] = @EndHash AND CMAX.N <= CTE.N)
          AND EXISTS(SELECT 1 FROM CTE CMIN WHERE CMIN.[Hash] = @StartHash AND CMIN.N >= CTE.N)
</code>```

Title: SQL Server : find rows between 2 rows

Body:
Modifying to more accurately represent the problem I am trying to solve. I over simplified the question the first time.

I have 2 SQL Server 2012 tables with data like so:

Table CommitBranch

Hash                                        HashDate                 BranchName
-----------------------------------------------------------------------------------
4191737d919e599690a8b9efd691ffc5165908f9    2013-01-26 15:24:44.000  B1
4191737d919e599690a8b9efd691ffc5165908f9    2013-01-26 15:24:44.000  B2
59503c5e22914b4926e8b5352ef254ebf67b1245    2013-01-28 19:28:12.000  B1
b3052d0c950a731d7221bab8825ba5787a9eb372    2013-01-29 17:05:02.000  B1
54752ce05b2c7784ff22c6161f9ecc33d4b1149f    2013-01-29 17:42:16.000  B2
d7c008d807d3439539b98dccf4c93ee6bc33405c    2013-01-29 21:29:32.000  B1
c890ca6ab1735ee391407ca80aa789a560632709    2013-01-31 04:39:57.000  B2
bf75a42b88782b0dc084a5642cc98876ad3ef41d    2013-01-31 04:41:30.000  B3
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B1
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B2
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B3

Hash and BranchName are the primary key.

Table Build

BuildID  LastCommitHash                            BranchName
------------------------------------------------------------
1        4191737d919e599690a8b9efd691ffc5165908f9  B1
2        b3052d0c950a731d7221bab8825ba5787a9eb372  B1
3        e54982d42d2b87e35d47536cd2017c18117afc28  B1
4        bf75a42b88782b0dc084a5642cc98876ad3ef41d  B3

LastCommitHash is the Hash of the CommitBranch record used at the time the Build was created. Note that not every Commit hash will appear in the Build table - there will be gaps as the example shows (59503c5e22914b4926e8b5352ef254ebf67b1245 is missing, for example). The only reliable sorting for the CommitBranch table is by HashDate - the hashes themselves are effectively random.

I am trying to write a query to be used in a view called BuildCommit to give me all of the CommitBranch records between the LastCommitHash in the Build table and the Previous Build's LastCommitHash (but not including that build). I'm basically trying to answer the question, what Commits have been made on this branch since the last build.

The query would return the following:

BuildID CommitHash                                  BranchName
------------------------------------------------------------------
1       4191737d919e599690a8b9efd691ffc5165908f9    B1
2       b3052d0c950a731d7221bab8825ba5787a9eb372    B1
2       59503c5e22914b4926e8b5352ef254ebf67b1245    B1
3       e54982d42d2b87e35d47536cd2017c18117afc28    B1
3       d7c008d807d3439539b98dccf4c93ee6bc33405c    B1
4       bf75a42b88782b0dc084a5642cc98876ad3ef41d    B3
...

Edge conditions (like there being only 1 build for a branch and therefore no "since" record) must be dealt with.

Answers to date have been helpful and appreciated, but unfortunately not quite what I needed due to me oversimplifying the original question.

Thanks in advance!

Body:
You can do something like below. Modify this query as per your need

DECLARE @StartHash char(40) = 'bf75a42b88782b0dc084a5642cc98876ad3ef41d'
DECLARE @EndHash char(40) = 'b3052d0c950a731d7221bab8825ba5787a9eb372'

    ;WITH CTE AS
    (
        SELECT *, ROW_NUMBER() OVER(ORDER BY H.HashDate) N
        FROM HASHTABLE H
    )
    SELECT [Hash], [HashDate]
    FROM CTE
    WHERE EXISTS(SELECT 1 FROM CTE CMAX WHERE CMAX.[Hash] = @EndHash AND CMAX.N <= CTE.N)
          AND EXISTS(SELECT 1 FROM CTE CMIN WHERE CMIN.[Hash] = @StartHash AND CMIN.N >= CTE.N)


问:
How to Iterate Twice over Map values in Java
I know there are other solutions out there but nothing is working for me.

Question: In my main method, I group together IDs by rating and make the rating the key and the rest of the info the value as a List. When I create the hashmap and put in the lists I can accurately print the contents of the hashmap. However, once I pass the map the evaluate method, the values are lost and I cannot iterate in the same way that I did in the main method, even though the logic is the same. I am not experienced with the Map class in java. Can somebody please help me figure out why when I pass the Map to my evaluate method that I can no longer iterate the Map?

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

public class Evaluate {

public static double grandTotal;

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

    FileInputStream fs = new FileInputStream("testInput.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fs));
    FileInputStream fs2 = new FileInputStream("testTest.txt");
    BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));
    String line;
    String line2;
    String[] bloop;
    String bleep;
    String flooper;
    String splitter;
    String[] splitInput;
    List<String> oneStarList= new ArrayList<String>();
    List<String> twoStarList= new ArrayList<String>();
    List<String> threeStarList= new ArrayList<String>();
    List<String> fourStarList= new ArrayList<String>();
    List<String> fiveStarList= new ArrayList<String>();
    List<String> values2 = new ArrayList<String>();

    try {

        while ((line=br.readLine()) != null) {
            bloop = new String[10];
            bloop = line.split("\\s+");
            bleep = bloop[1].toString();
            flooper = (bloop[0]+" "+bloop[2]+" "+bloop[3]+" "+bloop[4]);
            if (bleep.equals("1")){
                oneStarList.add(flooper);
            }
            else if (bleep.equals("2")){
                twoStarList.add(flooper);
            }
            else if (bleep.equals("3")){
                threeStarList.add(flooper);
            }
            else if (bleep.equals("4")){
                fourStarList.add(flooper);
            }
            else if (bleep.equals("5")){
                fiveStarList.add(flooper);
            }
            grandTotal+=(Double.parseDouble(bloop[2]));
        }
    }
    catch (Exception e){
    }

    Map<String,List<String>> hmap = new HashMap<String,List<String>>();

    hmap.put("1",oneStarList);
    hmap.put("2", twoStarList);
    hmap.put("3", threeStarList);
    hmap.put("4", fourStarList);
    hmap.put("5", fiveStarList);

    while ((line2=br2.readLine()) != null) {
        splitInput = new String[5];
        splitInput = line2.split("\\s+");
        evaluate(splitInput[0],splitInput[1],hmap);
    }
    br.close();
    br2.close();
}

public static void evaluate(String movID, String usrID, Map<String,List<String>> hash) throws Exception{

    FileWriter fw = new FileWriter("outputTest.txt");
    BufferedWriter bwr = new BufferedWriter(fw);
    List<String> values = new ArrayList<String>();
    List<String> outputList = new ArrayList<String>();
    String[] floop;
    String fleep;
    int movIDtotal=0;
    int usrIDtotal=0;
    int totalValues=0;
    double pmovIDStar=0;
    double pusrIDStar=0;
    double pmovID=0;
    double pusrID=0;
    double numID=0;
    double keyTotalProb=0;
    String keyOutputStr;
    String keyHold;

    final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();

    for (String key : hash.keySet()){
        values = hash.get(key);
        System.out.println(key + ":");
        for (int i=0;i<values.size();i++){
            System.out.println(values.get(i));
            floop = new String[5];
            fleep = values.get(i);
            floop = fleep.split("\\s+");
            if (movID.equals(floop[0])){
                movIDtotal++;
                totalValues++;
            }
            if (usrID.equals(floop[0])){
                usrIDtotal++;
                totalValues++;
            }
        }
        values.clear();
    }

    for (Map.Entry<String, List<String>> entry: entries){
        values= entry.getValue();
        keyHold = entry.getKey();
        for (int j=0;j<values.size();j++){

            floop = new String[5];
            fleep = values.get(j);
            floop = fleep.split("\\s+");
            if (movID.equals(floop[0])){
                pmovIDStar = Double.parseDouble(floop[3]);
                numID = Double.parseDouble(floop[1]);
                pmovID = (numID/movIDtotal);
            }
            if (usrID.equals(floop[0])){
                pusrIDStar = Double.parseDouble(floop[3]);
                numID = Double.parseDouble(floop[1]);
                pusrID = (numID/usrIDtotal);
            }
        }
        keyTotalProb = ((totalValues/grandTotal)*(pmovIDStar)*(pusrIDStar))/(pusrID*pmovID);
        keyOutputStr = Double.toString(keyTotalProb);
        outputList.add(keyHold);
        outputList.add(keyOutputStr);
        values.clear();
    }

    double max = Double.MIN_VALUE;
    for (int m=0;m<outputList.size();m+=2){
        double coolguy = Double.parseDouble(outputList.get(m+1));
        int index = 0;
        if(coolguy>max){
            max = coolguy;
            index = m;
        }

        try {
            bwr.write(String.format("%-1s %-1s %-1s%n", movID,usrID,outputList.get(index)));
            bwr.close();
            fw.close();
        }
        catch(Exception e) {

        }
    }
}
</code>```

}

Backup info: I'm trying to build a java program that essentially performs the final stage of the Naive Bayes algorithm to predict user ratings (1-5) for movies. I have used MapReduce to train data and now I have an input file where each line contains a string containing information in this order without the commas (movie or user id,rating , number of times rating and ID occur together in total, number of times ID occurs in total, probability that ID and rating occur together out of all ratings for ID). Essentially this is the classification stage.

答:
never suppress excetions. especially when you do coding/debugging.

catch (Exception e){    } is very bad practice

When you do:

final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();

it does not copy hash.entrySet to entries. It creates another reference to it.
 same is for values= entry.getValue();

then what do you expect after your first loop (and others too)?
when you do:

values.clear();

your values gone from the lists which are in hash and since entries is just a reference to hash.entrySet() you have what you've done - empty lists.

Body:
I know there are other solutions out there but nothing is working for me.

Question: In my main method, I group together IDs by rating and make the rating the key and the rest of the info the value as a List. When I create the hashmap and put in the lists I can accurately print the contents of the hashmap. However, once I pass the map the evaluate method, the values are lost and I cannot iterate in the same way that I did in the main method, even though the logic is the same. I am not experienced with the Map class in java. Can somebody please help me figure out why when I pass the Map to my evaluate method that I can no longer iterate the Map?

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

public class Evaluate {

public static double grandTotal;

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

    FileInputStream fs = new FileInputStream("testInput.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fs));
    FileInputStream fs2 = new FileInputStream("testTest.txt");
    BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));
    String line;
    String line2;
    String[] bloop;
    String bleep;
    String flooper;
    String splitter;
    String[] splitInput;
    List<String> oneStarList= new ArrayList<String>();
    List<String> twoStarList= new ArrayList<String>();
    List<String> threeStarList= new ArrayList<String>();
    List<String> fourStarList= new ArrayList<String>();
    List<String> fiveStarList= new ArrayList<String>();
    List<String> values2 = new ArrayList<String>();

    try {

        while ((line=br.readLine()) != null) {
            bloop = new String[10];
            bloop = line.split("\\s+");
            bleep = bloop[1].toString();
            flooper = (bloop[0]+" "+bloop[2]+" "+bloop[3]+" "+bloop[4]);
            if (bleep.equals("1")){
                oneStarList.add(flooper);
            }
            else if (bleep.equals("2")){
                twoStarList.add(flooper);
            }
            else if (bleep.equals("3")){
                threeStarList.add(flooper);
            }
            else if (bleep.equals("4")){
                fourStarList.add(flooper);
            }
            else if (bleep.equals("5")){
                fiveStarList.add(flooper);
            }
            grandTotal+=(Double.parseDouble(bloop[2]));
        }
    }
    catch (Exception e){
    }

    Map<String,List<String>> hmap = new HashMap<String,List<String>>();

    hmap.put("1",oneStarList);
    hmap.put("2", twoStarList);
    hmap.put("3", threeStarList);
    hmap.put("4", fourStarList);
    hmap.put("5", fiveStarList);

    while ((line2=br2.readLine()) != null) {
        splitInput = new String[5];
        splitInput = line2.split("\\s+");
        evaluate(splitInput[0],splitInput[1],hmap);
    }
    br.close();
    br2.close();
}

public static void evaluate(String movID, String usrID, Map<String,List<String>> hash) throws Exception{

    FileWriter fw = new FileWriter("outputTest.txt");
    BufferedWriter bwr = new BufferedWriter(fw);
    List<String> values = new ArrayList<String>();
    List<String> outputList = new ArrayList<String>();
    String[] floop;
    String fleep;
    int movIDtotal=0;
    int usrIDtotal=0;
    int totalValues=0;
    double pmovIDStar=0;
    double pusrIDStar=0;
    double pmovID=0;
    double pusrID=0;
    double numID=0;
    double keyTotalProb=0;
    String keyOutputStr;
    String keyHold;

    final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();

    for (String key : hash.keySet()){
        values = hash.get(key);
        System.out.println(key + ":");
        for (int i=0;i<values.size();i++){
            System.out.println(values.get(i));
            floop = new String[5];
            fleep = values.get(i);
            floop = fleep.split("\\s+");
            if (movID.equals(floop[0])){
                movIDtotal++;
                totalValues++;
            }
            if (usrID.equals(floop[0])){
                usrIDtotal++;
                totalValues++;
            }
        }
        values.clear();
    }

    for (Map.Entry<String, List<String>> entry: entries){
        values= entry.getValue();
        keyHold = entry.getKey();
        for (int j=0;j<values.size();j++){

            floop = new String[5];
            fleep = values.get(j);
            floop = fleep.split("\\s+");
            if (movID.equals(floop[0])){
                pmovIDStar = Double.parseDouble(floop[3]);
                numID = Double.parseDouble(floop[1]);
                pmovID = (numID/movIDtotal);
            }
            if (usrID.equals(floop[0])){
                pusrIDStar = Double.parseDouble(floop[3]);
                numID = Double.parseDouble(floop[1]);
                pusrID = (numID/usrIDtotal);
            }
        }
        keyTotalProb = ((totalValues/grandTotal)*(pmovIDStar)*(pusrIDStar))/(pusrID*pmovID);
        keyOutputStr = Double.toString(keyTotalProb);
        outputList.add(keyHold);
        outputList.add(keyOutputStr);
        values.clear();
    }

    double max = Double.MIN_VALUE;
    for (int m=0;m<outputList.size();m+=2){
        double coolguy = Double.parseDouble(outputList.get(m+1));
        int index = 0;
        if(coolguy>max){
            max = coolguy;
            index = m;
        }

        try {
            bwr.write(String.format("%-1s %-1s %-1s%n", movID,usrID,outputList.get(index)));
            bwr.close();
            fw.close();
        }
        catch(Exception e) {

        }
    }
}

}

Backup info: I'm trying to build a java program that essentially performs the final stage of the Naive Bayes algorithm to predict user ratings (1-5) for movies. I have used MapReduce to train data and now I have an input file where each line contains a string containing information in this order without the commas (movie or user id,rating , number of times rating and ID occur together in total, number of times ID occurs in total, probability that ID and rating occur together out of all ratings for ID). Essentially this is the classification stage.


问:
matching string to filenames with regex (java 1.6)
I have a bunch of images with names such as nineDiamonds.gif and aceHearts.gif along with a "Card" class for playing card faces.

In the constructor, I want to pass a String of the card name and be able to create a JPanel with the right image. Easy enough, but I want to be able to pass things such as:

"9 of hearts" => nineHearts.gif

"9 hearts" => nineHearts.gif

"nine of Hearts" => nineHearts.gif

Integer.toString(9) + "hearts" => nineHearts.gif

Integer.toString(1) + "hearts" => aceHearts.gif

"Ace of hearts" => aceHearts.gif

I understand I can overload the constructor and match things up with a switch and what not, but what I am really after is am elegant, functional style solution, something along the lines of:

```<code>String fileName = name.replaceAll("magic regex") + ".gif";
</code>```

Thanks!

答:
Here are some tips that should get you to a working solution:

Strip the word "of" using a regular expression with word boundaries (\bof\b)

Replace numeric strings with their respective words (can be done with a map defining the numbers (e.g. map[9] = "nine") and a for loop)

Use String.split() to split at word boundaries, then capatalise the all but the first word and re-join

So in the end, a regular expression alone is not the best solution as is often the case.

Body:
I have a bunch of images with names such as nineDiamonds.gif and aceHearts.gif along with a "Card" class for playing card faces.

In the constructor, I want to pass a String of the card name and be able to create a JPanel with the right image. Easy enough, but I want to be able to pass things such as:

"9 of hearts" => nineHearts.gif

"9 hearts" => nineHearts.gif

"nine of Hearts" => nineHearts.gif

Integer.toString(9) + "hearts" => nineHearts.gif

Integer.toString(1) + "hearts" => aceHearts.gif

"Ace of hearts" => aceHearts.gif

I understand I can overload the constructor and match things up with a switch and what not, but what I am really after is am elegant, functional style solution, something along the lines of:

String fileName = name.replaceAll("magic regex") + ".gif";

Thanks!


问:
GraphQL schema equivalent of this Json?
I'm newbie to GraphQL, and was wondering if someone could help me figure out what is the equivalent of below JSON into GraphQL schema:

```<code>[
 {
   "id": "1",
   "name": "A",
   "fldDef": [
    {
      "name": "f1",
      "type": "str",
      "opt": false
    },
    {
      "name": "f2",
      "type": "bool"
    }]
 },
 {
    "id": "2",
    "name": "B",
    "fldDef": [
     {
       "name": "f3",
       "type": "str",
       "opt": true
     },
     {
       "name": "f4",
       "type": "str",
       "opt": true
     }]
  }
]
</code>```

So far I managed to map above response to below object:

```<code>  public class FldDef {

     private String name, type;
     private boolean opt;
     // getters & setters
 }

 public class Product {

    private String id, name;
    private Map<String, FldDef> fldDef;

   // getters & setters

 }
</code>```

Then my schema looks like below, but the problem I'm having is as a part of Product object, I've a Map which I would like to get the schema right for it, but I'm having difficulty getting the schema right!

```<code>type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
 }
</code>```

I get below exception:

Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type!  Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type.  This allows for reverse-lookup by java class in interfaces and union types.

Note: I'm working with Java eco-system (graphql-java)

答:
You can try some changes as below:

Schema definition:

```<code>type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: [FldDef]! // make it as Collection of FldDef
 }
</code>```

Java Class:

```<code>public class FldDef {

    private String name;
    private String type;
    private boolean opt;
    // getters & setters
}

public class Product {

    private String id;
    private String name;
    private List<FldDef> fldDef; // Change to List of FldDef
    // getters & setters
}
</code>```

Hope it can help.

Title: GraphQL schema equivalent of this Json?

Body:
I'm newbie to GraphQL, and was wondering if someone could help me figure out what is the equivalent of below JSON into GraphQL schema:

[
 {
   "id": "1",
   "name": "A",
   "fldDef": [
    {
      "name": "f1",
      "type": "str",
      "opt": false
    },
    {
      "name": "f2",
      "type": "bool"
    }]
 },
 {
    "id": "2",
    "name": "B",
    "fldDef": [
     {
       "name": "f3",
       "type": "str",
       "opt": true
     },
     {
       "name": "f4",
       "type": "str",
       "opt": true
     }]
  }
]

So far I managed to map above response to below object:

  public class FldDef {

     private String name, type;
     private boolean opt;
     // getters & setters
 }

 public class Product {

    private String id, name;
    private Map<String, FldDef> fldDef;

   // getters & setters

 }

Then my schema looks like below, but the problem I'm having is as a part of Product object, I've a Map which I would like to get the schema right for it, but I'm having difficulty getting the schema right!

type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
 }

I get below exception:

Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type!  Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type.  This allows for reverse-lookup by java class in interfaces and union types.

Note: I'm working with Java eco-system (graphql-java)

Body:
You can try some changes as below:

Schema definition:

type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: [FldDef]! // make it as Collection of FldDef
 }

Java Class:

public class FldDef {

    private String name;
    private String type;
    private boolean opt;
    // getters & setters
}

public class Product {

    private String id;
    private String name;
    private List<FldDef> fldDef; // Change to List of FldDef
    // getters & setters
}

Hope it can help.


问:
In c++ why is pass by reference is directed by callee rather than by caller
In c++, the function signature defines that it will take the arguments by reference or value. Isn’t it the caller should decide what it wants to pass by reference or value?
Suppose caller does not want the function to modify its values, and is unsure of what the calle is doing inside its function. Then the caller does not have a right to say that the arguments should not be modified.

How is this C++ definiton justified?

答:
It is done this way to make overloading more versatile, and because the interpreter decides which function to call based off what parameters you pass.  Say I have two functions

```<code>void add(int* a, int* b){
    *a= *a+*b;
    *b = *a;
}
</code>```

and

```<code>int add(const& int a, const& int b){
    return a+b;
}
</code>```

These are two very different ways of adding two numbers.  When I call these functions the interpreter knows which one to call based off what I pass it.

Body:
It is done this way to make overloading more versatile, and because the interpreter decides which function to call based off what parameters you pass.  Say I have two functions

void add(int* a, int* b){
    *a= *a+*b;
    *b = *a;
}

and

int add(const& int a, const& int b){
    return a+b;
}

These are two very different ways of adding two numbers.  When I call these functions the interpreter knows which one to call based off what I pass it.


问:
gulp-babel and the strict mode
I use the "gulp-babel" before uglifying my js files. The module blocks the minification because a third party js script is not "strict mode" compilant.

```<code>// Include gulp
var gulp = require('gulp');
var baseDir = "./";
var jsources = [
    "sites/**/js/*.js",
    "!sites/**/js/*.min.js"
];

// Include Plugins
var jshint = require('gulp-jshint');
var babel = require('gulp-babel');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

// Minify JS
gulp.task('scripts', function () {
    return gulp.src(jsources, { base: baseDir })
        .pipe(babel({
            presets: [
                ['env', { modules: false }]
            ]
        }))
        .pipe(uglify().on('error', function (e) { console.log(e); }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(baseDir));
});
</code>```

As result I obtain an error because a js file is not strict mode compilant:

I don't want to modify that third-party file to make it strict mode compilant. How can I disable that check for that file or another similar files?

Just now the minification is blocked because of that kind of files...

I tried

to install the "transform-remove-strict-mode" plugin and then do

```<code>.pipe(babel({
    "presets": ["env"],
    "plugins": ["transform-remove-strict-mode"]
}))
</code>```

I also tried the

```<code>.pipe(babel({
    presets: [
        ["es2015", { "modules": false }]
    ]
}))
</code>```

but the output is still the same...

答:
Maybe it's too late but you could try to do it this way:</p>

```<code>gulp.task('foo_task', () => {

gulp.src('foo/src/path')

    .pipe(concat('foo_file.js')
    .pipe(babel({ presets: ['env'] }))
    .pipe(uglify())
    .pipe(gulp.dest('foo/dist/path'))

    .pipe(concat([ '/dist/path', 'foo/src/path' ]))
    .pipe(uglify())
    .pipe(gulp.dest('foo/dist/path'))

});
</code>```

Title: gulp-babel and the strict mode

Body:
I use the "gulp-babel" before uglifying my js files. The module blocks the minification because a third party js script is not "strict mode" compilant.

// Include gulp
var gulp = require('gulp');
var baseDir = "./";
var jsources = [
    "sites/**/js/*.js",
    "!sites/**/js/*.min.js"
];

// Include Plugins
var jshint = require('gulp-jshint');
var babel = require('gulp-babel');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

// Minify JS
gulp.task('scripts', function () {
    return gulp.src(jsources, { base: baseDir })
        .pipe(babel({
            presets: [
                ['env', { modules: false }]
            ]
        }))
        .pipe(uglify().on('error', function (e) { console.log(e); }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(baseDir));
});

As result I obtain an error because a js file is not strict mode compilant:

I don't want to modify that third-party file to make it strict mode compilant. How can I disable that check for that file or another similar files?

Just now the minification is blocked because of that kind of files...

I tried

to install the "transform-remove-strict-mode" plugin and then do

.pipe(babel({
    "presets": ["env"],
    "plugins": ["transform-remove-strict-mode"]
}))

I also tried the

.pipe(babel({
    presets: [
        ["es2015", { "modules": false }]
    ]
}))

but the output is still the same...

Body:
Maybe it's too late but you could try to do it this way:

gulp.task('foo_task', () => {

gulp.src('foo/src/path')

    .pipe(concat('foo_file.js')
    .pipe(babel({ presets: ['env'] }))
    .pipe(uglify())
    .pipe(gulp.dest('foo/dist/path'))

    .pipe(concat([ '/dist/path', 'foo/src/path' ]))
    .pipe(uglify())
    .pipe(gulp.dest('foo/dist/path'))

});


问:
Show div using button and hide it if click outside the div
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
  <button id="close-add">Close Div</button>
  <p> Show Me </p>
</div></code>```

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

答:
try this</p>

```<code> $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });
</code>```

Body:
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});

<button id="new-shipping'">Open Div</button>

  <button id="close-add">Close Div</button>

 Show Me

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

Body:
try this

 $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });


问:
Passing DropDown selected value along with other selected query result set
I have a form "test.cfm"  It passes values to an action page "testAction.cfm"!

test.cfm does the following:-

A drop down box “fruitsList”.

A query “qryFruits” that pulls data and then displays the query-result set

“Add” button for every query-result set

How it should work:-

The dropdown “fruitsList” is to be selected.

Once the “Add” button in the result list is selected the “query-result set -CurrentRow” value is to be passed.

Add button is passing the “query-resultset -CurrentRow”  value but NOT the "Drop down" Value.

How to pass the “dropdown- selected-value”?

```<code>    <!--- test.cfm --->
    <script type="text/javascript" >
          function assign_fruits()
         //
         {
           var a = document.fruitsForm.fruitsList.selectedIndex;
           document.getElementById('salesForce').value = document.fruitsForm.fruitsList.options[a].value;
           }
        </script>

    <form name="fruitsForm" >
    <table>
      <tr>
       <td>
        <select name="fruitsList" onChange="assign_fruits()">
         <option disabled="true">select One
         <option value="m1">apple
         <option value="m2" selected>orange
         <option value="m3">banana
         <option value="m4">grape
         <option value="m5">mango
        </select>
       </td>
<!--- Trying to assign the DD-value to an input field --->
 <input  name="salesForce" value="">
      </tr>
     <cfquery name="qryFruits" datasoure="#dsn#">
      Select values from Fruits_Table
     </cfquery>
     <cfloop startrow="1" endrow="#qryFruits.recordcount#" query="qryFruits">
      <cfoutput>
      <tr>
       <td><a href="testAction.cfm">Add</a></td>
      </tr>
      </cfoutput>
     </cfloop>
    </table>

    </form>
</code>```

答:
Your javascript says
var a = document.fruitsForm.fruits.selectedIndex;
but your form field isn't called 'fruits', it's called fruitsList.  Try

```<code>document.fruitsForm.fruitsList.selectedIndex;
</code>```

instead.

ContentLicense: CC BY-SA 4.0

Body:
I have a form "test.cfm"  It passes values to an action page "testAction.cfm"!

test.cfm does the following:-

A drop down box “fruitsList”.

A query “qryFruits” that pulls data and then displays the query-result set

“Add” button for every query-result set

How it should work:-

The dropdown “fruitsList” is to be selected.

Once the “Add” button in the result list is selected the “query-result set -CurrentRow” value is to be passed.

Add button is passing the “query-resultset -CurrentRow”  value but NOT the "Drop down" Value.

How to pass the “dropdown- selected-value”?

    <form name="fruitsForm" >

        <select name="fruitsList" onChange="assign_fruits()">
         <option disabled="true">select One
         <option value="m1">apple
         <option value="m2" selected>orange
         <option value="m3">banana
         <option value="m4">grape
         <option value="m5">mango
        </select>

 <input  name="salesForce" value="">

     <cfquery name="qryFruits" datasoure="#dsn#">
      Select values from Fruits_Table
     </cfquery>
     <cfloop startrow="1" endrow="#qryFruits.recordcount#" query="qryFruits">
      <cfoutput>

       Add

      </cfoutput>
     </cfloop>

    </form>

Body:
Your javascript says
var a = document.fruitsForm.fruits.selectedIndex;
but your form field isn't called 'fruits', it's called fruitsList.  Try

document.fruitsForm.fruitsList.selectedIndex;

instead.