问:
Filling two overlapping areas in d3.js
I am drawing two lines overlapping (sometimes the first one is higher, and sometimes the second one has higher value on y axis) each other in d3.js. I want to fill the areas under the lines in such a way that:

The area under the lower one will be gray.

The area between the two lines will be either green or red. If the first line has higher value, it will be green and if the second has higher value, it will be red.

For example

For now I only have this:

```<code>var area = d3.area()
            .curve(d3.curveBasis)
            .x(function(d) { return margin.left + x(d.date); })
            .y0(margin.top + height)
            .y1(function(d) { return y(d.value); });
</code>```

But this does not work, of course. I know about stacked area charts but I think I need some tricks to make this work.

答:
You can do it overlapping 2 areas:

```<code>// a gray area which finish in the minimun data
var greyArea = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(Math.min(d["First Line"], d["Second Line"])); });

// a colored area which in the value of the first line
var coloredArea = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y1(function(d) { return y(d["First Line"]); });
</code>```

then draw them with,

```<code>svg.append("clipPath")
  .attr("id", "clip-above")
  .append("path")
  .attr("d", coloredArea.y0(height));

svg.append("clipPath")
  .attr("id", "clip-below")
  .append("path")
  .attr("d", coloredArea.y0(0));

svg.append("path")
  .attr("class", "area below")
  .attr("clip-path", "url(#clip-below)")
  .attr("d", coloredArea.y0(function(d) { return y(d["Second Line"]); }));

svg.append("path")
  .attr("class", "area above")
  .attr("clip-path", "url(#clip-above)")
  .attr("d", coloredArea);

svg.append("path")
  .attr("class", "area gray")
  .attr("d", greyArea.y0(height));
</code>```

Working demo JSFiddle Demo

var data = [{"date":"20111001","First Line":"63.4","Second Line":"62.7"},{"date":"20111002","First Line":"58.0","Second Line":"59.9"},{"date":"20111003","First Line":"53.3","Second Line":"59.1"},{"date":"20111004","First Line":"55.7","Second Line":"58.8"},{"date":"20111005","First Line":"64.2","Second Line":"58.7"},{"date":"20111006","First Line":"58.8","Second Line":"57.0"},{"date":"20111007","First Line":"57.9","Second Line":"56.7"},{"date":"20111008","First Line":"61.8","Second Line":"56.8"},{"date":"20111009","First Line":"69.3","Second Line":"56.7"},{"date":"20111010","First Line":"71.2","Second Line":"60.1"},{"date":"20111011","First Line":"68.7","Second Line":"61.1"},{"date":"20111012","First Line":"61.8","Second Line":"61.5"},{"date":"20111013","First Line":"63.0","Second Line":"64.3"},{"date":"20111014","First Line":"66.9","Second Line":"67.1"},{"date":"20111015","First Line":"61.7","Second Line":"64.6"},{"date":"20111016","First Line":"61.8","Second Line":"61.6"},{"date":"20111017","First Line":"62.8","Second Line":"61.1"},{"date":"20111018","First Line":"60.8","Second Line":"59.2"},{"date":"20111019","First Line":"62.1","Second Line":"58.9"},{"date":"20111020","First Line":"65.1","Second Line":"57.2"},{"date":"20111021","First Line":"55.6","Second Line":"56.4"},{"date":"20111022","First Line":"54.4","Second Line":"60.7"},{"date":"20111023","First Line":"54.4","Second Line":"65.1"},{"date":"20111024","First Line":"54.8","Second Line":"60.9"},{"date":"20111025","First Line":"57.9","Second Line":"56.1"},{"date":"20111026","First Line":"54.6","Second Line":"54.6"},{"date":"20111027","First Line":"54.4","Second Line":"56.1"},{"date":"20111028","First Line":"42.5","Second Line":"58.1"},{"date":"20111029","First Line":"40.9","Second Line":"57.5"},{"date":"20111030","First Line":"38.6","Second Line":"57.7"},{"date":"20111031","First Line":"44.2","Second Line":"55.1"},{"date":"20111101","First Line":"49.6","Second Line":"57.9"},{"date":"20111102","First Line":"47.2","Second Line":"64.6"},{"date":"20111103","First Line":"50.1","Second Line":"56.2"},{"date":"20111104","First Line":"50.1","Second Line":"50.5"},{"date":"20111105","First Line":"43.5","Second Line":"51.3"},{"date":"20111106","First Line":"43.8","Second Line":"52.6"},{"date":"20111107","First Line":"48.9","Second Line":"51.4"},{"date":"20111108","First Line":"55.5","Second Line":"50.6"},{"date":"20111109","First Line":"53.7","Second Line":"54.6"},{"date":"20111110","First Line":"57.7","Second Line":"55.6"},{"date":"20111111","First Line":"48.5","Second Line":"53.9"},{"date":"20111112","First Line":"46.8","Second Line":"54.0"},{"date":"20111113","First Line":"51.1","Second Line":"53.8"},{"date":"20111114","First Line":"56.8","Second Line":"53.5"},{"date":"20111115","First Line":"59.7","Second Line":"53.4"},{"date":"20111116","First Line":"56.5","Second Line":"52.2"},{"date":"20111117","First Line":"49.6","Second Line":"52.7"},{"date":"20111118","First Line":"41.5","Second Line":"53.1"},{"date":"20111119","First Line":"44.3","Second Line":"49.0"},{"date":"20111120","First Line":"54.0","Second Line":"50.4"},{"date":"20111121","First Line":"54.1","Second Line":"51.1"},{"date":"20111122","First Line":"49.4","Second Line":"52.3"},{"date":"20111123","First Line":"50.0","Second Line":"54.6"},{"date":"20111124","First Line":"44.0","Second Line":"55.1"},{"date":"20111125","First Line":"50.3","Second Line":"51.5"},{"date":"20111126","First Line":"52.1","Second Line":"53.6"},{"date":"20111127","First Line":"49.6","Second Line":"52.3"},{"date":"20111128","First Line":"57.2","Second Line":"51.0"},{"date":"20111129","First Line":"59.1","Second Line":"49.5"},{"date":"20111130","First Line":"50.6","Second Line":"49.8"},{"date":"20111201","First Line":"44.3","Second Line":"60.4"},{"date":"20111202","First Line":"43.9","Second Line":"62.2"},{"date":"20111203","First Line":"42.1","Second Line":"58.3"},{"date":"20111204","First Line":"43.9","Second Line":"52.7"},{"date":"20111205","First Line":"50.2","Second Line":"51.5"},{"date":"20111206","First Line":"54.2","Second Line":"49.9"},{"date":"20111207","First Line":"54.6","Second Line":"48.6"},{"date":"20111208","First Line":"43.4","Second Line":"46.4"},{"date":"20111209","First Line":"42.2","Second Line":"49.8"},{"date":"20111210","First Line":"45.0","Second Line":"52.1"},{"date":"20111211","First Line":"33.8","Second Line":"48.8"},{"date":"20111212","First Line":"36.8","Second Line":"47.4"},{"date":"20111213","First Line":"38.6","Second Line":"47.2"},{"date":"20111214","First Line":"41.9","Second Line":"46.1"},{"date":"20111215","First Line":"49.6","Second Line":"48.8"},{"date":"20111216","First Line":"50.2","Second Line":"47.9"},{"date":"20111217","First Line":"40.6","Second Line":"49.8"},{"date":"20111218","First Line":"29.1","Second Line":"49.1"},{"date":"20111219","First Line":"33.7","Second Line":"48.3"},{"date":"20111220","First Line":"45.8","Second Line":"49.3"},{"date":"20111221","First Line":"47.4","Second Line":"48.4"},{"date":"20111222","First Line":"54.4","Second Line":"53.3"},{"date":"20111223","First Line":"47.8","Second Line":"47.5"},{"date":"20111224","First Line":"34.9","Second Line":"47.9"},{"date":"20111225","First Line":"35.9","Second Line":"48.9"},{"date":"20111226","First Line":"43.6","Second Line":"45.9"},{"date":"20111227","First Line":"42.9","Second Line":"47.2"},{"date":"20111228","First Line":"46.2","Second Line":"48.9"},{"date":"20111229","First Line":"30.8","Second Line":"50.9"},{"date":"20111230","First Line":"40.8","Second Line":"52.9"},{"date":"20111231","First Line":"49.8","Second Line":"50.1"},{"date":"20120101","First Line":"46.3","Second Line":"53.9"},{"date":"20120102","First Line":"43.2","Second Line":"53.1"},{"date":"20120103","First Line":"30.3","Second Line":"49.7"},{"date":"20120104","First Line":"19.2","Second Line":"52.7"},{"date":"20120105","First Line":"32.1","Second Line":"52.6"},{"date":"20120106","First Line":"41.2","Second Line":"49.0"},{"date":"20120107","First Line":"47.0","Second Line":"51.0"},{"date":"20120108","First Line":"46.0","Second Line":"56.8"},{"date":"20120109","First Line":"34.7","Second Line":"52.3"},{"date":"20120110","First Line":"39.4","Second Line":"51.6"},{"date":"20120111","First Line":"40.4","Second Line":"49.8"},{"date":"20120112","First Line":"45.4","Second Line":"51.9"},{"date":"20120113","First Line":"40.7","Second Line":"53.7"},{"date":"20120114","First Line":"30.4","Second Line":"52.9"},{"date":"20120115","First Line":"23.9","Second Line":"49.7"},{"date":"20120116","First Line":"22.6","Second Line":"45.3"},{"date":"20120117","First Line":"39.8","Second Line":"43.6"},{"date":"20120118","First Line":"43.2","Second Line":"45.0"},{"date":"20120119","First Line":"26.3","Second Line":"47.3"},{"date":"20120120","First Line":"32.8","Second Line":"51.4"},{"date":"20120121","First Line":"27.4","Second Line":"53.7"},{"date":"20120122","First Line":"25.0","Second Line":"48.3"},{"date":"20120123","First Line":"39.4","Second Line":"52.9"},{"date":"20120124","First Line":"48.7","Second Line":"49.1"},{"date":"20120125","First Line":"43.0","Second Line":"52.1"},{"date":"20120126","First Line":"37.1","Second Line":"53.6"},{"date":"20120127","First Line":"48.2","Second Line":"50.4"},{"date":"20120128","First Line":"43.7","Second Line":"50.3"},{"date":"20120129","First Line":"40.1","Second Line":"53.8"},{"date":"20120130","First Line":"38.0","Second Line":"51.9"},{"date":"20120131","First Line":"43.5","Second Line":"50.0"},{"date":"20120201","First Line":"50.4","Second Line":"50.0"},{"date":"20120202","First Line":"45.8","Second Line":"51.3"},{"date":"20120203","First Line":"37.5","Second Line":"51.5"},{"date":"20120204","First Line":"40.8","Second Line":"52.0"},{"date":"20120205","First Line":"36.5","Second Line":"53.8"},{"date":"20120206","First Line":"39.1","Second Line":"54.6"},{"date":"20120207","First Line":"43.2","Second Line":"54.3"},{"date":"20120208","First Line":"36.5","Second Line":"51.9"},{"date":"20120209","First Line":"36.5","Second Line":"53.8"},{"date":"20120210","First Line":"38.3","Second Line":"53.9"},{"date":"20120211","First Line":"36.9","Second Line":"52.3"},{"date":"20120212","First Line":"29.7","Second Line":"50.1"},{"date":"20120213","First Line":"33.1","Second Line":"49.5"},{"date":"20120214","First Line":"39.6","Second Line":"48.6"},{"date":"20120215","First Line":"42.3","Second Line":"49.9"},{"date":"20120216","First Line":"39.7","Second Line":"52.4"},{"date":"20120217","First Line":"46.0","Second Line":"49.9"},{"date":"20120218","First Line":"41.2","Second Line":"51.6"},{"date":"20120219","First Line":"39.8","Second Line":"47.8"},{"date":"20120220","First Line":"38.1","Second Line":"48.7"},{"date":"20120221","First Line":"37.1","Second Line":"49.7"},{"date":"20120222","First Line":"45.5","Second Line":"53.4"},{"date":"20120223","First Line":"50.6","Second Line":"54.1"},{"date":"20120224","First Line":"42.7","Second Line":"55.9"},{"date":"20120225","First Line":"42.6","Second Line":"51.7"},{"date":"20120226","First Line":"36.9","Second Line":"47.7"},{"date":"20120227","First Line":"40.9","Second Line":"45.4"},{"date":"20120228","First Line":"45.9","Second Line":"47.0"},{"date":"20120229","First Line":"40.7","Second Line":"49.8"},{"date":"20120301","First Line":"41.3","Second Line":"48.9"},{"date":"20120302","First Line":"36.8","Second Line":"48.1"},{"date":"20120303","First Line":"47.6","Second Line":"50.7"},{"date":"20120304","First Line":"44.2","Second Line":"55.0"},{"date":"20120305","First Line":"38.5","Second Line":"48.8"},{"date":"20120306","First Line":"32.9","Second Line":"48.4"},{"date":"20120307","First Line":"43.3","Second Line":"49.9"},{"date":"20120308","First Line":"51.2","Second Line":"49.2"},{"date":"20120309","First Line":"47.8","Second Line":"51.7"},{"date":"20120310","First Line":"37.2","Second Line":"49.3"},{"date":"20120311","First Line":"42.9","Second Line":"50.0"},{"date":"20120312","First Line":"48.8","Second Line":"48.6"},{"date":"20120313","First Line":"52.6","Second Line":"53.9"},{"date":"20120314","First Line":"60.5","Second Line":"55.2"},{"date":"20120315","First Line":"47.2","Second Line":"55.9"},{"date":"20120316","First Line":"44.7","Second Line":"54.6"},{"date":"20120317","First Line":"48.2","Second Line":"48.2"},{"date":"20120318","First Line":"48.2","Second Line":"47.1"},{"date":"20120319","First Line":"53.1","Second Line":"45.8"},{"date":"20120320","First Line":"57.8","Second Line":"49.7"},{"date":"20120321","First Line":"57.5","Second Line":"51.4"},{"date":"20120322","First Line":"57.3","Second Line":"51.4"},{"date":"20120323","First Line":"61.7","Second Line":"48.4"},{"date":"20120324","First Line":"55.8","Second Line":"49.0"},{"date":"20120325","First Line":"48.4","Second Line":"46.4"},{"date":"20120326","First Line":"49.8","Second Line":"49.7"},{"date":"20120327","First Line":"39.6","Second Line":"54.1"},{"date":"20120328","First Line":"49.7","Second Line":"54.6"},{"date":"20120329","First Line":"56.8","Second Line":"52.3"},{"date":"20120330","First Line":"46.5","Second Line":"54.5"},{"date":"20120331","First Line":"42.2","Second Line":"56.2"},{"date":"20120401","First Line":"45.3","Second Line":"51.1"},{"date":"20120402","First Line":"48.1","Second Line":"50.5"},{"date":"20120403","First Line":"51.2","Second Line":"52.2"},{"date":"20120404","First Line":"61.0","Second Line":"50.6"},{"date":"20120405","First Line":"50.7","Second Line":"47.9"},{"date":"20120406","First Line":"48.0","Second Line":"47.4"},{"date":"20120407","First Line":"51.1","Second Line":"49.4"},{"date":"20120408","First Line":"55.7","Second Line":"50.0"},{"date":"20120409","First Line":"58.3","Second Line":"51.3"},{"date":"20120410","First Line":"55.0","Second Line":"53.8"},{"date":"20120411","First Line":"49.0","Second Line":"52.9"},{"date":"20120412","First Line":"51.7","Second Line":"53.9"},{"date":"20120413","First Line":"53.1","Second Line":"50.2"},{"date":"20120414","First Line":"55.2","Second Line":"50.9"},{"date":"20120415","First Line":"62.3","Second Line":"51.5"},{"date":"20120416","First Line":"62.9","Second Line":"51.9"},{"date":"20120417","First Line":"69.3","Second Line":"53.2"},{"date":"20120418","First Line":"59.0","Second Line":"53.0"},{"date":"20120419","First Line":"54.1","Second Line":"55.1"},{"date":"20120420","First Line":"56.5","Second Line":"55.8"},{"date":"20120421","First Line":"58.2","Second Line":"58.0"},{"date":"20120422","First Line":"52.4","Second Line":"52.8"},{"date":"20120423","First Line":"51.6","Second Line":"55.1"},{"date":"20120424","First Line":"49.3","Second Line":"57.9"},{"date":"20120425","First Line":"52.5","Second Line":"57.5"},{"date":"20120426","First Line":"50.5","Second Line":"55.3"},{"date":"20120427","First Line":"51.9","Second Line":"53.5"},{"date":"20120428","First Line":"47.4","Second Line":"54.7"},{"date":"20120429","First Line":"54.1","Second Line":"54.0"},{"date":"20120430","First Line":"51.9","Second Line":"53.4"},{"date":"20120501","First Line":"57.4","Second Line":"52.7"},{"date":"20120502","First Line":"53.7","Second Line":"50.7"},{"date":"20120503","First Line":"53.1","Second Line":"52.6"},{"date":"20120504","First Line":"57.2","Second Line":"53.4"},{"date":"20120505","First Line":"57.0","Second Line":"53.1"},{"date":"20120506","First Line":"56.6","Second Line":"56.5"},{"date":"20120507","First Line":"54.6","Second Line":"55.3"},{"date":"20120508","First Line":"57.9","Second Line":"52.0"},{"date":"20120509","First Line":"59.2","Second Line":"52.4"},{"date":"20120510","First Line":"61.1","Second Line":"53.4"},{"date":"20120511","First Line":"59.7","Second Line":"53.1"},{"date":"20120512","First Line":"64.1","Second Line":"49.9"},{"date":"20120513","First Line":"65.3","Second Line":"52.0"},{"date":"20120514","First Line":"64.2","Second Line":"56.0"},{"date":"20120515","First Line":"62.0","Second Line":"53.0"},{"date":"20120516","First Line":"63.8","Second Line":"51.0"},{"date":"20120517","First Line":"64.5","Second Line":"51.4"},{"date":"20120518","First Line":"61.0","Second Line":"52.2"},{"date":"20120519","First Line":"62.6","Second Line":"52.4"},{"date":"20120520","First Line":"66.2","Second Line":"54.5"},{"date":"20120521","First Line":"62.7","Second Line":"52.8"},{"date":"20120522","First Line":"63.7","Second Line":"53.9"},{"date":"20120523","First Line":"66.4","Second Line":"56.5"},{"date":"20120524","First Line":"64.5","Second Line":"54.7"},{"date":"20120525","First Line":"65.4","Second Line":"52.5"},{"date":"20120526","First Line":"69.4","Second Line":"52.1"},{"date":"20120527","First Line":"71.9","Second Line":"52.2"},{"date":"20120528","First Line":"74.4","Second Line":"52.9"},{"date":"20120529","First Line":"75.9","Second Line":"52.1"},{"date":"20120530","First Line":"72.9","Second Line":"52.1"},{"date":"20120531","First Line":"72.5","Second Line":"53.3"},{"date":"20120601","First Line":"67.2","Second Line":"54.8"},{"date":"20120602","First Line":"68.3","Second Line":"54.0"},{"date":"20120603","First Line":"67.7","Second Line":"52.3"},{"date":"20120604","First Line":"61.9","Second Line":"55.3"},{"date":"20120605","First Line":"58.3","Second Line":"53.5"},{"date":"20120606","First Line":"61.7","Second Line":"54.1"},{"date":"20120607","First Line":"66.7","Second Line":"53.9"},{"date":"20120608","First Line":"68.7","Second Line":"54.4"},{"date":"20120609","First Line":"72.2","Second Line":"55.0"},{"date":"20120610","First Line":"72.6","Second Line":"60.0"},{"date":"20120611","First Line":"69.2","Second Line":"57.2"},{"date":"20120612","First Line":"66.9","Second Line":"55.1"},{"date":"20120613","First Line":"66.7","Second Line":"53.3"},{"date":"20120614","First Line":"67.7","Second Line":"53.4"},{"date":"20120615","First Line":"68.5","Second Line":"54.6"},{"date":"20120616","First Line":"67.5","Second Line":"57.0"},{"date":"20120617","First Line":"64.2","Second Line":"55.6"},{"date":"20120618","First Line":"61.7","Second Line":"52.5"},{"date":"20120619","First Line":"66.4","Second Line":"53.9"},{"date":"20120620","First Line":"77.9","Second Line":"55.3"},{"date":"20120621","First Line":"88.3","Second Line":"53.3"},{"date":"20120622","First Line":"82.2","Second Line":"54.1"},{"date":"20120623","First Line":"77.0","Second Line":"55.2"},{"date":"20120624","First Line":"75.4","Second Line":"55.8"},{"date":"20120625","First Line":"70.9","Second Line":"56.8"},{"date":"20120626","First Line":"65.9","Second Line":"57.5"},{"date":"20120627","First Line":"73.5","Second Line":"57.7"},{"date":"20120628","First Line":"77.4","Second Line":"56.6"},{"date":"20120629","First Line":"79.6","Second Line":"56.4"},{"date":"20120630","First Line":"84.2","Second Line":"58.4"},{"date":"20120701","First Line":"81.8","Second Line":"58.8"},{"date":"20120702","First Line":"82.5","Second Line":"56.4"},{"date":"20120703","First Line":"80.2","Second Line":"56.5"},{"date":"20120704","First Line":"77.8","Second Line":"55.8"},{"date":"20120705","First Line":"86.1","Second Line":"54.8"},{"date":"20120706","First Line":"79.9","Second Line":"54.9"},{"date":"20120707","First Line":"83.5","Second Line":"54.7"},{"date":"20120708","First Line":"81.5","Second Line":"52.8"},{"date":"20120709","First Line":"77.8","Second Line":"53.7"},{"date":"20120710","First Line":"76.1","Second Line":"53.1"},{"date":"20120711","First Line":"76.3","Second Line":"52.7"},{"date":"20120712","First Line":"75.8","Second Line":"52.0"},{"date":"20120713","First Line":"77.2","Second Line":"53.4"},{"date":"20120714","First Line":"79.3","Second Line":"54.0"},{"date":"20120715","First Line":"78.9","Second Line":"54.0"},{"date":"20120716","First Line":"79.6","Second Line":"54.5"},{"date":"20120717","First Line":"83.3","Second Line":"56.7"},{"date":"20120718","First Line":"84.3","Second Line":"57.5"},{"date":"20120719","First Line":"75.1","Second Line":"57.1"},{"date":"20120720","First Line":"68.4","Second Line":"58.1"},{"date":"20120721","First Line":"68.4","Second Line":"57.6"},{"date":"20120722","First Line":"72.2","Second Line":"56.0"},{"date":"20120723","First Line":"75.6","Second Line":"56.6"},{"date":"20120724","First Line":"82.6","Second Line":"57.8"},{"date":"20120725","First Line":"78.4","Second Line":"57.5"},{"date":"20120726","First Line":"77.0","Second Line":"56.4"},{"date":"20120727","First Line":"79.4","Second Line":"55.3"},{"date":"20120728","First Line":"77.4","Second Line":"55.0"},{"date":"20120729","First Line":"72.5","Second Line":"55.6"},{"date":"20120730","First Line":"72.9","Second Line":"55.6"},{"date":"20120731","First Line":"73.6","Second Line":"55.9"},{"date":"20120801","First Line":"75.0","Second Line":"55.4"},{"date":"20120802","First Line":"77.7","Second Line":"54.4"},{"date":"20120803","First Line":"79.7","Second Line":"53.7"},{"date":"20120804","First Line":"79.6","Second Line":"54.1"},{"date":"20120805","First Line":"81.5","Second Line":"57.8"},{"date":"20120806","First Line":"80.0","Second Line":"58.2"},{"date":"20120807","First Line":"75.7","Second Line":"58.0"},{"date":"20120808","First Line":"77.8","Second Line":"57.0"},{"date":"20120809","First Line":"78.6","Second Line":"55.0"},{"date":"20120810","First Line":"77.8","Second Line":"54.8"},{"date":"20120811","First Line":"78.5","Second Line":"53.0"},{"date":"20120812","First Line":"78.8","Second Line":"52.5"},{"date":"20120813","First Line":"78.6","Second Line":"53.3"},{"date":"20120814","First Line":"76.8","Second Line":"53.9"},{"date":"20120815","First Line":"76.7","Second Line":"56.2"},{"date":"20120816","First Line":"75.9","Second Line":"57.1"},{"date":"20120817","First Line":"77.6","Second Line":"55.3"},{"date":"20120818","First Line":"72.6","Second Line":"56.2"},{"date":"20120819","First Line":"70.4","Second Line":"54.3"},{"date":"20120820","First Line":"71.8","Second Line":"53.1"},{"date":"20120821","First Line":"73.6","Second Line":"53.4"},{"date":"20120822","First Line":"74.7","Second Line":"54.5"},{"date":"20120823","First Line":"74.6","Second Line":"55.7"},{"date":"20120824","First Line":"76.0","Second Line":"54.8"},{"date":"20120825","First Line":"76.2","Second Line":"53.8"},{"date":"20120826","First Line":"73.4","Second Line":"56.5"},{"date":"20120827","First Line":"74.6","Second Line":"58.3"},{"date":"20120828","First Line":"79.4","Second Line":"58.7"},{"date":"20120829","First Line":"74.7","Second Line":"57.5"},{"date":"20120830","First Line":"73.5","Second Line":"55.9"},{"date":"20120831","First Line":"77.9","Second Line":"55.4"},{"date":"20120901","First Line":"80.7","Second Line":"55.7"},{"date":"20120902","First Line":"75.1","Second Line":"53.1"},{"date":"20120903","First Line":"73.5","Second Line":"53.5"},{"date":"20120904","First Line":"73.5","Second Line":"52.5"},{"date":"20120905","First Line":"77.7","Second Line":"54.5"},{"date":"20120906","First Line":"74.2","Second Line":"56.3"},{"date":"20120907","First Line":"76.0","Second Line":"56.4"},{"date":"20120908","First Line":"77.1","Second Line":"56.5"},{"date":"20120909","First Line":"69.7","Second Line":"56.4"},{"date":"20120910","First Line":"67.8","Second Line":"55.4"},{"date":"20120911","First Line":"64.0","Second Line":"56.2"},{"date":"20120912","First Line":"68.1","Second Line":"55.7"},{"date":"20120913","First Line":"69.3","Second Line":"54.3"},{"date":"20120914","First Line":"70.0","Second Line":"55.2"},{"date":"20120915","First Line":"69.3","Second Line":"54.3"},{"date":"20120916","First Line":"66.3","Second Line":"52.9"},{"date":"20120917","First Line":"67.0","Second Line":"54.8"},{"date":"20120918","First Line":"72.8","Second Line":"54.8"},{"date":"20120919","First Line":"67.2","Second Line":"56.8"},{"date":"20120920","First Line":"62.1","Second Line":"55.4"},{"date":"20120921","First Line":"64.0","Second Line":"55.8"},{"date":"20120922","First Line":"65.5","Second Line":"55.9"},{"date":"20120923","First Line":"65.7","Second Line":"52.8"},{"date":"20120924","First Line":"60.4","Second Line":"54.5"},{"date":"20120925","First Line":"63.2","Second Line":"53.3"},{"date":"20120926","First Line":"68.5","Second Line":"53.6"},{"date":"20120927","First Line":"69.2","Second Line":"52.1"},{"date":"20120928","First Line":"68.7","Second Line":"52.6"},{"date":"20120929","First Line":"62.5","Second Line":"53.9"},{"date":"20120930","First Line":"62.3","Second Line":"55.1"}];

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y%m%d").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(Math.min(d["First Line"], d["Second Line"])); });

var area = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y1(function(d) { return y(d["First Line"]); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
    d.date = parseDate(d.date);
    d["First Line"]= +d["First Line"];
    d["Second Line"] = +d["Second Line"];
});

x.domain(d3.extent(data, function(d) { return d.date; }));

y.domain([
  d3.min(data, function(d) { return Math.min(d["First Line"], d["Second Line"]); }),
  d3.max(data, function(d) { return Math.max(d["First Line"], d["Second Line"]); })
]);

svg.datum(data);

svg.append("clipPath")
  .attr("id", "clip-above")
  .append("path")
  .attr("d", area.y0(height));

svg.append("clipPath")
  .attr("id", "clip-below")
  .append("path")
  .attr("d", area.y0(0));

svg.append("path")
  .attr("class", "area below")
  .attr("clip-path", "url(#clip-below)")
  .attr("d", area.y0(function(d) { return y(d["Second Line"]); }));

svg.append("path")
  .attr("class", "area above")
  .attr("clip-path", "url(#clip-above)")
  .attr("d", area);

svg.append("path")
  .attr("class", "line")
  .attr("d", line.y0(height));

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Temperature (ºF)");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  /*display: none;*/
}

.area.below {
  fill: rgb(252,141,89);
  stroke: #000;
  stroke-width: 1px;
}

.area.above {
  fill: rgb(145,207,96);
  stroke: #000;
  stroke-width: 1px;
}

.line {
  fill: #ccc;
  stroke: #000;
  stroke-width: 0.5px;
}</code>```

```

Title: Filling two overlapping areas in d3.js

Body:
I am drawing two lines overlapping (sometimes the first one is higher, and sometimes the second one has higher value on y axis) each other in d3.js. I want to fill the areas under the lines in such a way that:

The area under the lower one will be gray.

The area between the two lines will be either green or red. If the first line has higher value, it will be green and if the second has higher value, it will be red.

For example

For now I only have this:

var area = d3.area()
            .curve(d3.curveBasis)
            .x(function(d) { return margin.left + x(d.date); })
            .y0(margin.top + height)
            .y1(function(d) { return y(d.value); });

But this does not work, of course. I know about stacked area charts but I think I need some tricks to make this work.

Body:
You can do it overlapping 2 areas:

// a gray area which finish in the minimun data
var greyArea = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(Math.min(d["First Line"], d["Second Line"])); });

// a colored area which in the value of the first line
var coloredArea = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y1(function(d) { return y(d["First Line"]); });

then draw them with,

svg.append("clipPath")
  .attr("id", "clip-above")
  .append("path")
  .attr("d", coloredArea.y0(height));

svg.append("clipPath")
  .attr("id", "clip-below")
  .append("path")
  .attr("d", coloredArea.y0(0));

svg.append("path")
  .attr("class", "area below")
  .attr("clip-path", "url(#clip-below)")
  .attr("d", coloredArea.y0(function(d) { return y(d["Second Line"]); }));

svg.append("path")
  .attr("class", "area above")
  .attr("clip-path", "url(#clip-above)")
  .attr("d", coloredArea);

svg.append("path")
  .attr("class", "area gray")
  .attr("d", greyArea.y0(height));

Working demo JSFiddle Demo

var data = [{"date":"20111001","First Line":"63.4","Second Line":"62.7"},{"date":"20111002","First Line":"58.0","Second Line":"59.9"},{"date":"20111003","First Line":"53.3","Second Line":"59.1"},{"date":"20111004","First Line":"55.7","Second Line":"58.8"},{"date":"20111005","First Line":"64.2","Second Line":"58.7"},{"date":"20111006","First Line":"58.8","Second Line":"57.0"},{"date":"20111007","First Line":"57.9","Second Line":"56.7"},{"date":"20111008","First Line":"61.8","Second Line":"56.8"},{"date":"20111009","First Line":"69.3","Second Line":"56.7"},{"date":"20111010","First Line":"71.2","Second Line":"60.1"},{"date":"20111011","First Line":"68.7","Second Line":"61.1"},{"date":"20111012","First Line":"61.8","Second Line":"61.5"},{"date":"20111013","First Line":"63.0","Second Line":"64.3"},{"date":"20111014","First Line":"66.9","Second Line":"67.1"},{"date":"20111015","First Line":"61.7","Second Line":"64.6"},{"date":"20111016","First Line":"61.8","Second Line":"61.6"},{"date":"20111017","First Line":"62.8","Second Line":"61.1"},{"date":"20111018","First Line":"60.8","Second Line":"59.2"},{"date":"20111019","First Line":"62.1","Second Line":"58.9"},{"date":"20111020","First Line":"65.1","Second Line":"57.2"},{"date":"20111021","First Line":"55.6","Second Line":"56.4"},{"date":"20111022","First Line":"54.4","Second Line":"60.7"},{"date":"20111023","First Line":"54.4","Second Line":"65.1"},{"date":"20111024","First Line":"54.8","Second Line":"60.9"},{"date":"20111025","First Line":"57.9","Second Line":"56.1"},{"date":"20111026","First Line":"54.6","Second Line":"54.6"},{"date":"20111027","First Line":"54.4","Second Line":"56.1"},{"date":"20111028","First Line":"42.5","Second Line":"58.1"},{"date":"20111029","First Line":"40.9","Second Line":"57.5"},{"date":"20111030","First Line":"38.6","Second Line":"57.7"},{"date":"20111031","First Line":"44.2","Second Line":"55.1"},{"date":"20111101","First Line":"49.6","Second Line":"57.9"},{"date":"20111102","First Line":"47.2","Second Line":"64.6"},{"date":"20111103","First Line":"50.1","Second Line":"56.2"},{"date":"20111104","First Line":"50.1","Second Line":"50.5"},{"date":"20111105","First Line":"43.5","Second Line":"51.3"},{"date":"20111106","First Line":"43.8","Second Line":"52.6"},{"date":"20111107","First Line":"48.9","Second Line":"51.4"},{"date":"20111108","First Line":"55.5","Second Line":"50.6"},{"date":"20111109","First Line":"53.7","Second Line":"54.6"},{"date":"20111110","First Line":"57.7","Second Line":"55.6"},{"date":"20111111","First Line":"48.5","Second Line":"53.9"},{"date":"20111112","First Line":"46.8","Second Line":"54.0"},{"date":"20111113","First Line":"51.1","Second Line":"53.8"},{"date":"20111114","First Line":"56.8","Second Line":"53.5"},{"date":"20111115","First Line":"59.7","Second Line":"53.4"},{"date":"20111116","First Line":"56.5","Second Line":"52.2"},{"date":"20111117","First Line":"49.6","Second Line":"52.7"},{"date":"20111118","First Line":"41.5","Second Line":"53.1"},{"date":"20111119","First Line":"44.3","Second Line":"49.0"},{"date":"20111120","First Line":"54.0","Second Line":"50.4"},{"date":"20111121","First Line":"54.1","Second Line":"51.1"},{"date":"20111122","First Line":"49.4","Second Line":"52.3"},{"date":"20111123","First Line":"50.0","Second Line":"54.6"},{"date":"20111124","First Line":"44.0","Second Line":"55.1"},{"date":"20111125","First Line":"50.3","Second Line":"51.5"},{"date":"20111126","First Line":"52.1","Second Line":"53.6"},{"date":"20111127","First Line":"49.6","Second Line":"52.3"},{"date":"20111128","First Line":"57.2","Second Line":"51.0"},{"date":"20111129","First Line":"59.1","Second Line":"49.5"},{"date":"20111130","First Line":"50.6","Second Line":"49.8"},{"date":"20111201","First Line":"44.3","Second Line":"60.4"},{"date":"20111202","First Line":"43.9","Second Line":"62.2"},{"date":"20111203","First Line":"42.1","Second Line":"58.3"},{"date":"20111204","First Line":"43.9","Second Line":"52.7"},{"date":"20111205","First Line":"50.2","Second Line":"51.5"},{"date":"20111206","First Line":"54.2","Second Line":"49.9"},{"date":"20111207","First Line":"54.6","Second Line":"48.6"},{"date":"20111208","First Line":"43.4","Second Line":"46.4"},{"date":"20111209","First Line":"42.2","Second Line":"49.8"},{"date":"20111210","First Line":"45.0","Second Line":"52.1"},{"date":"20111211","First Line":"33.8","Second Line":"48.8"},{"date":"20111212","First Line":"36.8","Second Line":"47.4"},{"date":"20111213","First Line":"38.6","Second Line":"47.2"},{"date":"20111214","First Line":"41.9","Second Line":"46.1"},{"date":"20111215","First Line":"49.6","Second Line":"48.8"},{"date":"20111216","First Line":"50.2","Second Line":"47.9"},{"date":"20111217","First Line":"40.6","Second Line":"49.8"},{"date":"20111218","First Line":"29.1","Second Line":"49.1"},{"date":"20111219","First Line":"33.7","Second Line":"48.3"},{"date":"20111220","First Line":"45.8","Second Line":"49.3"},{"date":"20111221","First Line":"47.4","Second Line":"48.4"},{"date":"20111222","First Line":"54.4","Second Line":"53.3"},{"date":"20111223","First Line":"47.8","Second Line":"47.5"},{"date":"20111224","First Line":"34.9","Second Line":"47.9"},{"date":"20111225","First Line":"35.9","Second Line":"48.9"},{"date":"20111226","First Line":"43.6","Second Line":"45.9"},{"date":"20111227","First Line":"42.9","Second Line":"47.2"},{"date":"20111228","First Line":"46.2","Second Line":"48.9"},{"date":"20111229","First Line":"30.8","Second Line":"50.9"},{"date":"20111230","First Line":"40.8","Second Line":"52.9"},{"date":"20111231","First Line":"49.8","Second Line":"50.1"},{"date":"20120101","First Line":"46.3","Second Line":"53.9"},{"date":"20120102","First Line":"43.2","Second Line":"53.1"},{"date":"20120103","First Line":"30.3","Second Line":"49.7"},{"date":"20120104","First Line":"19.2","Second Line":"52.7"},{"date":"20120105","First Line":"32.1","Second Line":"52.6"},{"date":"20120106","First Line":"41.2","Second Line":"49.0"},{"date":"20120107","First Line":"47.0","Second Line":"51.0"},{"date":"20120108","First Line":"46.0","Second Line":"56.8"},{"date":"20120109","First Line":"34.7","Second Line":"52.3"},{"date":"20120110","First Line":"39.4","Second Line":"51.6"},{"date":"20120111","First Line":"40.4","Second Line":"49.8"},{"date":"20120112","First Line":"45.4","Second Line":"51.9"},{"date":"20120113","First Line":"40.7","Second Line":"53.7"},{"date":"20120114","First Line":"30.4","Second Line":"52.9"},{"date":"20120115","First Line":"23.9","Second Line":"49.7"},{"date":"20120116","First Line":"22.6","Second Line":"45.3"},{"date":"20120117","First Line":"39.8","Second Line":"43.6"},{"date":"20120118","First Line":"43.2","Second Line":"45.0"},{"date":"20120119","First Line":"26.3","Second Line":"47.3"},{"date":"20120120","First Line":"32.8","Second Line":"51.4"},{"date":"20120121","First Line":"27.4","Second Line":"53.7"},{"date":"20120122","First Line":"25.0","Second Line":"48.3"},{"date":"20120123","First Line":"39.4","Second Line":"52.9"},{"date":"20120124","First Line":"48.7","Second Line":"49.1"},{"date":"20120125","First Line":"43.0","Second Line":"52.1"},{"date":"20120126","First Line":"37.1","Second Line":"53.6"},{"date":"20120127","First Line":"48.2","Second Line":"50.4"},{"date":"20120128","First Line":"43.7","Second Line":"50.3"},{"date":"20120129","First Line":"40.1","Second Line":"53.8"},{"date":"20120130","First Line":"38.0","Second Line":"51.9"},{"date":"20120131","First Line":"43.5","Second Line":"50.0"},{"date":"20120201","First Line":"50.4","Second Line":"50.0"},{"date":"20120202","First Line":"45.8","Second Line":"51.3"},{"date":"20120203","First Line":"37.5","Second Line":"51.5"},{"date":"20120204","First Line":"40.8","Second Line":"52.0"},{"date":"20120205","First Line":"36.5","Second Line":"53.8"},{"date":"20120206","First Line":"39.1","Second Line":"54.6"},{"date":"20120207","First Line":"43.2","Second Line":"54.3"},{"date":"20120208","First Line":"36.5","Second Line":"51.9"},{"date":"20120209","First Line":"36.5","Second Line":"53.8"},{"date":"20120210","First Line":"38.3","Second Line":"53.9"},{"date":"20120211","First Line":"36.9","Second Line":"52.3"},{"date":"20120212","First Line":"29.7","Second Line":"50.1"},{"date":"20120213","First Line":"33.1","Second Line":"49.5"},{"date":"20120214","First Line":"39.6","Second Line":"48.6"},{"date":"20120215","First Line":"42.3","Second Line":"49.9"},{"date":"20120216","First Line":"39.7","Second Line":"52.4"},{"date":"20120217","First Line":"46.0","Second Line":"49.9"},{"date":"20120218","First Line":"41.2","Second Line":"51.6"},{"date":"20120219","First Line":"39.8","Second Line":"47.8"},{"date":"20120220","First Line":"38.1","Second Line":"48.7"},{"date":"20120221","First Line":"37.1","Second Line":"49.7"},{"date":"20120222","First Line":"45.5","Second Line":"53.4"},{"date":"20120223","First Line":"50.6","Second Line":"54.1"},{"date":"20120224","First Line":"42.7","Second Line":"55.9"},{"date":"20120225","First Line":"42.6","Second Line":"51.7"},{"date":"20120226","First Line":"36.9","Second Line":"47.7"},{"date":"20120227","First Line":"40.9","Second Line":"45.4"},{"date":"20120228","First Line":"45.9","Second Line":"47.0"},{"date":"20120229","First Line":"40.7","Second Line":"49.8"},{"date":"20120301","First Line":"41.3","Second Line":"48.9"},{"date":"20120302","First Line":"36.8","Second Line":"48.1"},{"date":"20120303","First Line":"47.6","Second Line":"50.7"},{"date":"20120304","First Line":"44.2","Second Line":"55.0"},{"date":"20120305","First Line":"38.5","Second Line":"48.8"},{"date":"20120306","First Line":"32.9","Second Line":"48.4"},{"date":"20120307","First Line":"43.3","Second Line":"49.9"},{"date":"20120308","First Line":"51.2","Second Line":"49.2"},{"date":"20120309","First Line":"47.8","Second Line":"51.7"},{"date":"20120310","First Line":"37.2","Second Line":"49.3"},{"date":"20120311","First Line":"42.9","Second Line":"50.0"},{"date":"20120312","First Line":"48.8","Second Line":"48.6"},{"date":"20120313","First Line":"52.6","Second Line":"53.9"},{"date":"20120314","First Line":"60.5","Second Line":"55.2"},{"date":"20120315","First Line":"47.2","Second Line":"55.9"},{"date":"20120316","First Line":"44.7","Second Line":"54.6"},{"date":"20120317","First Line":"48.2","Second Line":"48.2"},{"date":"20120318","First Line":"48.2","Second Line":"47.1"},{"date":"20120319","First Line":"53.1","Second Line":"45.8"},{"date":"20120320","First Line":"57.8","Second Line":"49.7"},{"date":"20120321","First Line":"57.5","Second Line":"51.4"},{"date":"20120322","First Line":"57.3","Second Line":"51.4"},{"date":"20120323","First Line":"61.7","Second Line":"48.4"},{"date":"20120324","First Line":"55.8","Second Line":"49.0"},{"date":"20120325","First Line":"48.4","Second Line":"46.4"},{"date":"20120326","First Line":"49.8","Second Line":"49.7"},{"date":"20120327","First Line":"39.6","Second Line":"54.1"},{"date":"20120328","First Line":"49.7","Second Line":"54.6"},{"date":"20120329","First Line":"56.8","Second Line":"52.3"},{"date":"20120330","First Line":"46.5","Second Line":"54.5"},{"date":"20120331","First Line":"42.2","Second Line":"56.2"},{"date":"20120401","First Line":"45.3","Second Line":"51.1"},{"date":"20120402","First Line":"48.1","Second Line":"50.5"},{"date":"20120403","First Line":"51.2","Second Line":"52.2"},{"date":"20120404","First Line":"61.0","Second Line":"50.6"},{"date":"20120405","First Line":"50.7","Second Line":"47.9"},{"date":"20120406","First Line":"48.0","Second Line":"47.4"},{"date":"20120407","First Line":"51.1","Second Line":"49.4"},{"date":"20120408","First Line":"55.7","Second Line":"50.0"},{"date":"20120409","First Line":"58.3","Second Line":"51.3"},{"date":"20120410","First Line":"55.0","Second Line":"53.8"},{"date":"20120411","First Line":"49.0","Second Line":"52.9"},{"date":"20120412","First Line":"51.7","Second Line":"53.9"},{"date":"20120413","First Line":"53.1","Second Line":"50.2"},{"date":"20120414","First Line":"55.2","Second Line":"50.9"},{"date":"20120415","First Line":"62.3","Second Line":"51.5"},{"date":"20120416","First Line":"62.9","Second Line":"51.9"},{"date":"20120417","First Line":"69.3","Second Line":"53.2"},{"date":"20120418","First Line":"59.0","Second Line":"53.0"},{"date":"20120419","First Line":"54.1","Second Line":"55.1"},{"date":"20120420","First Line":"56.5","Second Line":"55.8"},{"date":"20120421","First Line":"58.2","Second Line":"58.0"},{"date":"20120422","First Line":"52.4","Second Line":"52.8"},{"date":"20120423","First Line":"51.6","Second Line":"55.1"},{"date":"20120424","First Line":"49.3","Second Line":"57.9"},{"date":"20120425","First Line":"52.5","Second Line":"57.5"},{"date":"20120426","First Line":"50.5","Second Line":"55.3"},{"date":"20120427","First Line":"51.9","Second Line":"53.5"},{"date":"20120428","First Line":"47.4","Second Line":"54.7"},{"date":"20120429","First Line":"54.1","Second Line":"54.0"},{"date":"20120430","First Line":"51.9","Second Line":"53.4"},{"date":"20120501","First Line":"57.4","Second Line":"52.7"},{"date":"20120502","First Line":"53.7","Second Line":"50.7"},{"date":"20120503","First Line":"53.1","Second Line":"52.6"},{"date":"20120504","First Line":"57.2","Second Line":"53.4"},{"date":"20120505","First Line":"57.0","Second Line":"53.1"},{"date":"20120506","First Line":"56.6","Second Line":"56.5"},{"date":"20120507","First Line":"54.6","Second Line":"55.3"},{"date":"20120508","First Line":"57.9","Second Line":"52.0"},{"date":"20120509","First Line":"59.2","Second Line":"52.4"},{"date":"20120510","First Line":"61.1","Second Line":"53.4"},{"date":"20120511","First Line":"59.7","Second Line":"53.1"},{"date":"20120512","First Line":"64.1","Second Line":"49.9"},{"date":"20120513","First Line":"65.3","Second Line":"52.0"},{"date":"20120514","First Line":"64.2","Second Line":"56.0"},{"date":"20120515","First Line":"62.0","Second Line":"53.0"},{"date":"20120516","First Line":"63.8","Second Line":"51.0"},{"date":"20120517","First Line":"64.5","Second Line":"51.4"},{"date":"20120518","First Line":"61.0","Second Line":"52.2"},{"date":"20120519","First Line":"62.6","Second Line":"52.4"},{"date":"20120520","First Line":"66.2","Second Line":"54.5"},{"date":"20120521","First Line":"62.7","Second Line":"52.8"},{"date":"20120522","First Line":"63.7","Second Line":"53.9"},{"date":"20120523","First Line":"66.4","Second Line":"56.5"},{"date":"20120524","First Line":"64.5","Second Line":"54.7"},{"date":"20120525","First Line":"65.4","Second Line":"52.5"},{"date":"20120526","First Line":"69.4","Second Line":"52.1"},{"date":"20120527","First Line":"71.9","Second Line":"52.2"},{"date":"20120528","First Line":"74.4","Second Line":"52.9"},{"date":"20120529","First Line":"75.9","Second Line":"52.1"},{"date":"20120530","First Line":"72.9","Second Line":"52.1"},{"date":"20120531","First Line":"72.5","Second Line":"53.3"},{"date":"20120601","First Line":"67.2","Second Line":"54.8"},{"date":"20120602","First Line":"68.3","Second Line":"54.0"},{"date":"20120603","First Line":"67.7","Second Line":"52.3"},{"date":"20120604","First Line":"61.9","Second Line":"55.3"},{"date":"20120605","First Line":"58.3","Second Line":"53.5"},{"date":"20120606","First Line":"61.7","Second Line":"54.1"},{"date":"20120607","First Line":"66.7","Second Line":"53.9"},{"date":"20120608","First Line":"68.7","Second Line":"54.4"},{"date":"20120609","First Line":"72.2","Second Line":"55.0"},{"date":"20120610","First Line":"72.6","Second Line":"60.0"},{"date":"20120611","First Line":"69.2","Second Line":"57.2"},{"date":"20120612","First Line":"66.9","Second Line":"55.1"},{"date":"20120613","First Line":"66.7","Second Line":"53.3"},{"date":"20120614","First Line":"67.7","Second Line":"53.4"},{"date":"20120615","First Line":"68.5","Second Line":"54.6"},{"date":"20120616","First Line":"67.5","Second Line":"57.0"},{"date":"20120617","First Line":"64.2","Second Line":"55.6"},{"date":"20120618","First Line":"61.7","Second Line":"52.5"},{"date":"20120619","First Line":"66.4","Second Line":"53.9"},{"date":"20120620","First Line":"77.9","Second Line":"55.3"},{"date":"20120621","First Line":"88.3","Second Line":"53.3"},{"date":"20120622","First Line":"82.2","Second Line":"54.1"},{"date":"20120623","First Line":"77.0","Second Line":"55.2"},{"date":"20120624","First Line":"75.4","Second Line":"55.8"},{"date":"20120625","First Line":"70.9","Second Line":"56.8"},{"date":"20120626","First Line":"65.9","Second Line":"57.5"},{"date":"20120627","First Line":"73.5","Second Line":"57.7"},{"date":"20120628","First Line":"77.4","Second Line":"56.6"},{"date":"20120629","First Line":"79.6","Second Line":"56.4"},{"date":"20120630","First Line":"84.2","Second Line":"58.4"},{"date":"20120701","First Line":"81.8","Second Line":"58.8"},{"date":"20120702","First Line":"82.5","Second Line":"56.4"},{"date":"20120703","First Line":"80.2","Second Line":"56.5"},{"date":"20120704","First Line":"77.8","Second Line":"55.8"},{"date":"20120705","First Line":"86.1","Second Line":"54.8"},{"date":"20120706","First Line":"79.9","Second Line":"54.9"},{"date":"20120707","First Line":"83.5","Second Line":"54.7"},{"date":"20120708","First Line":"81.5","Second Line":"52.8"},{"date":"20120709","First Line":"77.8","Second Line":"53.7"},{"date":"20120710","First Line":"76.1","Second Line":"53.1"},{"date":"20120711","First Line":"76.3","Second Line":"52.7"},{"date":"20120712","First Line":"75.8","Second Line":"52.0"},{"date":"20120713","First Line":"77.2","Second Line":"53.4"},{"date":"20120714","First Line":"79.3","Second Line":"54.0"},{"date":"20120715","First Line":"78.9","Second Line":"54.0"},{"date":"20120716","First Line":"79.6","Second Line":"54.5"},{"date":"20120717","First Line":"83.3","Second Line":"56.7"},{"date":"20120718","First Line":"84.3","Second Line":"57.5"},{"date":"20120719","First Line":"75.1","Second Line":"57.1"},{"date":"20120720","First Line":"68.4","Second Line":"58.1"},{"date":"20120721","First Line":"68.4","Second Line":"57.6"},{"date":"20120722","First Line":"72.2","Second Line":"56.0"},{"date":"20120723","First Line":"75.6","Second Line":"56.6"},{"date":"20120724","First Line":"82.6","Second Line":"57.8"},{"date":"20120725","First Line":"78.4","Second Line":"57.5"},{"date":"20120726","First Line":"77.0","Second Line":"56.4"},{"date":"20120727","First Line":"79.4","Second Line":"55.3"},{"date":"20120728","First Line":"77.4","Second Line":"55.0"},{"date":"20120729","First Line":"72.5","Second Line":"55.6"},{"date":"20120730","First Line":"72.9","Second Line":"55.6"},{"date":"20120731","First Line":"73.6","Second Line":"55.9"},{"date":"20120801","First Line":"75.0","Second Line":"55.4"},{"date":"20120802","First Line":"77.7","Second Line":"54.4"},{"date":"20120803","First Line":"79.7","Second Line":"53.7"},{"date":"20120804","First Line":"79.6","Second Line":"54.1"},{"date":"20120805","First Line":"81.5","Second Line":"57.8"},{"date":"20120806","First Line":"80.0","Second Line":"58.2"},{"date":"20120807","First Line":"75.7","Second Line":"58.0"},{"date":"20120808","First Line":"77.8","Second Line":"57.0"},{"date":"20120809","First Line":"78.6","Second Line":"55.0"},{"date":"20120810","First Line":"77.8","Second Line":"54.8"},{"date":"20120811","First Line":"78.5","Second Line":"53.0"},{"date":"20120812","First Line":"78.8","Second Line":"52.5"},{"date":"20120813","First Line":"78.6","Second Line":"53.3"},{"date":"20120814","First Line":"76.8","Second Line":"53.9"},{"date":"20120815","First Line":"76.7","Second Line":"56.2"},{"date":"20120816","First Line":"75.9","Second Line":"57.1"},{"date":"20120817","First Line":"77.6","Second Line":"55.3"},{"date":"20120818","First Line":"72.6","Second Line":"56.2"},{"date":"20120819","First Line":"70.4","Second Line":"54.3"},{"date":"20120820","First Line":"71.8","Second Line":"53.1"},{"date":"20120821","First Line":"73.6","Second Line":"53.4"},{"date":"20120822","First Line":"74.7","Second Line":"54.5"},{"date":"20120823","First Line":"74.6","Second Line":"55.7"},{"date":"20120824","First Line":"76.0","Second Line":"54.8"},{"date":"20120825","First Line":"76.2","Second Line":"53.8"},{"date":"20120826","First Line":"73.4","Second Line":"56.5"},{"date":"20120827","First Line":"74.6","Second Line":"58.3"},{"date":"20120828","First Line":"79.4","Second Line":"58.7"},{"date":"20120829","First Line":"74.7","Second Line":"57.5"},{"date":"20120830","First Line":"73.5","Second Line":"55.9"},{"date":"20120831","First Line":"77.9","Second Line":"55.4"},{"date":"20120901","First Line":"80.7","Second Line":"55.7"},{"date":"20120902","First Line":"75.1","Second Line":"53.1"},{"date":"20120903","First Line":"73.5","Second Line":"53.5"},{"date":"20120904","First Line":"73.5","Second Line":"52.5"},{"date":"20120905","First Line":"77.7","Second Line":"54.5"},{"date":"20120906","First Line":"74.2","Second Line":"56.3"},{"date":"20120907","First Line":"76.0","Second Line":"56.4"},{"date":"20120908","First Line":"77.1","Second Line":"56.5"},{"date":"20120909","First Line":"69.7","Second Line":"56.4"},{"date":"20120910","First Line":"67.8","Second Line":"55.4"},{"date":"20120911","First Line":"64.0","Second Line":"56.2"},{"date":"20120912","First Line":"68.1","Second Line":"55.7"},{"date":"20120913","First Line":"69.3","Second Line":"54.3"},{"date":"20120914","First Line":"70.0","Second Line":"55.2"},{"date":"20120915","First Line":"69.3","Second Line":"54.3"},{"date":"20120916","First Line":"66.3","Second Line":"52.9"},{"date":"20120917","First Line":"67.0","Second Line":"54.8"},{"date":"20120918","First Line":"72.8","Second Line":"54.8"},{"date":"20120919","First Line":"67.2","Second Line":"56.8"},{"date":"20120920","First Line":"62.1","Second Line":"55.4"},{"date":"20120921","First Line":"64.0","Second Line":"55.8"},{"date":"20120922","First Line":"65.5","Second Line":"55.9"},{"date":"20120923","First Line":"65.7","Second Line":"52.8"},{"date":"20120924","First Line":"60.4","Second Line":"54.5"},{"date":"20120925","First Line":"63.2","Second Line":"53.3"},{"date":"20120926","First Line":"68.5","Second Line":"53.6"},{"date":"20120927","First Line":"69.2","Second Line":"52.1"},{"date":"20120928","First Line":"68.7","Second Line":"52.6"},{"date":"20120929","First Line":"62.5","Second Line":"53.9"},{"date":"20120930","First Line":"62.3","Second Line":"55.1"}];

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y%m%d").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(Math.min(d["First Line"], d["Second Line"])); });

var area = d3.svg.area()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y1(function(d) { return y(d["First Line"]); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
    d.date = parseDate(d.date);
    d["First Line"]= +d["First Line"];
    d["Second Line"] = +d["Second Line"];
});

x.domain(d3.extent(data, function(d) { return d.date; }));

y.domain([
  d3.min(data, function(d) { return Math.min(d["First Line"], d["Second Line"]); }),
  d3.max(data, function(d) { return Math.max(d["First Line"], d["Second Line"]); })
]);

svg.datum(data);

svg.append("clipPath")
  .attr("id", "clip-above")
  .append("path")
  .attr("d", area.y0(height));

svg.append("clipPath")
  .attr("id", "clip-below")
  .append("path")
  .attr("d", area.y0(0));

svg.append("path")
  .attr("class", "area below")
  .attr("clip-path", "url(#clip-below)")
  .attr("d", area.y0(function(d) { return y(d["Second Line"]); }));

svg.append("path")
  .attr("class", "area above")
  .attr("clip-path", "url(#clip-above)")
  .attr("d", area);

svg.append("path")
  .attr("class", "line")
  .attr("d", line.y0(height));

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Temperature (ºF)");

body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  /*display: none;*/
}

.area.below {
  fill: rgb(252,141,89);
  stroke: #000;
  stroke-width: 1px;
}

.area.above {
  fill: rgb(145,207,96);
  stroke: #000;
  stroke-width: 1px;
}

.line {
  fill: #ccc;
  stroke: #000;
  stroke-width: 0.5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart"></div>


来源: stackexchange

问:
Getting ZoneId from a SimpleTimeZone
Using Java I have a SimpleTimeZone instance with GMT offset and daylight saving time information from a legacy system.

I would like to retrieve ZoneId to be able to use Java 8 time API.

Actually, toZoneId returns a ZoneId without the daylight Saving time infos

```<code>SimpleTimeZone stz = new SimpleTimeZone( 2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY,1,1,1, Calendar.FEBRUARY,1,1,1, 1 * 60 * 60 * 1000);
stz.toZoneId();
</code>```

答:
First of all, when you do:

```<code>SimpleTimeZone stz = new SimpleTimeZone(2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY, 1, 1, 1, Calendar.FEBRUARY, 1, 1, 1, 1 * 60 * 60 * 1000);
</code>```

You're creating a timezone with ID equals to "GMT". When you call toZoneId(), it just calls ZoneId.of("GMT") (it uses the same ID as parameter, as already told in @Ole V.V.'s answer). And then ZoneId class loads whatever Daylight Saving infos are configured in the JVM (it doesn't keep the same rules from the original SimpleTimeZone object).

And according to ZoneId javadoc: If the zone ID equals 'GMT', 'UTC' or 'UT' then the result is a ZoneId with the same ID and rules equivalent to ZoneOffset.UTC. And ZoneOffset.UTC has no DST rules at all.

So, if you want to have a ZoneId instance with the same DST rules, you'll have to create them by hand (I didn't know it was possible, but it actually is, check below).

Your DST rules

Looking at SimpleTimeZone javadoc, the instance you created has the following rules (according to my tests):

standard offset is +02:00 (2 hours ahead UTC/GMT)

DST starts at the first Sunday of January (take a look at the javadoc for more details), 1 millisecond after midnight (you passed 1 as start and end times)

when in DST, offset changes to +03:00

DST ends at the first Sunday of February, 1 millisecond after midnight (then offset gets back to +02:00)

Actually, according to javadoc, you should've passed a negative number in dayOfWeek parameters to work this way, so the timezone should be created like this:

```<code>stz = new SimpleTimeZone(2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY, 1, -Calendar.SUNDAY, 1, Calendar.FEBRUARY, 1, -Calendar.SUNDAY, 1, 1 * 60 * 60 * 1000);
</code>```

But in my tests, both worked the same way (maybe it fixes the non-negative values). Anyway, I've made some tests just to check these rules. First I created a SimpleDateFormat with your custom timezone:

```<code>TimeZone t = TimeZone.getTimeZone("America/Sao_Paulo");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z");
sdf.setTimeZone(t);
</code>```

Then I tested with the boundaries dates (before start and end of DST):

```<code>// starts at 01/01/2017 (first Sunday of January)
ZonedDateTime z = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneOffset.ofHours(2));
// 01/01/2017 00:00:00 +0200 (not in DST yet, offset is still +02)
System.out.println(sdf.format(new Date(z.toInstant().toEpochMilli())));
// 01/01/2017 01:01:00 +0300 (DST starts, offset changed to +03)
System.out.println(sdf.format(new Date(z.plusMinutes(1).toInstant().toEpochMilli())));

// ends at 05/02/2017 (first Sunday of February)
z = ZonedDateTime.of(2017, 2, 5, 0, 0, 0, 0, ZoneOffset.ofHours(3));
// 05/02/2017 00:00:00 +0300 (in DST yet, offset is still +03)
System.out.println(sdf.format(new Date(z.toInstant().toEpochMilli())));
// 04/02/2017 23:01:00 +0200 (DST ends, offset changed to +02 - clock moves back 1 hour: from midnight to 11 PM of previous day)
System.out.println(sdf.format(new Date(z.plusMinutes(1).toInstant().toEpochMilli())));
</code>```

The output is:

01/01/2017 00:00:00 +0200

  01/01/2017 01:01:00 +0300

  05/02/2017 00:00:00 +0300

  04/02/2017 23:01:00 +0200

So, it follows the rules described above (at 01/01/2017 midnight the offset is +0200, one minute later it's in DST (offset is now +0300; the opposite occurs at 05/02 (DST ends and offset goes back to +0200)).

Create a ZoneId with the rules above

Unfortunatelly you can't extend ZoneId and ZoneOffset, and you can't also change them because both are immutable. But it's possible to create custom rules and assign them to a new ZoneId.

And it doesn't seem to have a way to directly export the rules from SimpleTimeZone to ZoneId, so you'll have to create them by hand.

First we need to create a ZoneRules, a class that contains all the rules to when and how the offset changes. In order to create it, we need to build a list of 2 classes:

ZoneOffsetTransition: defines a specific date for an offset change. There must be at least one to make it work (with an empty list it failed)

ZoneOffsetTransitionRule: defines a general rule, not bounded to a specific date (like "first Sunday of January the offset changes from X to Y"). We must have 2 rules (one for DST start, and another for DST end)

So, let's create them:

```<code>// offsets (standard and DST)
ZoneOffset standardOffset = ZoneOffset.ofHours(2);
ZoneOffset dstOffset = ZoneOffset.ofHours(3);

// you need to create at least one transition (using a date in the very past to not interfere with the transition rules)
LocalDateTime startDate = LocalDateTime.MIN;
LocalDateTime endDate = LocalDateTime.MIN.plusDays(1);
// DST transitions (date when it happens, offset before and offset after) - you need to create at least one
ZoneOffsetTransition start = ZoneOffsetTransition.of(startDate, standardOffset, dstOffset);
ZoneOffsetTransition end = ZoneOffsetTransition.of(endDate, dstOffset, standardOffset);
// create list of transitions (to be used in ZoneRules creation)
List<ZoneOffsetTransition> transitions = Arrays.asList(start, end);

// a time to represent the first millisecond after midnight
LocalTime firstMillisecond = LocalTime.of(0, 0, 0, 1000000);
// DST start rule: first Sunday of January, 1 millisecond after midnight
ZoneOffsetTransitionRule startRule = ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.SUNDAY, firstMillisecond, false, TimeDefinition.WALL,
    standardOffset, standardOffset, dstOffset);
// DST end rule: first Sunday of February, 1 millisecond after midnight
ZoneOffsetTransitionRule endRule = ZoneOffsetTransitionRule.of(Month.FEBRUARY, 1, DayOfWeek.SUNDAY, firstMillisecond, false, TimeDefinition.WALL,
    standardOffset, dstOffset, standardOffset);
// list of transition rules
List<ZoneOffsetTransitionRule> transitionRules = Arrays.asList(startRule, endRule);

// create the ZoneRules instance (it'll be set on the timezone)
ZoneRules rules = ZoneRules.of(start.getOffsetAfter(), end.getOffsetAfter(), transitions, transitions, transitionRules);
</code>```

I couldn't create a ZoneOffsetTransition that starts at the first millisecond after midnight (they actually start at midnight exactly), because the fraction of seconds must be zero (if it's not, ZoneOffsetTransition.of() throws an exception). So, I decided to set a date in the past (LocalDateTime.MIN) to not interfere with the rules.

But the ZoneOffsetTransitionRule instances works exactly like expected (DST starts and ends 1 millisecond after midnight, just like the SimpleTimeZone instance).

Now we must set this ZoneRules to a timezone. As I said, ZoneId can't be extended (the constructor is not public) and neither does ZoneOffset (it's a  final class). I initially thought that the only way to set the rules was to create an instance and set it using reflection, but actually the API provides a way to create custom ZoneId's by extending the java.time.zone.ZoneRulesProvider class:

```<code>// new provider for my custom zone id's
public class CustomZoneRulesProvider extends ZoneRulesProvider {

    @Override
    protected Set<String> provideZoneIds() {
        // returns only one ID
        return Collections.singleton("MyNewTimezone");
    }

    @Override
    protected ZoneRules provideRules(String zoneId, boolean forCaching) {
        // returns the ZoneRules for the custom timezone
        if ("MyNewTimezone".equals(zoneId)) {
            ZoneRules rules = // create the ZoneRules as above
            return rules;
        }
        return null;
    }

    // returns a map with the ZoneRules, check javadoc for more details
    @Override
    protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
        TreeMap<String, ZoneRules> map = new TreeMap<>();
        ZoneRules rules = getRules(zoneId, false);
        if (rules != null) {
            map.put(zoneId, rules);
        }
        return map;
    }
}
</code>```

Please keep in mind that you shouldn't set the ID to "GMT", "UTC", or any valid ID (you can check all existent IDs with ZoneId.getAvailableZoneIds()). "GMT" and "UTC" are special names used internally by the API and it can lead to unexpected behaviour. So choose a name that doesn't exist - I've chosen MyNewTimezone (without spaces otherwise it'll fail because ZoneRegion throws an exception if there's a space in the name).

Let's test this new timezone. The new class must be registered using the ZoneRulesProvider.registerProvider method:

```<code>// register the new zonerules provider
ZoneRulesProvider.registerProvider(new CustomZoneRulesProvider());
// create my custom zone
ZoneId customZone = ZoneId.of("MyNewTimezone");

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss Z");
// starts at 01/01/2017 (first Sunday of January)
ZonedDateTime z = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, customZone);
// 01/01/2017 00:00:00 +0200 (not in DST yet, offset is still +02)
System.out.println(z.format(fmt));
// 01/01/2017 01:01:00 +0300 (DST starts, offset changed to +03)
System.out.println(z.plusMinutes(1).format(fmt));

// ends at 05/02/2017 (first Sunday of February)
z = ZonedDateTime.of(2017, 2, 5, 0, 0, 0, 0, customZone);
// 05/02/2017 00:00:00 +0300 (in DST yet, offset is still +03)
System.out.println(z.format(fmt));
// 04/02/2017 23:01:00 +0200 (DST ends, offset changed to +02 - clock moves back 1 hour: from midnight to 11 PM of previous day)
System.out.println(z.plusMinutes(1).format(fmt));
</code>```

The output is the same (so the rules are the same used by the SimpleTimeZone):

01/01/2017 00:00:00 +0200

  01/01/2017 01:01:00 +0300

  05/02/2017 00:00:00 +0300

  04/02/2017 23:01:00 +0200

Notes:

The CustomZoneRulesProvider creates just one new ZoneId, but of course you can extend it to create more. Check the javadoc for more details about how to correct implement your own rules provider.

You must check exactly what are the rules from your custom timezones before creating the ZoneRules. One way is to use SimpleTimeZone.toString() method (that returns the internal state of the object) and read the javadoc to know how the parameters affect the rules.

I haven't tested enough cases to know if there are some specific date where the SimpleTimeZone and ZoneId rules behave in a different way. I've tested some dates in different years and it seems to be working fine.

ContentLicense: CC BY-SA 3.0

Title: Getting ZoneId from a SimpleTimeZone

Body:
Using Java I have a SimpleTimeZone instance with GMT offset and daylight saving time information from a legacy system.

I would like to retrieve ZoneId to be able to use Java 8 time API.

Actually, toZoneId returns a ZoneId without the daylight Saving time infos

SimpleTimeZone stz = new SimpleTimeZone( 2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY,1,1,1, Calendar.FEBRUARY,1,1,1, 1 * 60 * 60 * 1000);
stz.toZoneId();

Body:
First of all, when you do:

SimpleTimeZone stz = new SimpleTimeZone(2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY, 1, 1, 1, Calendar.FEBRUARY, 1, 1, 1, 1 * 60 * 60 * 1000);

You're creating a timezone with ID equals to "GMT". When you call toZoneId(), it just calls ZoneId.of("GMT") (it uses the same ID as parameter, as already told in @Ole V.V.'s answer). And then ZoneId class loads whatever Daylight Saving infos are configured in the JVM (it doesn't keep the same rules from the original SimpleTimeZone object).

And according to ZoneId javadoc: If the zone ID equals 'GMT', 'UTC' or 'UT' then the result is a ZoneId with the same ID and rules equivalent to ZoneOffset.UTC. And ZoneOffset.UTC has no DST rules at all.

So, if you want to have a ZoneId instance with the same DST rules, you'll have to create them by hand (I didn't know it was possible, but it actually is, check below).

Your DST rules

Looking at SimpleTimeZone javadoc, the instance you created has the following rules (according to my tests):

standard offset is +02:00 (2 hours ahead UTC/GMT)

DST starts at the first Sunday of January (take a look at the javadoc for more details), 1 millisecond after midnight (you passed 1 as start and end times)

when in DST, offset changes to +03:00

DST ends at the first Sunday of February, 1 millisecond after midnight (then offset gets back to +02:00)

Actually, according to javadoc, you should've passed a negative number in dayOfWeek parameters to work this way, so the timezone should be created like this:

stz = new SimpleTimeZone(2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY, 1, -Calendar.SUNDAY, 1, Calendar.FEBRUARY, 1, -Calendar.SUNDAY, 1, 1 * 60 * 60 * 1000);

But in my tests, both worked the same way (maybe it fixes the non-negative values). Anyway, I've made some tests just to check these rules. First I created a SimpleDateFormat with your custom timezone:

TimeZone t = TimeZone.getTimeZone("America/Sao_Paulo");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z");
sdf.setTimeZone(t);

Then I tested with the boundaries dates (before start and end of DST):

// starts at 01/01/2017 (first Sunday of January)
ZonedDateTime z = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneOffset.ofHours(2));
// 01/01/2017 00:00:00 +0200 (not in DST yet, offset is still +02)
System.out.println(sdf.format(new Date(z.toInstant().toEpochMilli())));
// 01/01/2017 01:01:00 +0300 (DST starts, offset changed to +03)
System.out.println(sdf.format(new Date(z.plusMinutes(1).toInstant().toEpochMilli())));

// ends at 05/02/2017 (first Sunday of February)
z = ZonedDateTime.of(2017, 2, 5, 0, 0, 0, 0, ZoneOffset.ofHours(3));
// 05/02/2017 00:00:00 +0300 (in DST yet, offset is still +03)
System.out.println(sdf.format(new Date(z.toInstant().toEpochMilli())));
// 04/02/2017 23:01:00 +0200 (DST ends, offset changed to +02 - clock moves back 1 hour: from midnight to 11 PM of previous day)
System.out.println(sdf.format(new Date(z.plusMinutes(1).toInstant().toEpochMilli())));

The output is:

01/01/2017 00:00:00 +0200

  01/01/2017 01:01:00 +0300

  05/02/2017 00:00:00 +0300

  04/02/2017 23:01:00 +0200

So, it follows the rules described above (at 01/01/2017 midnight the offset is +0200, one minute later it's in DST (offset is now +0300; the opposite occurs at 05/02 (DST ends and offset goes back to +0200)).

Create a ZoneId with the rules above

Unfortunatelly you can't extend ZoneId and ZoneOffset, and you can't also change them because both are immutable. But it's possible to create custom rules and assign them to a new ZoneId.

And it doesn't seem to have a way to directly export the rules from SimpleTimeZone to ZoneId, so you'll have to create them by hand.

First we need to create a ZoneRules, a class that contains all the rules to when and how the offset changes. In order to create it, we need to build a list of 2 classes:

ZoneOffsetTransition: defines a specific date for an offset change. There must be at least one to make it work (with an empty list it failed)

ZoneOffsetTransitionRule: defines a general rule, not bounded to a specific date (like "first Sunday of January the offset changes from X to Y"). We must have 2 rules (one for DST start, and another for DST end)

So, let's create them:

// offsets (standard and DST)
ZoneOffset standardOffset = ZoneOffset.ofHours(2);
ZoneOffset dstOffset = ZoneOffset.ofHours(3);

// you need to create at least one transition (using a date in the very past to not interfere with the transition rules)
LocalDateTime startDate = LocalDateTime.MIN;
LocalDateTime endDate = LocalDateTime.MIN.plusDays(1);
// DST transitions (date when it happens, offset before and offset after) - you need to create at least one
ZoneOffsetTransition start = ZoneOffsetTransition.of(startDate, standardOffset, dstOffset);
ZoneOffsetTransition end = ZoneOffsetTransition.of(endDate, dstOffset, standardOffset);
// create list of transitions (to be used in ZoneRules creation)
List<ZoneOffsetTransition> transitions = Arrays.asList(start, end);

// a time to represent the first millisecond after midnight
LocalTime firstMillisecond = LocalTime.of(0, 0, 0, 1000000);
// DST start rule: first Sunday of January, 1 millisecond after midnight
ZoneOffsetTransitionRule startRule = ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.SUNDAY, firstMillisecond, false, TimeDefinition.WALL,
    standardOffset, standardOffset, dstOffset);
// DST end rule: first Sunday of February, 1 millisecond after midnight
ZoneOffsetTransitionRule endRule = ZoneOffsetTransitionRule.of(Month.FEBRUARY, 1, DayOfWeek.SUNDAY, firstMillisecond, false, TimeDefinition.WALL,
    standardOffset, dstOffset, standardOffset);
// list of transition rules
List<ZoneOffsetTransitionRule> transitionRules = Arrays.asList(startRule, endRule);

// create the ZoneRules instance (it'll be set on the timezone)
ZoneRules rules = ZoneRules.of(start.getOffsetAfter(), end.getOffsetAfter(), transitions, transitions, transitionRules);

I couldn't create a ZoneOffsetTransition that starts at the first millisecond after midnight (they actually start at midnight exactly), because the fraction of seconds must be zero (if it's not, ZoneOffsetTransition.of() throws an exception). So, I decided to set a date in the past (LocalDateTime.MIN) to not interfere with the rules.

But the ZoneOffsetTransitionRule instances works exactly like expected (DST starts and ends 1 millisecond after midnight, just like the SimpleTimeZone instance).

Now we must set this ZoneRules to a timezone. As I said, ZoneId can't be extended (the constructor is not public) and neither does ZoneOffset (it's a  final class). I initially thought that the only way to set the rules was to create an instance and set it using reflection, but actually the API provides a way to create custom ZoneId's by extending the java.time.zone.ZoneRulesProvider class:

// new provider for my custom zone id's
public class CustomZoneRulesProvider extends ZoneRulesProvider {

    @Override
    protected Set<String> provideZoneIds() {
        // returns only one ID
        return Collections.singleton("MyNewTimezone");
    }

    @Override
    protected ZoneRules provideRules(String zoneId, boolean forCaching) {
        // returns the ZoneRules for the custom timezone
        if ("MyNewTimezone".equals(zoneId)) {
            ZoneRules rules = // create the ZoneRules as above
            return rules;
        }
        return null;
    }

    // returns a map with the ZoneRules, check javadoc for more details
    @Override
    protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
        TreeMap<String, ZoneRules> map = new TreeMap<>();
        ZoneRules rules = getRules(zoneId, false);
        if (rules != null) {
            map.put(zoneId, rules);
        }
        return map;
    }
}

Please keep in mind that you shouldn't set the ID to "GMT", "UTC", or any valid ID (you can check all existent IDs with ZoneId.getAvailableZoneIds()). "GMT" and "UTC" are special names used internally by the API and it can lead to unexpected behaviour. So choose a name that doesn't exist - I've chosen MyNewTimezone (without spaces otherwise it'll fail because ZoneRegion throws an exception if there's a space in the name).

Let's test this new timezone. The new class must be registered using the ZoneRulesProvider.registerProvider method:

// register the new zonerules provider
ZoneRulesProvider.registerProvider(new CustomZoneRulesProvider());
// create my custom zone
ZoneId customZone = ZoneId.of("MyNewTimezone");

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss Z");
// starts at 01/01/2017 (first Sunday of January)
ZonedDateTime z = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, customZone);
// 01/01/2017 00:00:00 +0200 (not in DST yet, offset is still +02)
System.out.println(z.format(fmt));
// 01/01/2017 01:01:00 +0300 (DST starts, offset changed to +03)
System.out.println(z.plusMinutes(1).format(fmt));

// ends at 05/02/2017 (first Sunday of February)
z = ZonedDateTime.of(2017, 2, 5, 0, 0, 0, 0, customZone);
// 05/02/2017 00:00:00 +0300 (in DST yet, offset is still +03)
System.out.println(z.format(fmt));
// 04/02/2017 23:01:00 +0200 (DST ends, offset changed to +02 - clock moves back 1 hour: from midnight to 11 PM of previous day)
System.out.println(z.plusMinutes(1).format(fmt));

The output is the same (so the rules are the same used by the SimpleTimeZone):

01/01/2017 00:00:00 +0200

  01/01/2017 01:01:00 +0300

  05/02/2017 00:00:00 +0300

  04/02/2017 23:01:00 +0200

Notes:

The CustomZoneRulesProvider creates just one new ZoneId, but of course you can extend it to create more. Check the javadoc for more details about how to correct implement your own rules provider.

You must check exactly what are the rules from your custom timezones before creating the ZoneRules. One way is to use SimpleTimeZone.toString() method (that returns the internal state of the object) and read the javadoc to know how the parameters affect the rules.

I haven't tested enough cases to know if there are some specific date where the SimpleTimeZone and ZoneId rules behave in a different way. I've tested some dates in different years and it seems to be working fine.


问:
cfloop and query of queries
I have a scenario like below on a page. I have a query being returned from a cfc all_data which has columns, section, state, data. Now the page design looks something like below.

section1 section2 section3 section4 -> select one section to select the state in it

Lets say section1 is selected -> State1 state2 state3 associated with that section need to be displayed -> select one state to see the data related to it.

Say State3 is selected -> related State3 data is shown.

So basically I need 3 cfloops which will accomplish the above. I am doing `

```<code><cfquery name="section" dbtype="query">
 select distinct section from all_data
</cfquery>`
</code>```

for first loop, I loop over 'section' query to display all the sections.

```<code><cfloop query ="section">
    <cfquery name="state" dbtype="query">
    select distinct state from all_data where section = section.section
    </cfquery>
</cfloop>
</code>```

for state display I loop like above. For loop 3 that is the data display I have tried multiple things but nothing seems to work the right way. Is this the right approach. Any insights are appreciated.

答:
I think you can use the group attribute as below
     </p>

```<code><cfset myQuery = QueryNew("Section, State, Data", "VarChar, VarChar, VarChar")>

<cfset newRow = QueryAddRow(MyQuery, 5)>

<!--- Set the values of the cells in the query --->
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 1)>
<cfset temp = QuerySetCell(myQuery, "State", "State 1", 1)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 1", 1)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 2)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 2)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 2", 2)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 3)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 3)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 3", 3)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 2", 4)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 4)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 2", 4)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 2", 5)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 5)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 3", 5)>

 <cfoutput query ="myQuery" group="Section">
    </br>#Section# <!--- You will get distinct Sections here --->
    <cfoutput group="Section">
            </br>#State#,
            <cfoutput>#Data#,</cfoutput>
    </cfoutput>
 </cfoutput>
</code>```

Title: cfloop and query of queries

Body:
I have a scenario like below on a page. I have a query being returned from a cfc all_data which has columns, section, state, data. Now the page design looks something like below.

section1 section2 section3 section4 -> select one section to select the state in it

Lets say section1 is selected -> State1 state2 state3 associated with that section need to be displayed -> select one state to see the data related to it.

Say State3 is selected -> related State3 data is shown.

So basically I need 3 cfloops which will accomplish the above. I am doing `

<cfquery name="section" dbtype="query">
 select distinct section from all_data
</cfquery>`

for first loop, I loop over 'section' query to display all the sections.

<cfloop query ="section">
    <cfquery name="state" dbtype="query">
    select distinct state from all_data where section = section.section
    </cfquery>
</cfloop>

for state display I loop like above. For loop 3 that is the data display I have tried multiple things but nothing seems to work the right way. Is this the right approach. Any insights are appreciated.

Body:
I think you can use the group attribute as below

<cfset myQuery = QueryNew("Section, State, Data", "VarChar, VarChar, VarChar")>

<cfset newRow = QueryAddRow(MyQuery, 5)>

<!--- Set the values of the cells in the query --->
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 1)>
<cfset temp = QuerySetCell(myQuery, "State", "State 1", 1)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 1", 1)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 2)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 2)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 2", 2)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 1", 3)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 3)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 3", 3)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 2", 4)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 4)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 2", 4)>
<cfset temp = QuerySetCell(myQuery, "Section", "Section 2", 5)>
<cfset temp = QuerySetCell(myQuery, "State", "State 2", 5)>
<cfset temp = QuerySetCell(myQuery, "Data", "Data 3", 5)>

 <cfoutput query ="myQuery" group="Section">
    </br>#Section# <!--- You will get distinct Sections here --->
    <cfoutput group="Section">
            </br>#State#,
            <cfoutput>#Data#,</cfoutput>
    </cfoutput>
 </cfoutput>


问:
JavaCC: How to parse characters that may not be exist?
I am trying to adapt a PDDL parser and there is a token that is optional to be exist. Suppose these are 2 options I want to read.
(figure1)

```<code>(node1)
(node1 :isGood)               // :isGood is optional to be exist
</code>```

To support both situations, I developed code in .jj like this figure2 below. It works correctly; however, it is an inappropriate way to write like this.
(figure2)

```<code><LEFT_BRACKET>
<NODE>
(LOOKAHEAD(2) <IS_GOOD> <RIGHT_BRACKET> | <RIGHT_BRACKET>)
</code>```

The code in .jj that I actually want it to be should be like in this figure3 below. From figure3, it parses from .jj successfully but it is unable to parse the scripts in the figure1 from which I received unexpected token ")" instead. (figure3)

```<code><LEFT_BRACKET>
<NODE>
(LOOKAHEAD(2) <IS_GOOD>)      // this is where it should support an optional token
<RIGHT_BRACKET>
</code>```

Question: How to write the code in .jj to support both conditions in figure1? In other words, how to make it support the optional token :isGood that may not be exist with an appropriate approach of programming.

I probably don't know how the LOOKAHEAD works. Any solution to read the figure1 is appreciate.

答:
You don't need the lookahead specification in this case. Just use

```<code><LEFT_BRACKET>
<NODE>
[ <IS_GOOD> ]
<RIGHT_BRACKET>
</code>```

or

```<code><LEFT_BRACKET>
<NODE>
( <IS_GOOD> )?
<RIGHT_BRACKET>
</code>```

or

```<code><LEFT_BRACKET>
<NODE>
( <IS_GOOD> | {} )
<RIGHT_BRACKET>
</code>```

They mean the same thing.

Body:
I am trying to adapt a PDDL parser and there is a token that is optional to be exist. Suppose these are 2 options I want to read.
(figure1)

(node1)
(node1 :isGood)               // :isGood is optional to be exist

To support both situations, I developed code in .jj like this figure2 below. It works correctly; however, it is an inappropriate way to write like this.
(figure2)

<LEFT_BRACKET>
<NODE>
(LOOKAHEAD(2) <IS_GOOD> <RIGHT_BRACKET> | <RIGHT_BRACKET>)

The code in .jj that I actually want it to be should be like in this figure3 below. From figure3, it parses from .jj successfully but it is unable to parse the scripts in the figure1 from which I received unexpected token ")" instead. (figure3)

<LEFT_BRACKET>
<NODE>
(LOOKAHEAD(2) <IS_GOOD>)      // this is where it should support an optional token
<RIGHT_BRACKET>

Question: How to write the code in .jj to support both conditions in figure1? In other words, how to make it support the optional token :isGood that may not be exist with an appropriate approach of programming.

I probably don't know how the LOOKAHEAD works. Any solution to read the figure1 is appreciate.

Body:
You don't need the lookahead specification in this case. Just use

<LEFT_BRACKET>
<NODE>
[ <IS_GOOD> ]
<RIGHT_BRACKET>

or

<LEFT_BRACKET>
<NODE>
( <IS_GOOD> )?
<RIGHT_BRACKET>

or

<LEFT_BRACKET>
<NODE>
( <IS_GOOD> | {} )
<RIGHT_BRACKET>

They mean the same thing.


问:
Straight line planar embedding of a graph structure
Here is my problem: I have a graph structure (with straight line edges) which I know to be planar (i.e. there exists an embedding of the graph where no edges cross). I need an algorithm which will take my graph and produce a straight line planar embedding of it. The algorithm does not need to be too efficient (an O(N^2) algorithm would do fine). Any ideas/suggestions?</p>

答:
Read this document...

I had this project for my Algorithms course, to embed the graph we used SVG format... once u decide the algorithm, SVG format is easy to generate...

ContentLicense: CC BY-SA 2.5


问:
Visibility Converter Binding Not Working
I have a visibility converter for a a DataGrid that should hide the grid when the item source for the grid is null.  The item source is a property of the class for the window.

Here is partial XAML for the window - the window and visibility converter definition and the data grid:

Window:

```<code><Window x:Name="DiagramWindow"
    x:Class="FabricAnalyzer.FabricDiagram"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:FabricAnalyzer"

    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    mc:Ignorable="d"
    Title="FabricDiagram"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>

    <ResourceDictionary>
        <local:SwitchThumbColorConverter x:Key="SwitchThumbColor"/>
        <local:PortThumbColorConverter x:Key="PortThumbColor"/>
        <local:StringLengthVisiblityConverter x:Key="VisConverter"/>
        <local:PortListVisiblityConverter x:Key="PortVisConverter"/>
</code>```

Datagrid:

```<code><Grid Name="FabricGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <DataGrid Name="SVCPortDataGrid" Grid.Column="0" Width="Auto"
                   Visibility="{Binding Path=PortList, Converter=
    {StaticResource PortVisConverter}}"
                      AutoGenerateColumns="False">
</code>```

Here is the code behind for the property it should bind to and the VisibilityConverter.  the idea is that if the PortList is null - it will be by default - the DataGrid should stay collapsed.  I have verified that the PortList is null when I want it to be.

```<code> public partial class FabricDiagram : Window
{

    public List<PortResult> PortList = null;
</code>```

lastly the visibilityconverter.  I have verified in the debugger that it is not getting called.

```<code> public class PortListVisiblityConverter : IValueConverter
{

    public Object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null )
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

I've tried changing the XAML to this binding

```<code>Visibility="{Binding PortList, Converter={StaticResource PortVisConverter}}"
</code>```

答:
Your binding is failing, so the converter never runs.

```<code>public List<PortResult> PortList = null;
</code>```

declares a field and you can only bind to properties. Changing to:

```<code>public List<PortResult> PortList { get; set; } = null;
</code>```

will solve your first problem; then you need to use INotifyPropertyChanged if you want changes to that property to propagate to the UI.

As an aside, you could have figured this out if you looked at the output window while running and saw System.Data exceptions. Easiest way to debug binding issues :)

Body:
I have a visibility converter for a a DataGrid that should hide the grid when the item source for the grid is null.  The item source is a property of the class for the window.

Here is partial XAML for the window - the window and visibility converter definition and the data grid:

Window:

<Window x:Name="DiagramWindow"
    x:Class="FabricAnalyzer.FabricDiagram"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:FabricAnalyzer"

    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    mc:Ignorable="d"
    Title="FabricDiagram"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>

    <ResourceDictionary>
        <local:SwitchThumbColorConverter x:Key="SwitchThumbColor"/>
        <local:PortThumbColorConverter x:Key="PortThumbColor"/>
        <local:StringLengthVisiblityConverter x:Key="VisConverter"/>
        <local:PortListVisiblityConverter x:Key="PortVisConverter"/>

Datagrid:

<Grid Name="FabricGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <DataGrid Name="SVCPortDataGrid" Grid.Column="0" Width="Auto"
                   Visibility="{Binding Path=PortList, Converter=
    {StaticResource PortVisConverter}}"
                      AutoGenerateColumns="False">

Here is the code behind for the property it should bind to and the VisibilityConverter.  the idea is that if the PortList is null - it will be by default - the DataGrid should stay collapsed.  I have verified that the PortList is null when I want it to be.

 public partial class FabricDiagram : Window
{

    public List<PortResult> PortList = null;

lastly the visibilityconverter.  I have verified in the debugger that it is not getting called.

 public class PortListVisiblityConverter : IValueConverter
{

    public Object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null )
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I've tried changing the XAML to this binding

Visibility="{Binding PortList, Converter={StaticResource PortVisConverter}}"

Body:
Your binding is failing, so the converter never runs.

public List<PortResult> PortList = null;

declares a field and you can only bind to properties. Changing to:

public List<PortResult> PortList { get; set; } = null;

will solve your first problem; then you need to use INotifyPropertyChanged if you want changes to that property to propagate to the UI.

As an aside, you could have figured this out if you looked at the output window while running and saw System.Data exceptions. Easiest way to debug binding issues :)


问:
Split a String into an array in Swift?
Say I have a string here:

```<code>var fullName: String = "First Last"
</code>```

I want to split the string base on white space and assign the values to their respective variables

```<code>var fullNameArr = // something like: fullName.explode(" ")

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
</code>```

Also, sometimes users might not have a last name.

答:
Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Example:

let s = "hi, hello"
let a = s.split(separator: ",")
print(a)

Now you got an array with 'hi' and ' hello'.

ContentLicense: CC BY-SA 4.0

Title: Split a String into an array in Swift?

Body:
Say I have a string here:

var fullName: String = "First Last"

I want to split the string base on white space and assign the values to their respective variables

var fullNameArr = // something like: fullName.explode(" ")

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

Also, sometimes users might not have a last name.


问:
String member variable of an object used in C++ Class template cannot be assigned to
I wrote a class template for an array data structure like so:

```<code>#pragma once
#include <cstdlib>

template<typename T, unsigned int N>
class CArray {
public:
    CArray();
    T& operator [] (unsigned int index);
private:
    T *entries;
};

template<typename T, unsigned int N>
CArray<T, N>::CArray()
{
    entries = (T *)malloc(N*sizeof(T));
}

template<typename T, unsigned int N>
T& CArray<T, N>::operator [] (unsigned int index) {
    if (index >= N) {
        throw ;
    } else {
        return entries[index];
    }
}
</code>```

I wrote a minimal wrapper class that stores string objects, like so:

```<code>#pragma once
#include <string>
using namespace std;

class CEntry
{
public:
    CEntry();
    const string & getSymbol() const;
    void setSymbol(string);
protected:
    string m_value;
};
</code>```

Implementation:

```<code>#include "CEntry.hpp"

CEntry::CEntry() : m_value(""){
}

const string & CEntry::getSymbol() const {
    return  m_value;
}

void CEntry::setSymbol(string value) {
    m_value = value;
}
</code>```

When i execute the following main:

```<code>#include <iostream>
#include <string>

#include "CEntry.hpp"
#include "CArray.hpp"

int main(int argc, char** argv) {
    CArray<CEntry, 2000> test;
    test[0].setSymbol("asdf");
    cout << test[0].getSymbol();
}
</code>```

The program crashes with a segmentation fault.
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ffad1783f2a in msvcrt!memmove () from C:\WINDOWS\System32\msvcrt.dll

I inspected the program and the crash happens directly in the line of CEntry, where m_value gets assigned to the passed value (in the setSymbol function).
I am using eclipse on windows. I inspected the m_value variable before assignment and it shows suspect values, e.g. 13451671603782742029 for the string length? Could it be that the CEntry object was initialized but not it's member variables?

I've tried researching but cannot figure out whats happening here, thanks in advance.

答:
Your program is crashing because you are accessing unconstructed string objects.

When you use malloc to allocate memory, the memory is uninitialized and the objects you are trying to use have not been constructed.  This is Undefined Behavior and, in this case, is causing the crash.

Body:
I wrote a class template for an array data structure like so:

#pragma once
#include <cstdlib>

template<typename T, unsigned int N>
class CArray {
public:
    CArray();
    T& operator [] (unsigned int index);
private:
    T *entries;
};

template<typename T, unsigned int N>
CArray<T, N>::CArray()
{
    entries = (T *)malloc(N*sizeof(T));
}

template<typename T, unsigned int N>
T& CArray<T, N>::operator [] (unsigned int index) {
    if (index >= N) {
        throw ;
    } else {
        return entries[index];
    }
}

I wrote a minimal wrapper class that stores string objects, like so:

#pragma once
#include <string>
using namespace std;

class CEntry
{
public:
    CEntry();
    const string & getSymbol() const;
    void setSymbol(string);
protected:
    string m_value;
};

Implementation:

#include "CEntry.hpp"

CEntry::CEntry() : m_value(""){
}

const string & CEntry::getSymbol() const {
    return  m_value;
}

void CEntry::setSymbol(string value) {
    m_value = value;
}

When i execute the following main:

#include <iostream>
#include <string>

#include "CEntry.hpp"
#include "CArray.hpp"

int main(int argc, char** argv) {
    CArray<CEntry, 2000> test;
    test[0].setSymbol("asdf");
    cout << test[0].getSymbol();
}

The program crashes with a segmentation fault.
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ffad1783f2a in msvcrt!memmove () from C:\WINDOWS\System32\msvcrt.dll

I inspected the program and the crash happens directly in the line of CEntry, where m_value gets assigned to the passed value (in the setSymbol function).
I am using eclipse on windows. I inspected the m_value variable before assignment and it shows suspect values, e.g. 13451671603782742029 for the string length? Could it be that the CEntry object was initialized but not it's member variables?

I've tried researching but cannot figure out whats happening here, thanks in advance.


问:
MVC 5 -> MVC 5.1 Migration. Intellisense issues
I just updated my project to MVC 5.1 from MVC 5. The main web.config file got updated automatically, but web.configs under main View and Areas folders weren't changed. I suspect that's why now I lost both intellisense and resharper support for my actions, controllers and areas.

Does anyone know correct web.config content for MVC 5.1 Views? Just replacing 3.0.0.0 to 3.1.0.0 and 5.0.0.0 -> 5.1.0.0 did not solve the issue.

It happens in both Visual Studio 2012 and 2013 Professional.

答:
Update NuGet Packages in Package Manager Console.

Verify the current version of System.web.MVC and update it in the Views/Web.config file and also verify the version in Web.config of Root folder.


问:
QLPreviewController and UIWebView do not display filled PDFs
I have a PDFthat has text boxes in it. My program uses Xfinium PDF software to fill the text boxes. When I view the filled in PDF the document shows up with no data in the fields. I have tried using QLPreviewController and UIWebView and they both do not display the filled in fields; however, if I email the document to myself and open it in Adobe DC on the iPad all the data shows up correctly. It may be important to note that even the mail app does not show the PDF correctly filled in.
Here is the PDF opened in Adobe on iPad

Here is the PDF opened in UIWebView in my app (also shows same way in QLPreviewController

答:
Thanks,
It works for me.

pdfDocumentObject.Form.FlattenFormFields();

Bala.