问:
Parse Forecast_IO API Response with Rails

Hi, I've got an API call in my controller

```<code>@dailyForecast = ForecastIO.forecast(37.8267,-122.4233).daily.data.to_json
</code>```

I'm trying to iterate through the JSON response and print out the summary for each item in the response.

In my view I have<%=JSON.parse(@dailyForecast%>

The response has 8 items in it. each one corresponding to the current and next 7 days.

What I'm hoping to get is a list of all times, but I can't seem to just parse the time and print it out.

The response I'm getting is

[{"time"=>1512460800, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512486716, "sunsetTime"=>1512521519, "moonPhase"=>0.58, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0006, "precipIntensityMaxTime"=>1512500400, "precipProbability"=>0.06, "precipType"=>"rain", "temperatureHigh"=>64.54, "temperatureHighTime"=>1512514800, "temperatureLow"=>47.44, "temperatureLowTime"=>1512572400, "apparentTemperatureHigh"=>64.54, "apparentTemperatureHighTime"=>1512514800, "apparentTemperatureLow"=>44.22, "apparentTemperatureLowTime"=>1512572400, "dewPoint"=>30.15, "humidity"=>0.39, "pressure"=>1023.77, "windSpeed"=>1.68, "windGust"=>8.69, "windGustTime"=>1512460800, "windBearing"=>5, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512500400, "visibility"=>10, "ozone"=>297.16, "temperatureMin"=>48.29, "temperatureMinTime"=>1512486000, "temperatureMax"=>64.54, "temperatureMaxTime"=>1512514800, "apparentTemperatureMin"=>48.29, "apparentTemperatureMinTime"=>1512486000, "apparentTemperatureMax"=>64.54, "apparentTemperatureMaxTime"=>1512514800}, {"time"=>1512547200, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512573168, "sunsetTime"=>1512607917, "moonPhase"=>0.62, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1512561600, "precipProbability"=>0.09, "precipType"=>"rain", "temperatureHigh"=>62.86, "temperatureHighTime"=>1512604800, "temperatureLow"=>48.56, "temperatureLowTime"=>1512658800, "apparentTemperatureHigh"=>62.86, "apparentTemperatureHighTime"=>1512604800, "apparentTemperatureLow"=>43.79, "apparentTemperatureLowTime"=>1512658800, "dewPoint"=>34.95, "humidity"=>0.48, "pressure"=>1025.29, "windSpeed"=>6.22, "windGust"=>16.92, "windGustTime"=>1512583200, "windBearing"=>46, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512586800, "visibility"=>10, "ozone"=>278.87, "temperatureMin"=>47.44, "temperatureMinTime"=>1512572400, "temperatureMax"=>62.86, "temperatureMaxTime"=>1512604800, "apparentTemperatureMin"=>44.22, "apparentTemperatureMinTime"=>1512572400, "apparentTemperatureMax"=>62.86, "apparentTemperatureMaxTime"=>1512604800}, {"time"=>1512633600, "summary"=>"Partly cloudy starting in the evening.", "icon"=>"partly-cloudy-night", "sunriseTime"=>1512659619, "sunsetTime"=>1512694317, "moonPhase"=>0.66, "precipIntensity"=>0, "precipIntensityMax"=>0.0002, "precipIntensityMaxTime"=>1512698400, "precipProbability"=>0, "temperatureHigh"=>63.83, "temperatureHighTime"=>1512687600, "temperatureLow"=>48.42, "temperatureLowTime"=>1512745200, "apparentTemperatureHigh"=>63.83, "apparentTemperatureHighTime"=>1512687600, "apparentTemperatureLow"=>44.92, "apparentTemperatureLowTime"=>1512745200, "dewPoint"=>33.82, "humidity"=>0.44, "pressure"=>1028.91, "windSpeed"=>7.95, "windGust"=>25.41, "windGustTime"=>1512658800, "windBearing"=>55, "cloudCover"=>0.18, "uvIndex"=>2, "uvIndexTime"=>1512673200, "visibility"=>10, "ozone"=>258.06, "temperatureMin"=>48.56, "temperatureMinTime"=>1512658800, "temperatureMax"=>63.83, "temperatureMaxTime"=>1512687600, "apparentTemperatureMin"=>43.79, "apparentTemperatureMinTime"=>1512658800, "apparentTemperatureMax"=>63.83, "apparentTemperatureMaxTime"=>1512687600}, {"time"=>1512720000, "summary"=>"Mostly cloudy throughout the day.", "icon"=>"partly-cloudy-day", "sunriseTime"=>1512746069, "sunsetTime"=>1512780719, "moonPhase"=>0.69, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0001, "precipIntensityMaxTime"=>1512734400, "precipProbability"=>0.07, "precipType"=>"rain", "temperatureHigh"=>61.45, "temperatureHighTime"=>1512777600, "temperatureLow"=>48.15, "temperatureLowTime"=>1512831600, "apparentTemperatureHigh"=>61.45, "apparentTemperatureHighTime"=>1512777600, "apparentTemperatureLow"=>44.44, "apparentTemperatureLowTime"=>1512831600, "dewPoint"=>34.61, "humidity"=>0.47, "pressure"=>1031.01, "windSpeed"=>5.99, "windGust"=>13.87, "windGustTime"=>1512756000, "windBearing"=>51, "cloudCover"=>0.77, "uvIndex"=>1, "uvIndexTime"=>1512752400, "visibility"=>10, "ozone"=>269.7, "temperatureMin"=>48.42, "temperatureMinTime"=>1512745200, "temperatureMax"=>61.45, "temperatureMaxTime"=>1512777600, "apparentTemperatureMin"=>44.92, "apparentTemperatureMinTime"=>1512745200, "apparentTemperatureMax"=>61.45, "apparentTemperatureMaxTime"=>1512777600}, {"time"=>1512806400, "summary"=>"Partly cloudy in the morning.", "icon"=>"partly-cloudy-night", "sunriseTime"=>1512832517, "sunsetTime"=>1512867123, "moonPhase"=>0.73, "precipIntensity"=>0, "precipIntensityMax"=>0.0001, "precipIntensityMaxTime"=>1512806400, "precipProbability"=>0, "temperatureHigh"=>62.74, "temperatureHighTime"=>1512864000, "temperatureLow"=>50.62, "temperatureLowTime"=>1512918000, "apparentTemperatureHigh"=>62.74, "apparentTemperatureHighTime"=>1512864000, "apparentTemperatureLow"=>50.62, "apparentTemperatureLowTime"=>1512918000, "dewPoint"=>35.49, "humidity"=>0.49, "pressure"=>1025.93, "windSpeed"=>6.93, "windGust"=>12.55, "windGustTime"=>1512842400, "windBearing"=>48, "cloudCover"=>0.33, "uvIndex"=>2, "uvIndexTime"=>1512846000, "ozone"=>283.11, "temperatureMin"=>48.15, "temperatureMinTime"=>1512831600, "temperatureMax"=>62.74, "temperatureMaxTime"=>1512864000, "apparentTemperatureMin"=>44.44, "apparentTemperatureMinTime"=>1512831600, "apparentTemperatureMax"=>62.74, "apparentTemperatureMaxTime"=>1512864000}, {"time"=>1512892800, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512918964, "sunsetTime"=>1512953528, "moonPhase"=>0.76, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1512896400, "precipProbability"=>0.08, "precipType"=>"rain", "temperatureHigh"=>62.47, "temperatureHighTime"=>1512950400, "temperatureLow"=>50.61, "temperatureLowTime"=>1513004400, "apparentTemperatureHigh"=>62.47, "apparentTemperatureHighTime"=>1512950400, "apparentTemperatureLow"=>50.61, "apparentTemperatureLowTime"=>1513004400, "dewPoint"=>34.72, "humidity"=>0.45, "pressure"=>1023.18, "windSpeed"=>7.76, "windGust"=>16.21, "windGustTime"=>1512928800, "windBearing"=>54, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512932400, "ozone"=>282.43, "temperatureMin"=>50.62, "temperatureMinTime"=>1512918000, "temperatureMax"=>62.47, "temperatureMaxTime"=>1512950400, "apparentTemperatureMin"=>50.62, "apparentTemperatureMinTime"=>1512918000, "apparentTemperatureMax"=>62.47, "apparentTemperatureMaxTime"=>1512950400}, {"time"=>1512979200, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1513005410, "sunsetTime"=>1513039936, "moonPhase"=>0.8, "precipIntensity"=>0, "precipIntensityMax"=>0, "precipProbability"=>0, "temperatureHigh"=>64.19, "temperatureHighTime"=>1513033200, "temperatureLow"=>48.85, "temperatureLowTime"=>1513090800, "apparentTemperatureHigh"=>64.19, "apparentTemperatureHighTime"=>1513033200, "apparentTemperatureLow"=>46.51, "apparentTemperatureLowTime"=>1513090800, "dewPoint"=>36.65, "humidity"=>0.48, "pressure"=>1025.06, "windSpeed"=>4.75, "windGust"=>11.56, "windGustTime"=>1513015200, "windBearing"=>38, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1513018800, "ozone"=>315.21, "temperatureMin"=>50.61, "temperatureMinTime"=>1513004400, "temperatureMax"=>64.19, "temperatureMaxTime"=>1513033200, "apparentTemperatureMin"=>50.61, "apparentTemperatureMinTime"=>1513004400, "apparentTemperatureMax"=>64.19, "apparentTemperatureMaxTime"=>1513033200}, {"time"=>1513065600, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1513091855, "sunsetTime"=>1513126347, "moonPhase"=>0.83, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1513069200, "precipProbability"=>0.08, "precipType"=>"rain", "temperatureHigh"=>63.42, "temperatureHighTime"=>1513119600, "temperatureLow"=>49.53, "temperatureLowTime"=>1513177200, "apparentTemperatureHigh"=>63.42, "apparentTemperatureHighTime"=>1513119600, "apparentTemperatureLow"=>47.18, "apparentTemperatureLowTime"=>1513177200, "dewPoint"=>36.66, "humidity"=>0.49, "pressure"=>1023.65, "windSpeed"=>4.19, "windGust"=>12.25, "windGustTime"=>1513101600, "windBearing"=>28, "cloudCover"=>0.02, "uvIndex"=>2, "uvIndexTime"=>1513105200, "ozone"=>318.34, "temperatureMin"=>48.85, "temperatureMinTime"=>1513090800, "temperatureMax"=>63.42, "temperatureMaxTime"=>1513119600, "apparentTemperatureMin"=>46.51, "apparentTemperatureMinTime"=>1513090800, "apparentTemperatureMax"=>63.42, "apparentTemperatureMaxTime"=>1513119600}]

Body:
Hi, I've got an API call in my controller

@dailyForecast = ForecastIO.forecast(37.8267,-122.4233).daily.data.to_json

I'm trying to iterate through the JSON response and print out the summary for each item in the response.

In my view I have<%=JSON.parse(@dailyForecast%>

The response has 8 items in it. each one corresponding to the current and next 7 days.

What I'm hoping to get is a list of all times, but I can't seem to just parse the time and print it out.

The response I'm getting is

[{"time"=>1512460800, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512486716, "sunsetTime"=>1512521519, "moonPhase"=>0.58, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0006, "precipIntensityMaxTime"=>1512500400, "precipProbability"=>0.06, "precipType"=>"rain", "temperatureHigh"=>64.54, "temperatureHighTime"=>1512514800, "temperatureLow"=>47.44, "temperatureLowTime"=>1512572400, "apparentTemperatureHigh"=>64.54, "apparentTemperatureHighTime"=>1512514800, "apparentTemperatureLow"=>44.22, "apparentTemperatureLowTime"=>1512572400, "dewPoint"=>30.15, "humidity"=>0.39, "pressure"=>1023.77, "windSpeed"=>1.68, "windGust"=>8.69, "windGustTime"=>1512460800, "windBearing"=>5, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512500400, "visibility"=>10, "ozone"=>297.16, "temperatureMin"=>48.29, "temperatureMinTime"=>1512486000, "temperatureMax"=>64.54, "temperatureMaxTime"=>1512514800, "apparentTemperatureMin"=>48.29, "apparentTemperatureMinTime"=>1512486000, "apparentTemperatureMax"=>64.54, "apparentTemperatureMaxTime"=>1512514800}, {"time"=>1512547200, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512573168, "sunsetTime"=>1512607917, "moonPhase"=>0.62, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1512561600, "precipProbability"=>0.09, "precipType"=>"rain", "temperatureHigh"=>62.86, "temperatureHighTime"=>1512604800, "temperatureLow"=>48.56, "temperatureLowTime"=>1512658800, "apparentTemperatureHigh"=>62.86, "apparentTemperatureHighTime"=>1512604800, "apparentTemperatureLow"=>43.79, "apparentTemperatureLowTime"=>1512658800, "dewPoint"=>34.95, "humidity"=>0.48, "pressure"=>1025.29, "windSpeed"=>6.22, "windGust"=>16.92, "windGustTime"=>1512583200, "windBearing"=>46, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512586800, "visibility"=>10, "ozone"=>278.87, "temperatureMin"=>47.44, "temperatureMinTime"=>1512572400, "temperatureMax"=>62.86, "temperatureMaxTime"=>1512604800, "apparentTemperatureMin"=>44.22, "apparentTemperatureMinTime"=>1512572400, "apparentTemperatureMax"=>62.86, "apparentTemperatureMaxTime"=>1512604800}, {"time"=>1512633600, "summary"=>"Partly cloudy starting in the evening.", "icon"=>"partly-cloudy-night", "sunriseTime"=>1512659619, "sunsetTime"=>1512694317, "moonPhase"=>0.66, "precipIntensity"=>0, "precipIntensityMax"=>0.0002, "precipIntensityMaxTime"=>1512698400, "precipProbability"=>0, "temperatureHigh"=>63.83, "temperatureHighTime"=>1512687600, "temperatureLow"=>48.42, "temperatureLowTime"=>1512745200, "apparentTemperatureHigh"=>63.83, "apparentTemperatureHighTime"=>1512687600, "apparentTemperatureLow"=>44.92, "apparentTemperatureLowTime"=>1512745200, "dewPoint"=>33.82, "humidity"=>0.44, "pressure"=>1028.91, "windSpeed"=>7.95, "windGust"=>25.41, "windGustTime"=>1512658800, "windBearing"=>55, "cloudCover"=>0.18, "uvIndex"=>2, "uvIndexTime"=>1512673200, "visibility"=>10, "ozone"=>258.06, "temperatureMin"=>48.56, "temperatureMinTime"=>1512658800, "temperatureMax"=>63.83, "temperatureMaxTime"=>1512687600, "apparentTemperatureMin"=>43.79, "apparentTemperatureMinTime"=>1512658800, "apparentTemperatureMax"=>63.83, "apparentTemperatureMaxTime"=>1512687600}, {"time"=>1512720000, "summary"=>"Mostly cloudy throughout the day.", "icon"=>"partly-cloudy-day", "sunriseTime"=>1512746069, "sunsetTime"=>1512780719, "moonPhase"=>0.69, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0001, "precipIntensityMaxTime"=>1512734400, "precipProbability"=>0.07, "precipType"=>"rain", "temperatureHigh"=>61.45, "temperatureHighTime"=>1512777600, "temperatureLow"=>48.15, "temperatureLowTime"=>1512831600, "apparentTemperatureHigh"=>61.45, "apparentTemperatureHighTime"=>1512777600, "apparentTemperatureLow"=>44.44, "apparentTemperatureLowTime"=>1512831600, "dewPoint"=>34.61, "humidity"=>0.47, "pressure"=>1031.01, "windSpeed"=>5.99, "windGust"=>13.87, "windGustTime"=>1512756000, "windBearing"=>51, "cloudCover"=>0.77, "uvIndex"=>1, "uvIndexTime"=>1512752400, "visibility"=>10, "ozone"=>269.7, "temperatureMin"=>48.42, "temperatureMinTime"=>1512745200, "temperatureMax"=>61.45, "temperatureMaxTime"=>1512777600, "apparentTemperatureMin"=>44.92, "apparentTemperatureMinTime"=>1512745200, "apparentTemperatureMax"=>61.45, "apparentTemperatureMaxTime"=>1512777600}, {"time"=>1512806400, "summary"=>"Partly cloudy in the morning.", "icon"=>"partly-cloudy-night", "sunriseTime"=>1512832517, "sunsetTime"=>1512867123, "moonPhase"=>0.73, "precipIntensity"=>0, "precipIntensityMax"=>0.0001, "precipIntensityMaxTime"=>1512806400, "precipProbability"=>0, "temperatureHigh"=>62.74, "temperatureHighTime"=>1512864000, "temperatureLow"=>50.62, "temperatureLowTime"=>1512918000, "apparentTemperatureHigh"=>62.74, "apparentTemperatureHighTime"=>1512864000, "apparentTemperatureLow"=>50.62, "apparentTemperatureLowTime"=>1512918000, "dewPoint"=>35.49, "humidity"=>0.49, "pressure"=>1025.93, "windSpeed"=>6.93, "windGust"=>12.55, "windGustTime"=>1512842400, "windBearing"=>48, "cloudCover"=>0.33, "uvIndex"=>2, "uvIndexTime"=>1512846000, "ozone"=>283.11, "temperatureMin"=>48.15, "temperatureMinTime"=>1512831600, "temperatureMax"=>62.74, "temperatureMaxTime"=>1512864000, "apparentTemperatureMin"=>44.44, "apparentTemperatureMinTime"=>1512831600, "apparentTemperatureMax"=>62.74, "apparentTemperatureMaxTime"=>1512864000}, {"time"=>1512892800, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1512918964, "sunsetTime"=>1512953528, "moonPhase"=>0.76, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1512896400, "precipProbability"=>0.08, "precipType"=>"rain", "temperatureHigh"=>62.47, "temperatureHighTime"=>1512950400, "temperatureLow"=>50.61, "temperatureLowTime"=>1513004400, "apparentTemperatureHigh"=>62.47, "apparentTemperatureHighTime"=>1512950400, "apparentTemperatureLow"=>50.61, "apparentTemperatureLowTime"=>1513004400, "dewPoint"=>34.72, "humidity"=>0.45, "pressure"=>1023.18, "windSpeed"=>7.76, "windGust"=>16.21, "windGustTime"=>1512928800, "windBearing"=>54, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1512932400, "ozone"=>282.43, "temperatureMin"=>50.62, "temperatureMinTime"=>1512918000, "temperatureMax"=>62.47, "temperatureMaxTime"=>1512950400, "apparentTemperatureMin"=>50.62, "apparentTemperatureMinTime"=>1512918000, "apparentTemperatureMax"=>62.47, "apparentTemperatureMaxTime"=>1512950400}, {"time"=>1512979200, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1513005410, "sunsetTime"=>1513039936, "moonPhase"=>0.8, "precipIntensity"=>0, "precipIntensityMax"=>0, "precipProbability"=>0, "temperatureHigh"=>64.19, "temperatureHighTime"=>1513033200, "temperatureLow"=>48.85, "temperatureLowTime"=>1513090800, "apparentTemperatureHigh"=>64.19, "apparentTemperatureHighTime"=>1513033200, "apparentTemperatureLow"=>46.51, "apparentTemperatureLowTime"=>1513090800, "dewPoint"=>36.65, "humidity"=>0.48, "pressure"=>1025.06, "windSpeed"=>4.75, "windGust"=>11.56, "windGustTime"=>1513015200, "windBearing"=>38, "cloudCover"=>0, "uvIndex"=>2, "uvIndexTime"=>1513018800, "ozone"=>315.21, "temperatureMin"=>50.61, "temperatureMinTime"=>1513004400, "temperatureMax"=>64.19, "temperatureMaxTime"=>1513033200, "apparentTemperatureMin"=>50.61, "apparentTemperatureMinTime"=>1513004400, "apparentTemperatureMax"=>64.19, "apparentTemperatureMaxTime"=>1513033200}, {"time"=>1513065600, "summary"=>"Clear throughout the day.", "icon"=>"clear-day", "sunriseTime"=>1513091855, "sunsetTime"=>1513126347, "moonPhase"=>0.83, "precipIntensity"=>0.0001, "precipIntensityMax"=>0.0003, "precipIntensityMaxTime"=>1513069200, "precipProbability"=>0.08, "precipType"=>"rain", "temperatureHigh"=>63.42, "temperatureHighTime"=>1513119600, "temperatureLow"=>49.53, "temperatureLowTime"=>1513177200, "apparentTemperatureHigh"=>63.42, "apparentTemperatureHighTime"=>1513119600, "apparentTemperatureLow"=>47.18, "apparentTemperatureLowTime"=>1513177200, "dewPoint"=>36.66, "humidity"=>0.49, "pressure"=>1023.65, "windSpeed"=>4.19, "windGust"=>12.25, "windGustTime"=>1513101600, "windBearing"=>28, "cloudCover"=>0.02, "uvIndex"=>2, "uvIndexTime"=>1513105200, "ozone"=>318.34, "temperatureMin"=>48.85, "temperatureMinTime"=>1513090800, "temperatureMax"=>63.42, "temperatureMaxTime"=>1513119600, "apparentTemperatureMin"=>46.51, "apparentTemperatureMinTime"=>1513090800, "apparentTemperatureMax"=>63.42, "apparentTemperatureMaxTime"=>1513119600}]

Body:
You can parse the time as follow:

Use Time.at

Example:

irb(main):084:0> @dailyForecast.map {|hash| Time.at(hash["time"]) }

=> [2017-12-05 03:00:00 -0500, 2017-12-06 03:00:00 -0500, 2017-12-07 03:00:00
-0500, 2017-12-08 03:00:00 -0500, 2017-12-09 03:00:00 -0500, 2017-12-10
03:00:00 -0500, 2017-12-11 03:00:00 -0500, 2017-12-12 03:00:00 -0500]

Make sure you check how to format the time.

There is also a Ruby gem for retrieving data from the Forecast Weather API.
https://github.com/darkskyapp/forecast-ruby


来源: stackexchange

问:
Regular expression in distinct texts
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

```<code>referente[,;]*\s\S\s(.+)\.\sOnde
</code>```

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

答:
I am not sure why you want to match/embolden the trailing punctuation and Onde/Where substring.

I would recommend this pattern to optionally match referente then the à then the all-caps words to follow.  There are no capture groups, just replace the fullstring with the emboldened fullstring.

(I don't use nsregularexpression, so let me know if something is simply not right.)

```<code>/(?:referente )?à [A-Z]+(?: [A-Z]+)*/u
</code>```

The unicode flag is to accommodate the accented letters that will be encountered.

Pattern Demo

p.s. In your "solution" you are incorporating [,;]* but that doesn't get represented in your sample strings, so I left it out.  Reducing the total number of parenthetical groups delivers improved pattern efficiency -- that is why I use just two non-capturing groups.

ContentLicense: CC BY-SA 3.0

Title: Regular expression in distinct texts

Body:
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

referente[,;]*\s\S\s(.+)\.\sOnde

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

Body:
I am not sure why you want to match/embolden the trailing punctuation and Onde/Where substring.

I would recommend this pattern to optionally match referente then the à then the all-caps words to follow.  There are no capture groups, just replace the fullstring with the emboldened fullstring.

(I don't use nsregularexpression, so let me know if something is simply not right.)

/(?:referente )?à [A-Z]+(?: [A-Z]+)*/u

The unicode flag is to accommodate the accented letters that will be encountered.

Pattern Demo

p.s. In your "solution" you are incorporating [,;]* but that doesn't get represented in your sample strings, so I left it out.  Reducing the total number of parenthetical groups delivers improved pattern efficiency -- that is why I use just two non-capturing groups.


问:
Generic class inheritance in Swift
I have the following class:

```<code>class BaseCache<T: Equatable>: NSObject {

    var allEntities = [T]()

    // MARK: - Append

    func appendEntities(newEntities: [T]) {
        ....
    }
}
</code>```

Now I want to subclass it, but I get annoying error, that my type "does not conform to protocol 'Equatable'":

It seems generics in Swift are real pain-in-the-ass.

答:
this should work: < swift 4 >

```<code>class TrackingCache<T: AftershipTracking>: BaseCache<T>
</code>```

Another example:

```<code>protocol P {

}

class C: P {

}

class CS: C {

}

class L<T:P> {
    let c: T

    init(_ c: T) {
        self.c = c
    }
}

class LS<T:CS>:L<T> {

}

let i = LS(CS())

i.c
</code>```

c is CS now.

Title: Generic class inheritance in Swift

Body:
I have the following class:

class BaseCache<T: Equatable>: NSObject {

    var allEntities = [T]()

    // MARK: - Append

    func appendEntities(newEntities: [T]) {
        ....
    }
}

Now I want to subclass it, but I get annoying error, that my type "does not conform to protocol 'Equatable'":

It seems generics in Swift are real pain-in-the-ass.

Body:
this should work: < swift 4 >

class TrackingCache<T: AftershipTracking>: BaseCache<T>

Another example:

protocol P {

}

class C: P {

}

class CS: C {

}

class L<T:P> {
    let c: T

    init(_ c: T) {
        self.c = c
    }
}

class LS<T:CS>:L<T> {

}

let i = LS(CS())

i.c

c is CS now.


问:
How to divide the current price to the last price in the same column in sql
How can I divide ((89-95)/95)*100 or ((95-100)/100)*100

```<code> CREATE TABLE `priceindex` (
          `priceIndexId` int(11) NOT NULL,
          `Date` date DEFAULT NULL,
          `Price` decimal(31,9) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

priceIndexId |    Date    | Price | Currentvalue/previous value
      1      | 2017-11-30 |  100  |
      2      | 2017-12-06 |  95   | answer should be(95-100)/100)*100 = -0.50
      3      | 2017-12-13 |  89   | answer should be(89-95)/95)*100 = -0.63
</code>```

Thanks in advance

答:
You need to get the previous value.  One method uses a correlated subquery.  I would suggest using a subquery for the calculation:</p>

```<code>select pi.priceIndexId, pi.Date, pi.Price,
       (pi.Price - pi.prev_price) / pi.prev_price as change
from (select pi.*,
             (select pi2.price
              from priceindex pi2
              where pi2.date < pi.date
              order by pi2.date desc
              limit 1
             ) as prev_price
      from priceindex pi
     ) pi;
</code>```

Body:
How can I divide ((89-95)/95)*100 or ((95-100)/100)*100

 CREATE TABLE `priceindex` (
          `priceIndexId` int(11) NOT NULL,
          `Date` date DEFAULT NULL,
          `Price` decimal(31,9) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

priceIndexId |    Date    | Price | Currentvalue/previous value
      1      | 2017-11-30 |  100  |
      2      | 2017-12-06 |  95   | answer should be(95-100)/100)*100 = -0.50
      3      | 2017-12-13 |  89   | answer should be(89-95)/95)*100 = -0.63

Thanks in advance

Body:
You need to get the previous value.  One method uses a correlated subquery.  I would suggest using a subquery for the calculation:

select pi.priceIndexId, pi.Date, pi.Price,
       (pi.Price - pi.prev_price) / pi.prev_price as change
from (select pi.*,
             (select pi2.price
              from priceindex pi2
              where pi2.date < pi.date
              order by pi2.date desc
              limit 1
             ) as prev_price
      from priceindex pi
     ) pi;


答:
In your append function calls you are using slices meaning you work with references, thus no guarantee that the values will remain static as @zerkms mentioned.
What you can do is create a copy of the slice temp returned from the 1st append call and use it in the 2nd append. This will make passing a copy of the temp slice and with that avoiding any interferences.

```<code>package main

import (
    "fmt"
)

func main() {
    fmt.Println(subsets([]int{0, 1, 2, 3, 4}))
}

func subsets(nums []int) [][]int {
    res := [][]int{}

    res = append(res, []int{})
    for i := 0; i < len(nums); i++ {
        for j := range res {
            fmt.Println(i)
            temp := append(res[j], nums[i])
            copy_temp := make([]int, len(temp))
            copy(copy_temp, temp)
            fmt.Println(copy_temp)
            res = append(res, copy_temp)
            fmt.Println(res)
        }
    }

    return res
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Slice append change other elements in Slice

Body:
I'm solving Leetcode question at https://leetcode.com/problems/subsets with Golang and iterative solution. The algorithm is basically trying to add the new element to the existing array. After all, it will generate all of the subsets.

But when some elements added to the existing array solution, it change the other element also. Here's the code I provided. I put some debugging Println also.

package main

import (
    "fmt"
)

func main() {
    fmt.Println(subsets([]int{0, 1, 2, 3, 4}))
}

func subsets(nums []int) [][]int {
    res := [][]int{}

    res = append(res, []int{})
    for i := 0; i < len(nums); i++ {
        for j := range res {
            fmt.Println(i)
            temp := append(res[j], nums[i])
            fmt.Println(temp)
            res = append(res, temp)
            fmt.Println(res)
        }
    }

    return res
}

Output

0
[0]
[[] [0]]
1
[1]
[[] [0] [1]]
1
[0 1]
[[] [0] [1] [0 1]]
2
[2]
[[] [0] [1] [0 1] [2]]
2
[0 2]
[[] [0] [1] [0 1] [2] [0 2]]
2
[1 2]
[[] [0] [1] [0 1] [2] [0 2] [1 2]]
2
[0 1 2]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2]]
3
[3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3]]
3
[0 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3]]
3
[1 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3]]
3
[0 1 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3]]
3
[2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3]]
3
[0 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3]]
3
[1 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3]]
3
[0 1 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3]]
4
[4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4]]
4
[0 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4]]
4
[1 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4]]
4
[0 1 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4]]
4
[2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4] [2 4]]
4
[0 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4]]
4
[1 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] **[0 1 2 3]** [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4]]
4
[0 1 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] **[0 1 2 4]** [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4]]
4
[3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4]]
4
[0 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4]]
4
[1 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4]]
4
[0 1 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4]]
4
[2 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4]]
4
[0 2 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4]]
4
[1 2 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4]]
4
[0 1 2 4 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4] [0 1 2 4 4]]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4] [0 1 2 4 4]]

When it add the [0 1 2 4] element, it also change the existing [0 1 2 3] to [0 1 2 4]. Is there any specific reason why this happen?

Body:
In your append function calls you are using slices meaning you work with references, thus no guarantee that the values will remain static as @zerkms mentioned.
What you can do is create a copy of the slice temp returned from the 1st append call and use it in the 2nd append. This will make passing a copy of the temp slice and with that avoiding any interferences.

package main

import (
    "fmt"
)

func main() {
    fmt.Println(subsets([]int{0, 1, 2, 3, 4}))
}

func subsets(nums []int) [][]int {
    res := [][]int{}

    res = append(res, []int{})
    for i := 0; i < len(nums); i++ {
        for j := range res {
            fmt.Println(i)
            temp := append(res[j], nums[i])
            copy_temp := make([]int, len(temp))
            copy(copy_temp, temp)
            fmt.Println(copy_temp)
            res = append(res, copy_temp)
            fmt.Println(res)
        }
    }

    return res
}


问:
Extract a value from within a nested key python
I need to extract out a specific value from within a nested key in python
for example from the below I want to extract out the Start from the key Params

```<code>{'Key': 'Params', 'Value': `'{"Shut":false,"Remove":false,"SnapshotRequired":false,"Start":"Never","End":"Never"}'}
</code>```

This is as far as I have got

```<code>            for tag in i["Tags"]:
            if 'Params' in tag['Key']:
</code>```

then I can get the value but this is the whole string.

答:
You can use dict.get(key) method to get a value of the key you specify in get(), where dict is variable which stores your dictionary.

Also you can use dict[key]. It gives the same result.

In your case, for example, dict['Key'] will return 'Params',
dict['Value'] will return nested dictionary.

Body:
I need to extract out a specific value from within a nested key in python
for example from the below I want to extract out the Start from the key Params

{'Key': 'Params', 'Value': `'{"Shut":false,"Remove":false,"SnapshotRequired":false,"Start":"Never","End":"Never"}'}

This is as far as I have got

            for tag in i["Tags"]:
            if 'Params' in tag['Key']:

then I can get the value but this is the whole string.


问:
CouchRest - checking if document id exists
I've probably just missed it in obvious doco but I can't work out how to check if a doc exists in my db using CouchRest.

I tried db.get(id) but that throws a 404 in my application, and it seems kind of silly to have to try/ catch my way around it.

Is there a simple way to say "if this ID exists -> update, else -> create"?

答:
Fully working function based on previous stacker comment (i add ['_rev'] to query):</p>

```<code>def save_or_create(db, doc)
    begin
      rev = db.get(doc['_id'])['_rev']
      doc['_rev'] = rev
      db.save_doc(doc)
    rescue RestClient::ResourceNotFound => nfe
      db.save_doc(doc)
    end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Fully working function based on previous stacker comment (i add ['_rev'] to query):

def save_or_create(db, doc)
    begin
      rev = db.get(doc['_id'])['_rev']
      doc['_rev'] = rev
      db.save_doc(doc)
    rescue RestClient::ResourceNotFound => nfe
      db.save_doc(doc)
    end
end


问:
Creating a matrix from spatial data
I have created a large number of centroids (84) based off of home ranges.  All of these centroids are individual Formal Class SpatialPoints, saved as values; here are four examples:

```<code>> C004cen
SpatialPoints:
              x        y
homerange -122.7916 42.87038
Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84
+ellps=WGS84 +towgs84=0,0,0

> C006cen
SpatialPoints:
              x        y
homerange -122.5906 42.96253
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

> C008cen
SpatialPoints:
              x        y
homerange -122.5926 42.95456
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

> C012cen
SpatialPoints:
             x        y
homerange -122.567 42.68344
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
</code>```

I would like to create a matrix of these 84 centroids that is essentially 84x84 with the distances between each populating the cells; however I am not quite sure how to go from 84 individual Formal Class SpatialPoints to a matrix.  It would seem the first thing to do would be to combine all of these centroids into a single Formal Class SpatialPoints, but everything I have found so far deals with SpatialPointsDataFrames.  Is it possible to consolidate 84 separate SpatialPoints into a single one?

Thank you RobertH for the command to generate distances.

Title: Creating a matrix from spatial data

Body:
I have created a large number of centroids (84) based off of home ranges.  All of these centroids are individual Formal Class SpatialPoints, saved as values; here are four examples:

> C004cen
SpatialPoints:
              x        y
homerange -122.7916 42.87038
Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84
+ellps=WGS84 +towgs84=0,0,0

> C006cen
SpatialPoints:
              x        y
homerange -122.5906 42.96253
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

> C008cen
SpatialPoints:
              x        y
homerange -122.5926 42.95456
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

> C012cen
SpatialPoints:
             x        y
homerange -122.567 42.68344
Coordinate Reference System (CRS) arguments: +proj=longlat
+datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

I would like to create a matrix of these 84 centroids that is essentially 84x84 with the distances between each populating the cells; however I am not quite sure how to go from 84 individual Formal Class SpatialPoints to a matrix.  It would seem the first thing to do would be to combine all of these centroids into a single Formal Class SpatialPoints, but everything I have found so far deals with SpatialPointsDataFrames.  Is it possible to consolidate 84 separate SpatialPoints into a single one?

Thank you RobertH for the command to generate distances.

Body:
# Please provide example data!
library(raster)
n <- 10
set.seed(123)
x <- runif(n) * 360 - 180
y <- runif(n) * 180 - 90
xy <- SpatialPoints(cbind(x, y), proj4string=CRS('+proj=longlat +datum=WGS84'))
xy
#class       : SpatialPoints
#features    : 10
#extent      : -163.5997, 158.5682, -82.42928, 82.23  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

Given SpatialPoints* object xy, we can do

d <- pointDistance(xy)
round(d/1000)

#       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
# [1,]     0    NA    NA    NA    NA    NA    NA    NA    NA    NA
# [2,] 11799     0    NA    NA    NA    NA    NA    NA    NA    NA
# [3,]  5857 14840     0    NA    NA    NA    NA    NA    NA    NA
# [4,]  9276  4456 14923     0    NA    NA    NA    NA    NA    NA
# [5,] 18285  7930 15556  9508     0    NA    NA    NA    NA    NA
# [6,]  2146 10976  7871  7574 16150     0    NA    NA    NA    NA
# [7,] 14955  9631  9627 13941  6769 17060     0    NA    NA    NA
# [8,] 19451  8406 14380 10604  1285 17416  5524     0    NA    NA
# [9,] 13471  9090  8817 13543  8223 15442  1790  7053     0    NA
#[10,]   901 11372  5594  9377 18842  2829 14231 19647 12662     0

If you want a distance matrix, you can do:

dd <- as.dist(d)

If you do not want the NAs, you can do:

d <- as.matrix(as.dist(d))
round(d/1000)

#       1     2     3     4     5     6     7     8     9    10
#1      0 11799  5857  9276 18285  2146 14955 19451 13471   901
#2  11799     0 14840  4456  7930 10976  9631  8406  9090 11372
#3   5857 14840     0 14923 15556  7871  9627 14380  8817  5594
#4   9276  4456 14923     0  9508  7574 13941 10604 13543  9377
#5  18285  7930 15556  9508     0 16150  6769  1285  8223 18842
#6   2146 10976  7871  7574 16150     0 17060 17416 15442  2829
#7  14955  9631  9627 13941  6769 17060     0  5524  1790 14231
#8  19451  8406 14380 10604  1285 17416  5524     0  7053 19647
#9  13471  9090  8817 13543  8223 15442  1790  7053     0 12662
#10   901 11372  5594  9377 18842  2829 14231 19647 12662     0


问:
Trying to create a function for a button to display two text box answers when the user input is multiplied
```<code>Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnConvert.Click
    Dim result As Decimal
    result = Calc(txtGrams.Text) & Calcul(txtTroyOunces.Text)
    MessageBox.Show(result)

End Sub

Private Function Calc(ByVal a As Decimal) As Decimal
    ' declare variables and convert to decimal
    Dim Grams As Decimal
    a = txtGrams.Text
    Grams = a * 31.1035

    ' determine if text boxes txtGrams and txtTroyOunces is empty
    If String.IsNullOrEmpty(a) Then
        MessageBox.Show("Please enter a number")
    Else
        Return Calc(Grams)

    End If

#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
#Enable Warning BC42353 ' Function doesn't return a value on all code paths

Private Function Calcul(ByVal b As Decimal) As Decimal
    Dim Ounces As Decimal
    b = txtTroyOunces.Text
    Ounces = b * 0.911458
    If String.IsNullOrEmpty(b) Then
        MessageBox.Show("Please enter a number")
    Else
        Return (Ounces)
    End If
#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
#Enable Warning BC42353 ' Function doesn't return a value on all code paths
</code>```

When I click my convert button I get this error:

$exception    {"Exception of type 'System.StackOverflowException' was thrown."}   System.StackOverflowException

答:
Edit: Incidentally, if you're trying to convert troy grams to troy ounces, your conversion factor should be 0.0321507 not 0.911458, but if it's ounces to troy - all good.

Firstly, you shouldn't disable option strict. It makes coding a little harder, but unless your code really needs it disabled, leave it on. It forces you to write better code.

Secondly, your error on your line ..

```<code>result = Calc(txtGrams.Text) & Calcul(txtTroyOunces.Text)
</code>```

While it looks kind of OK, you have a problem that result is declared as a Decimal type, and you probably meant to declare it as a String type - When using string types, the & operator will join two strings together. Fair enough, but in Vb, if you're trying to assign a value to a Decimal type, & does something completely different - it tries to do a logical AND operation on the bitwise values. This is why it is so important to have Option Strict on. This error would have been picked up by the IDE before you had got any further in your code writing.

If you did simply change the declaration of result to a String type, the & operator, will join your numbers with no spaces, hence the changed MessageBox.Show line

Thirdly, do your validation of the TextBoxes in the button click event to make sure that the values entered are valid decimals. Like this..

```<code>Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles Btnconvert.Click
    If IsNumeric(TxtGrams.Text) And IsNumeric(TxtTroyOunces.Text) Then
        Dim grams As Decimal = CDec(Val(TxtGrams.Text))
        Dim troyOunces As Decimal = CDec(Val(TxtTroyOunces.Text))
        Dim convertedToTroy As Decimal = Calc(grams)
        Dim convertedToGrams As Decimal = Calcul(troyOunces)
        MessageBox.Show(convertedToGrams & "g   " & convertedToTroy & "Troy oz")
    Else
        MessageBox.Show("Enter numbers > 0")
    End If
End Sub
</code>```

As you can see there is extra code that gets a numeric value from the TextBoxes ( using Val) and also there I'm using  CDec to convert the numbers to decimals. It looks long winded at the moment, but you'll get used to it.

Also, another coding tip - When you are choosing names for subs and functions, pick a name related to what it does - If you come back to some code six months later, at least you'll have an idea of what it does. It's not so important in the current code as the subs etc are short and it's obvious what they do, but get into the habit anyway. It's a good one to cultivate.

In your original conversion functions, you have the following lines..

```<code>a = txtGrams.Text
</code>```

and

```<code>b = txtTroyOunces.Text
</code>```

these are redundant because when you call the function from your BtnConvert_click handler, the value is already passed to a and b .. you don't need to get it again from the TextBox

Now that your validation is done in the button click, the two calculation functions look much cleaner and you don't need to muck around disabling compiler warnings. Have a look below.

```<code>Private Function ConvertToGrams(ByVal a As Decimal) As Decimal
    Dim Grams As Decimal
    Grams = a * 31.1035D
    Return Grams
End Function

Private Function ConvertToTroy(ByVal b As Decimal) As Decimal
    Dim Ounces As Decimal
    Ounces = b * 0.911458D
    Return (Ounces)
End Function
</code>```

In the two functions above, you'll notice that there is a letter D after each conversion factor. This simply makes sure that the compiler treats the numbers as Decimal types. Another good practice when dealing with literal numbers.

Hope this helps.

If an answer sorts out your problem, don't forget to click the tick next to the answer - It makes sure that the user gets reputation points and makes it easier for anyone else who has the same problem to see that your question has an accepted answer that might work for them as well. (And the person answering the question gets reputation points btw)

Body:
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnConvert.Click
    Dim result As Decimal
    result = Calc(txtGrams.Text) & Calcul(txtTroyOunces.Text)
    MessageBox.Show(result)

End Sub

Private Function Calc(ByVal a As Decimal) As Decimal
    ' declare variables and convert to decimal
    Dim Grams As Decimal
    a = txtGrams.Text
    Grams = a * 31.1035

    ' determine if text boxes txtGrams and txtTroyOunces is empty
    If String.IsNullOrEmpty(a) Then
        MessageBox.Show("Please enter a number")
    Else
        Return Calc(Grams)

    End If

#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
#Enable Warning BC42353 ' Function doesn't return a value on all code paths

Private Function Calcul(ByVal b As Decimal) As Decimal
    Dim Ounces As Decimal
    b = txtTroyOunces.Text
    Ounces = b * 0.911458
    If String.IsNullOrEmpty(b) Then
        MessageBox.Show("Please enter a number")
    Else
        Return (Ounces)
    End If
#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
#Enable Warning BC42353 ' Function doesn't return a value on all code paths

When I click my convert button I get this error:

$exception    {"Exception of type 'System.StackOverflowException' was thrown."}   System.StackOverflowException

Body:
Edit: Incidentally, if you're trying to convert troy grams to troy ounces, your conversion factor should be 0.0321507 not 0.911458, but if it's ounces to troy - all good.

Firstly, you shouldn't disable option strict. It makes coding a little harder, but unless your code really needs it disabled, leave it on. It forces you to write better code.

Secondly, your error on your line ..

result = Calc(txtGrams.Text) & Calcul(txtTroyOunces.Text)

While it looks kind of OK, you have a problem that result is declared as a Decimal type, and you probably meant to declare it as a String type - When using string types, the & operator will join two strings together. Fair enough, but in Vb, if you're trying to assign a value to a Decimal type, & does something completely different - it tries to do a logical AND operation on the bitwise values. This is why it is so important to have Option Strict on. This error would have been picked up by the IDE before you had got any further in your code writing.

If you did simply change the declaration of result to a String type, the & operator, will join your numbers with no spaces, hence the changed MessageBox.Show line

Thirdly, do your validation of the TextBoxes in the button click event to make sure that the values entered are valid decimals. Like this..

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles Btnconvert.Click
    If IsNumeric(TxtGrams.Text) And IsNumeric(TxtTroyOunces.Text) Then
        Dim grams As Decimal = CDec(Val(TxtGrams.Text))
        Dim troyOunces As Decimal = CDec(Val(TxtTroyOunces.Text))
        Dim convertedToTroy As Decimal = Calc(grams)
        Dim convertedToGrams As Decimal = Calcul(troyOunces)
        MessageBox.Show(convertedToGrams & "g   " & convertedToTroy & "Troy oz")
    Else
        MessageBox.Show("Enter numbers > 0")
    End If
End Sub

As you can see there is extra code that gets a numeric value from the TextBoxes ( using Val) and also there I'm using  CDec to convert the numbers to decimals. It looks long winded at the moment, but you'll get used to it.

Also, another coding tip - When you are choosing names for subs and functions, pick a name related to what it does - If you come back to some code six months later, at least you'll have an idea of what it does. It's not so important in the current code as the subs etc are short and it's obvious what they do, but get into the habit anyway. It's a good one to cultivate.

In your original conversion functions, you have the following lines..

a = txtGrams.Text

and

b = txtTroyOunces.Text

these are redundant because when you call the function from your BtnConvert_click handler, the value is already passed to a and b .. you don't need to get it again from the TextBox

Now that your validation is done in the button click, the two calculation functions look much cleaner and you don't need to muck around disabling compiler warnings. Have a look below.

Private Function ConvertToGrams(ByVal a As Decimal) As Decimal
    Dim Grams As Decimal
    Grams = a * 31.1035D
    Return Grams
End Function

Private Function ConvertToTroy(ByVal b As Decimal) As Decimal
    Dim Ounces As Decimal
    Ounces = b * 0.911458D
    Return (Ounces)
End Function

In the two functions above, you'll notice that there is a letter D after each conversion factor. This simply makes sure that the compiler treats the numbers as Decimal types. Another good practice when dealing with literal numbers.

Hope this helps.

If an answer sorts out your problem, don't forget to click the tick next to the answer - It makes sure that the user gets reputation points and makes it easier for anyone else who has the same problem to see that your question has an accepted answer that might work for them as well. (And the person answering the question gets reputation points btw)


问:
Display css and javascript code as it does when files are saved in their format. But inside html file?
I use notepad++ and have got an index.html file that contains css and javascript.

Is there a way to display css and javascript code as it does when files are saved in their format; but in this case inside the html file?

Any editor, software, plugin for notepad++?

答:
You can use JavaScript libraries Highlight.js or Prism.js to highlight the ```</code> and <code><code></code>. Another way is to embed the code with <a href="https://gist.github.com/" rel="nofollow noreferrer">GitHub gist</a>.</p>

<p>Download the javascript library or use the following for Highlight.js:</p>

```<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">

```

<p>Usage:<code>``` --you code goes here-- ```</code>, change the class name to  <code>class="js"</code> for javascript.</p>

<p>For Prism.js:</p>

```<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/themes/prism.min.css">

```

<p>Usage:<code>``` --you code goes here-- ```, change the class name to  class="language-js" for javascript.

Various themes are available for each library.

To embed you code using GitHub gist, paste your code and create public gist. Then copy the embed link provided and paste it on your html.

Body:
You can use JavaScript libraries Highlight.js or Prism.js to highlight the <pre> and <code>. Another way is to embed the code with GitHub gist.

Download the javascript library or use the following for Highlight.js:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

Usage:<pre><code class="css"> --you code goes here-- </code></pre>, change the class name to  class="js" for javascript.

For Prism.js:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/themes/prism.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/prism.min.js"></script>

Usage:<pre><code class="language-css"> --you code goes here-- </code></pre>, change the class name to  class="language-js" for javascript.

Various themes are available for each library.

To embed you code using GitHub gist, paste your code and create public gist. Then copy the embed link provided and paste it on your html.


问:
Cannot horizontally center fixed width div in IE
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

```<code>#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

<body>
  <div id="body">
    <div id="inner_body"></div>
  </div>
</body>
</code>```

What could the issue be?

答:
Set the CSS for your "body" div to include:

```<code>text-align: center;
</code>```

And remove any text-aligns you may have on the "inner_body" div, it should inherit from body.

Body:
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

What could the issue be?

Body:
Set the CSS for your "body" div to include:

text-align: center;

And remove any text-aligns you may have on the "inner_body" div, it should inherit from body.


问:
Visual Studio keeps asking to install Git command prompt tools
Im using Visual Studio 2015 and using Git as my code repo. In Team Explorer it is asking to Install 3rd-party Git command prompt tools, i have restarted VS2015 and restarted my machine and this message still appears under Team Explorer. What i have also noticed is that  when i make changes to any fill and try to commit. I look under Included Changes and the only file that is mentioned is a .suo file , even though i had been making changes to a .cs file.

Update 1:
What i have also noticed  when i go to the file directory and look for a file that i have modified the modified date is not update after i save it.

答:
Actually you can install the 3rd-party Git command prompt tools within the VS Team Explorer.

You can also download the win version to install : https://git-scm.com/download/win

For the changed files can not be identified issue, make sure you have the correct permission to edit/save the files, also check that if you have created the .gitignore file to prevent tracking of specific files. See Use gitignore to prevent tracking of files for details.


问:
How to start main iOS app from companion watch app in background?
Situation:

Since our users have updated their iOS to 11 and/or WatchOS to 4, our iOS app doesn't seem to fire any scheduled timers when the app gets started by our WatchOS app. Maybe we are doing something wrong when starting our main app from the WatchOS app.

Context & code:

Our WatchOS app is a companion app that lets the user start/stop our iPhone app in the background by pressing a button. We do this by using:

```<code>func startMainApp() {
    guard WCSession.default().isReachable == true else {
        print("Watch is not reachable")
        return
    }

    var data = [String : AnyObject]()
    data[WatchActions.actionKey()] = NSNumber.init(value: WatchActions.startApp.rawValue as Int)

    WCSession.default().sendMessage(data, replyHandler: { (result: [String : Any]) in
        let resultNumber = result[WatchActions.resultKey()] as? NSNumber
        let resultBool = resultNumber!.boolValue
        if resultBool == true {
            self.setModeActivated()
        } else {
            self.setModeActivationFailed()
        }

    }) { (error: Error) in
        if (error as NSError).code != 7012 {
            print("start app error: \(error.localizedDescription)")
            self.setModeActivationFailed()
        }
    }
}
</code>```

Then in our main app, we receive the message and start our base controller:

```<code>func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    if let actionNumber : NSNumber = message[WatchActions.actionKey()] as? NSNumber {
        if let watchAction : WatchActions = WatchActions(rawValue: actionNumber.intValue) {

            switch(watchAction) {
                case .isAppActive:
                    let result = BaseController.sharedInstance.sleepAndWakeUpController.isAwake()
                     replyHandler([WatchActions.resultKey() : NSNumber.init(value: result as Bool)])
                return

                case .startApp:
                    AudioController.sharedInstance().playActivatedSound()

                    let isRunningOnForeground = ApplicationStateHelper.isActive()
                    if isRunningOnForeground == false {
                        BaseController.sharedInstance.start(inBackground: true)
                    }
                    let result = true
                    replyHandler([WatchActions.resultKey() : NSNumber.init(value: result as Bool)])

                    DDLogInfo("[APPLE WATCH] [didReceiveMessage] [.startApp]")
                return
            }
        }
    }

    replyHandler([WatchActions.resultKey() : NSNumber.init(value: false as Bool)])
    return
}
</code>```

Everything seems to work as before, we correctly get GPS locations, all our processes get started, however, Timer objects that get started, don't fire.

This worked perfectly before on iOS 10, so I suspect this has something to do with iOS 11 background states that work differently. However, I cannot seem to find any documentation of this.

Extra info:

On iOS 10, when we started our main app this way, the app got visible in the multitask view on the iPhone. Now on iOS 11, it isn't visible in the multitask view, however it does run on background. I successfully see local notifications that I schedule on the background, I can debug through the active code and when tapping the app icon, the app is immediately available.

Our WatchOS app has the deployment target of 2.0

Debugged via XCode with device connected, using Debug-->Attach to PID or Name-->Entered app name. Then start our app from the Apple Watch and debug.

Reproducable on iOS 11.0.3 with WatchOS 4.0 on iPhone 6

Questions:
What is the best way to start our main app from the watch app? Has something changed in iOS 11/WatchOS 4 regarding to background states? Can I find documentation of this? Could this be an iOS bug?

答:
All I can offer you is a confirmation that this behavior did in fact change from iOS 10 to iOS 11. It is my suspicion that the behavior on iOS 10 (and earlier?) was incorrect. Apple doesn't have any qualms about changing behavior that was inadvertent/what they deem incorrect even if developer's come to rely on the behavior (I'm pretty sure I used this behavior on my last watch project).

The fact is that the UIApplication's state when launched by a message from the watch is background. Timer's aren't supposed to run when the application is in the background unless using particular background execution modes/background task. That fact is pretty well known and is usually encountered quite early on in an iOS developer's career. The fact that timer's would run in the background when launched from the watch was, I can surmise, a mistake.

I do not know your use case, i.e. why you were relying on those timers, but one thing you can do that is quite simple is to create an empty background task that will get you a little more time when the app is launched.

```<code>var backgroundTask: UIBackgroundTaskIdentifier?
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "app Start Task", expirationHandler: {
    guard let task = backgroundTask else { return }
    UIApplication.shared.endBackgroundTask(task)
})

let timer = Timer(timeInterval: 1, repeats: true) { (timer) in
    print("Running")
}
</code>```

If you need a more consistent, longer running solution, you may need to leverage your location updates as an opportunity to do whatever work the timer is currently for. There are plenty of other background modes to pursue as well.

Summary of your questions:

Q: What is the best way to start our main app from the watch app?

A: Your proposed code is a great way to launch the companion app.

Q: Has something changed in iOS 11/WatchOS 4 regarding to background states?

A: No, especially in regards to timers. The different behavior is likely a correction.

Q: Can I find documentation of this?

A: I can't. Sometimes you can squeeze this information out of apple engineers on the forums or via the code level support questions through your developer account or go to WWDC.

Q: Could this be an iOS bug?

A: The earlier behavior was likely the bug.

Body:
Situation:

Since our users have updated their iOS to 11 and/or WatchOS to 4, our iOS app doesn't seem to fire any scheduled timers when the app gets started by our WatchOS app. Maybe we are doing something wrong when starting our main app from the WatchOS app.

Context & code:

Our WatchOS app is a companion app that lets the user start/stop our iPhone app in the background by pressing a button. We do this by using:

func startMainApp() {
    guard WCSession.default().isReachable == true else {
        print("Watch is not reachable")
        return
    }

    var data = [String : AnyObject]()
    data[WatchActions.actionKey()] = NSNumber.init(value: WatchActions.startApp.rawValue as Int)

    WCSession.default().sendMessage(data, replyHandler: { (result: [String : Any]) in
        let resultNumber = result[WatchActions.resultKey()] as? NSNumber
        let resultBool = resultNumber!.boolValue
        if resultBool == true {
            self.setModeActivated()
        } else {
            self.setModeActivationFailed()
        }

    }) { (error: Error) in
        if (error as NSError).code != 7012 {
            print("start app error: \(error.localizedDescription)")
            self.setModeActivationFailed()
        }
    }
}

Then in our main app, we receive the message and start our base controller:

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    if let actionNumber : NSNumber = message[WatchActions.actionKey()] as? NSNumber {
        if let watchAction : WatchActions = WatchActions(rawValue: actionNumber.intValue) {

            switch(watchAction) {
                case .isAppActive:
                    let result = BaseController.sharedInstance.sleepAndWakeUpController.isAwake()
                     replyHandler([WatchActions.resultKey() : NSNumber.init(value: result as Bool)])
                return

                case .startApp:
                    AudioController.sharedInstance().playActivatedSound()

                    let isRunningOnForeground = ApplicationStateHelper.isActive()
                    if isRunningOnForeground == false {
                        BaseController.sharedInstance.start(inBackground: true)
                    }
                    let result = true
                    replyHandler([WatchActions.resultKey() : NSNumber.init(value: result as Bool)])

                    DDLogInfo("[APPLE WATCH] [didReceiveMessage] [.startApp]")
                return
            }
        }
    }

    replyHandler([WatchActions.resultKey() : NSNumber.init(value: false as Bool)])
    return
}

Everything seems to work as before, we correctly get GPS locations, all our processes get started, however, Timer objects that get started, don't fire.

This worked perfectly before on iOS 10, so I suspect this has something to do with iOS 11 background states that work differently. However, I cannot seem to find any documentation of this.

Extra info:

On iOS 10, when we started our main app this way, the app got visible in the multitask view on the iPhone. Now on iOS 11, it isn't visible in the multitask view, however it does run on background. I successfully see local notifications that I schedule on the background, I can debug through the active code and when tapping the app icon, the app is immediately available.

Our WatchOS app has the deployment target of 2.0

Debugged via XCode with device connected, using Debug-->Attach to PID or Name-->Entered app name. Then start our app from the Apple Watch and debug.

Reproducable on iOS 11.0.3 with WatchOS 4.0 on iPhone 6

Questions:
What is the best way to start our main app from the watch app? Has something changed in iOS 11/WatchOS 4 regarding to background states? Can I find documentation of this? Could this be an iOS bug?

Body:
All I can offer you is a confirmation that this behavior did in fact change from iOS 10 to iOS 11. It is my suspicion that the behavior on iOS 10 (and earlier?) was incorrect. Apple doesn't have any qualms about changing behavior that was inadvertent/what they deem incorrect even if developer's come to rely on the behavior (I'm pretty sure I used this behavior on my last watch project).

The fact is that the UIApplication's state when launched by a message from the watch is background. Timer's aren't supposed to run when the application is in the background unless using particular background execution modes/background task. That fact is pretty well known and is usually encountered quite early on in an iOS developer's career. The fact that timer's would run in the background when launched from the watch was, I can surmise, a mistake.

I do not know your use case, i.e. why you were relying on those timers, but one thing you can do that is quite simple is to create an empty background task that will get you a little more time when the app is launched.

var backgroundTask: UIBackgroundTaskIdentifier?
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "app Start Task", expirationHandler: {
    guard let task = backgroundTask else { return }
    UIApplication.shared.endBackgroundTask(task)
})

let timer = Timer(timeInterval: 1, repeats: true) { (timer) in
    print("Running")
}

If you need a more consistent, longer running solution, you may need to leverage your location updates as an opportunity to do whatever work the timer is currently for. There are plenty of other background modes to pursue as well.

Summary of your questions:

Q: What is the best way to start our main app from the watch app?

A: Your proposed code is a great way to launch the companion app.

Q: Has something changed in iOS 11/WatchOS 4 regarding to background states?

A: No, especially in regards to timers. The different behavior is likely a correction.

Q: Can I find documentation of this?

A: I can't. Sometimes you can squeeze this information out of apple engineers on the forums or via the code level support questions through your developer account or go to WWDC.

Q: Could this be an iOS bug?

A: The earlier behavior was likely the bug.


问:
Creating a dynamic 2D array to store class objects
So I have a class called Cell, and I need to create a new Cell and put it into a 2d array. I believe the problem is how I created the 2D array. I have looked up how dynamic arrays work but I still can't find the problem. Below is some of my code and the first few errors I get

```<code>    Cell * board = new Cell[h]; //create new board
        for(int i = 0; i < h; i++){
            board[i] = new Cell[w];
            }
        for (int row = 0; row < h; row ++){     //initialize board
            for (int col = 0; col < w; col++){
                board[row][col] = new Cell;
                board[row][col]->status = '#';
                board[row][col]->isCovered = true;
            }
        }
</code>```

ERRORS:

```<code>minesweeper.h: In constructor ‘GameBoard::GameBoard(int, int, int)’:
minesweeper.h:29:17: error: no match for ‘operator=’ (operand types are
‘Cell’ and ‘Cell*’)
    board[i] = new Cell[w];
             ^
minesweeper.h:29:17: note: candidate is:
minesweeper.h:4:8: note: Cell& Cell::operator=(const Cell&)
 struct Cell
    ^
minesweeper.h:4:8: note:   no known conversion for argument 1 from ‘Cell*’
to ‘const Cell&’
minesweeper.h:33:16: error: no match for ‘operator[]’ (operand types are
‘Cell’ and ‘int’)
      board[row][col] = new Cell;
            ^
minesweeper.h:34:16: error: no match for ‘operator[]’ (operand types are
‘Cell’ and ‘int’)
      board[row][col]->status = '#';
                ^
</code>```

答:
Change the line

```<code>Cell* board = new Cell[h]
</code>```

to

```<code>Cell** board = new Cell*[h]
</code>```

Basically you want to create a 2d array, so you need to create and array of Cell pointers (new Cell*[h]). Then for each of those Cell pointers you want to allocate memory for each individual Cell. This is done in the loop:

```<code>for(int i = 0; i < h; i++){
    board[i] = new Cell[w];
}
</code>```

Body:
So I have a class called Cell, and I need to create a new Cell and put it into a 2d array. I believe the problem is how I created the 2D array. I have looked up how dynamic arrays work but I still can't find the problem. Below is some of my code and the first few errors I get

    Cell * board = new Cell[h]; //create new board
        for(int i = 0; i < h; i++){
            board[i] = new Cell[w];
            }
        for (int row = 0; row < h; row ++){     //initialize board
            for (int col = 0; col < w; col++){
                board[row][col] = new Cell;
                board[row][col]->status = '#';
                board[row][col]->isCovered = true;
            }
        }

ERRORS:

minesweeper.h: In constructor ‘GameBoard::GameBoard(int, int, int)’:
minesweeper.h:29:17: error: no match for ‘operator=’ (operand types are
‘Cell’ and ‘Cell*’)
    board[i] = new Cell[w];
             ^
minesweeper.h:29:17: note: candidate is:
minesweeper.h:4:8: note: Cell& Cell::operator=(const Cell&)
 struct Cell
    ^
minesweeper.h:4:8: note:   no known conversion for argument 1 from ‘Cell*’
to ‘const Cell&’
minesweeper.h:33:16: error: no match for ‘operator[]’ (operand types are
‘Cell’ and ‘int’)
      board[row][col] = new Cell;
            ^
minesweeper.h:34:16: error: no match for ‘operator[]’ (operand types are
‘Cell’ and ‘int’)
      board[row][col]->status = '#';
                ^

Body:
Change the line

Cell* board = new Cell[h]

to

Cell** board = new Cell*[h]

Basically you want to create a 2d array, so you need to create and array of Cell pointers (new Cell*[h]). Then for each of those Cell pointers you want to allocate memory for each individual Cell. This is done in the loop:

for(int i = 0; i < h; i++){
    board[i] = new Cell[w];
}


问:
How to add MySQL table column with a default value of another column of the existing row
The current existing table looks like this:

```<code>id    number    amount
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00
</code>```

Now i would like add new column allocated_amount with the default value of the amount column in every existing row.

```<code>id    number    amount      allocated_amount
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00
</code>```

It is possible? Im using MySQL Workbench GUI.

答:
It is not possible as default column. You can write a trigger and do that or add virtual column in Mysql 5.7.

OR

```<code>alter table Tab1 add allocated_amount int;  -- Add column
update Tab1 set allocated_amount= amount;   -- Set the value
</code>```

Or you could create a Virtual Column:

```<code>alter table Table1
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;
</code>```

Body:
The current existing table looks like this:

id    number    amount
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00

Now i would like add new column allocated_amount with the default value of the amount column in every existing row.

id    number    amount      allocated_amount
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00

It is possible? Im using MySQL Workbench GUI.

Body:
It is not possible as default column. You can write a trigger and do that or add virtual column in Mysql 5.7.

OR

alter table Tab1 add allocated_amount int;  -- Add column
update Tab1 set allocated_amount= amount;   -- Set the value

Or you could create a Virtual Column:

alter table Table1
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;


问:
Java Read Text File not completely
I write a program to read line by line result from a text file to check for certain condition using below code.

```<code>for (File f : readAllTxtFile) {
    if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                       ...//do something
                        break;
                    }
                }
   }
 }
</code>```

My question is, why system only read until half of my txt file and stopped ?? it didnt continue reading the next line eventhough the condition if (lineResult.contains("TER_GetCarrierInfo")) is not exist/hit.
My txt file got thousand of line around 900++ kb

Can someone explain with me ?

Thanks and appreaciate

答:
Here is the code i use to simulate your scenario.

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class test {

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

        File dir = new File("/yourpath");
        File[] readAllTxtFile = dir.listFiles();

        for (File f : readAllTxtFile) {
            if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                        //do something
                        break;
                    }
                }
            }

        }

    }

}
</code>```

If you want to check if your program continue to read after 500 line, put 'TER_GetCarrierInfo' in your text file after line 500 and replace the code segment

```<code>if (lineResult.contains("TER_GetCarrierInfo")) {
   System.out.println("Found 'TER_GetCarrierInfo' ");
   break;
}
</code>```

This will show that your program continue even after half of the file is scan.HTH.

Title: Java Read Text File not completely

Body:
I write a program to read line by line result from a text file to check for certain condition using below code.

for (File f : readAllTxtFile) {
    if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                       ...//do something
                        break;
                    }
                }
   }
 }

My question is, why system only read until half of my txt file and stopped ?? it didnt continue reading the next line eventhough the condition if (lineResult.contains("TER_GetCarrierInfo")) is not exist/hit.
My txt file got thousand of line around 900++ kb

Can someone explain with me ?

Thanks and appreaciate

Body:
Here is the code i use to simulate your scenario.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class test {

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

        File dir = new File("/yourpath");
        File[] readAllTxtFile = dir.listFiles();

        for (File f : readAllTxtFile) {
            if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                        //do something
                        break;
                    }
                }
            }

        }

    }

}

If you want to check if your program continue to read after 500 line, put 'TER_GetCarrierInfo' in your text file after line 500 and replace the code segment

if (lineResult.contains("TER_GetCarrierInfo")) {
   System.out.println("Found 'TER_GetCarrierInfo' ");
   break;
}

This will show that your program continue even after half of the file is scan.HTH.


问:
grep on unix / linux: how to replace or capture text?
So I'm pretty good with regular expressions, but I'm having some trouble with them on unix. Here are two things I'd love to know how to do:

1) Replace all text except letters, numbers, and underscore

In PHP I'd do this: (works great)```
preg_replace('#[^a-zA-Z0-9_]#','',$text).
```

In bash I tried this (with limited success); seems like it dosen't allow you to use the full set of regex:  ```
text="my #1 example!"
${text/[^a-zA-Z0-9_]/'')
```

I tried it with sed but it still seems to have problems with the full regex set:

```echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//
```

I'm sure there is a way to do it with grep, too, but it was breaking it into multiple lines when i tried:

```echo abc\!\@\#\$\%\^\&\*\(222 | grep -Eos '[a-zA-Z0-9\_]+'```

And finally I also tried using expr but it seemed like that had really limited support for extended regex...

2) Capture (multiple) parts of text

In PHP I could just do something like this:

```
preg_match('#(word1).*(word2)#',$text,$matches);
```

I'm not sure how that would be possible in *nix...

答:
As an alternative to codaddict's nice answer using sed, you could also use tr for the first part of your question.

```<code>echo "my #1 _ example!" | tr -d -C '[[:alnum:]_]'
</code>```

I've also made use of the [:alnum:] character class, just to show another option.

Body:
So I'm pretty good with regular expressions, but I'm having some trouble with them on unix. Here are two things I'd love to know how to do:

1) Replace all text except letters, numbers, and underscore

In PHP I'd do this: (works great)

preg_replace('#[^a-zA-Z0-9_]#','',$text).

In bash I tried this (with limited success); seems like it dosen't allow you to use the full set of regex:

text="my #1 example!"
${text/[^a-zA-Z0-9_]/'')

I tried it with sed but it still seems to have problems with the full regex set:

echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//

I'm sure there is a way to do it with grep, too, but it was breaking it into multiple lines when i tried:

echo abc\!\@\#\$\%\^\&\*\(222 | grep -Eos '[a-zA-Z0-9\_]+'

And finally I also tried using expr but it seemed like that had really limited support for extended regex...

2) Capture (multiple) parts of text

In PHP I could just do something like this:

preg_match('#(word1).*(word2)#',$text,$matches);

I'm not sure how that would be possible in *nix...

Body:
As an alternative to codaddict's nice answer using sed, you could also use tr for the first part of your question.

echo "my #1 _ example!" | tr -d -C '[[:alnum:]_]'

I've also made use of the [:alnum:] character class, just to show another option.


问:
ag-Grid: set color to FloatingFiler
I am wondering if I could set color to Floating Filter of ag-Grid(picture below), it would be more user-friendly.

If anyone knows, please help me out...

答:
The cellRenderer should help you:

```<code>cellRenderer: function (params) {
  let eHeaderCell = params.eHeaderCell;
  eHeaderCell.style.backgroundColor = 'red';
}
</code>```

Title: ag-Grid: set color to FloatingFiler

Body:
The cellRenderer should help you:

cellRenderer: function (params) {
  let eHeaderCell = params.eHeaderCell;
  eHeaderCell.style.backgroundColor = 'red';
}


问:
VS Code will not build c++ programs with multiple .ccp source files
Note that I'm using VS Code on Ubuntu 17.10 and using the GCC Compiler.

I'm having trouble building a simple program which makes use of additional .ccp files. I'm probably missing something obvious here as I'm fairly new to programming but I'll explain what I've done so far. This is something that is stopping me from continuing with a tutorial I'm doing.

I have written a very simple program to demonstrate my point as follows.

main.ccp

```<code>#include <iostream>
#include "Cat.h"

using namespace std;

int main ()
{

speak();

return 0;
}
</code>```

Cat.h

```<code>#pragma once

void speak();
</code>```

Cat.ccp

```<code>#include <iostream>
#include "Cat.h"

using namespace std;

void speak()
{
std::cout << "Meow!!" << std::endl;

}
</code>```

This simple program builds in both Codeblocks and Visual Studio Community 2017 no problem and I can't figure out what I need to do to make it run.
This error at the bottom indicates that the Cat.ccp file is not being picked up at all. If I was to drop the definition from this Cat.ccp into the header file the program compiles and runs fine but I need to make use of that .ccp file as I understand this is the accepted way of separating code. I'll note that all the files are in the same folder too.

I understand that I may need to tell VS Code where to look for the Cat.ccp file but it's strange to me that it finds the header in the same location. Nevertheless, after looking online I've been reading that I may need to place a directory into the c_cpp_intellisense_properties.json. Here's what mine looks like.

```<code>{
"configurations": [
    {
        "name": "Mac",
        "includePath": [
            "/usr/include",
            "/usr/local/include",
            "${workspaceRoot}"
        ],
        "defines": [],
        "intelliSenseMode": "clang-x64",
        "browse": {
            "path": [
                "/usr/include",
                "/usr/local/include",
                "${workspaceRoot}"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        },
        "macFrameworkPath": [
            "/System/Library/Frameworks",
            "/Library/Frameworks"
        ]
    },
    {
        "name": "Linux",
        "includePath": [
            "/usr/include/c++/7",
            "/usr/include/x86_64-linux-gnu/c++/7",
            "/usr/include/c++/7/backward",
            "/usr/lib/gcc/x86_64-linux-gnu/7/include",
            "/usr/local/include",
            "/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
            "/usr/include/x86_64-linux-gnu",
            "/usr/include",
            "/home/danny/Documents/C++_Projects/24_-_Classes/Cat.cpp",
            "${workspaceRoot}",
            "/home/danny/Documents/C++_Projects/24_-_Classes/",
            "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode",
            "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
        ],
        "defines": [],
        "intelliSenseMode": "clang-x64",
        "browse": {
            "path": [
                "/usr/include/c++/7",
                "/usr/include/x86_64-linux-gnu/c++/7",
                "/usr/include/c++/7/backward",
                "/usr/lib/gcc/x86_64-linux-gnu/7/include",
                "/usr/local/include",
                "/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
                "/usr/include/x86_64-linux-gnu",
                "/usr/include",
                "${workspaceRoot}",
                "/home/danny/Documents/C++_Projects/24_-_Classes/",
                "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        }
    },
    {
        "name": "Win32",
        "includePath": [
            "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include",
            "${workspaceRoot}"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE"
        ],
        "intelliSenseMode": "msvc-x64",
        "browse": {
            "path": [
                "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*",
                "${workspaceRoot}"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        }
    }
],
"version": 3
}
</code>```

At one point I wondered if I need to add a double command in there to tell the compiler to build both .ccp files in the tasks.json but I haven't managed to figure out how to do that, or even if that's the right approach.

tasks.json

```<code>{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
    {
        "label": "Build",
        "type": "shell",
        "command": "g++ -g /home/danny/Documents/C++_Projects/24_-_Classes/main.cpp -o Classes",
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "problemMatcher":"$gcc"
    }
]
}
</code>```

Appreciate any help. And just in case you're wondering, the reason I don't just finish the tutorial in Codeblocks or VS Community is that I like to know what's going on under the hood in most things. Plus I'd like to get VS Code working for me as it's been great so far.

答:
If you have multiple files and one depends on a cpp file for another, you need to tell g++ to compile it as well, so the linker can find it. The simplest way would be:

```<code>$ g++ Cat.cpp main.cpp -o Classes
</code>```

As a side note, you should probably compile with warnings, minimally -Wall, likely -Wextra, and possibly -Wpedantic, so you know if something you're doing is problematic.

Body:
Note that I'm using VS Code on Ubuntu 17.10 and using the GCC Compiler.

I'm having trouble building a simple program which makes use of additional .ccp files. I'm probably missing something obvious here as I'm fairly new to programming but I'll explain what I've done so far. This is something that is stopping me from continuing with a tutorial I'm doing.

I have written a very simple program to demonstrate my point as follows.

main.ccp

#include <iostream>
#include "Cat.h"

using namespace std;

int main ()
{

speak();

return 0;
}

Cat.h

#pragma once

void speak();

Cat.ccp

#include <iostream>
#include "Cat.h"

using namespace std;

void speak()
{
std::cout << "Meow!!" << std::endl;

}

This simple program builds in both Codeblocks and Visual Studio Community 2017 no problem and I can't figure out what I need to do to make it run.
This error at the bottom indicates that the Cat.ccp file is not being picked up at all. If I was to drop the definition from this Cat.ccp into the header file the program compiles and runs fine but I need to make use of that .ccp file as I understand this is the accepted way of separating code. I'll note that all the files are in the same folder too.

I understand that I may need to tell VS Code where to look for the Cat.ccp file but it's strange to me that it finds the header in the same location. Nevertheless, after looking online I've been reading that I may need to place a directory into the c_cpp_intellisense_properties.json. Here's what mine looks like.

{
"configurations": [
    {
        "name": "Mac",
        "includePath": [
            "/usr/include",
            "/usr/local/include",
            "${workspaceRoot}"
        ],
        "defines": [],
        "intelliSenseMode": "clang-x64",
        "browse": {
            "path": [
                "/usr/include",
                "/usr/local/include",
                "${workspaceRoot}"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        },
        "macFrameworkPath": [
            "/System/Library/Frameworks",
            "/Library/Frameworks"
        ]
    },
    {
        "name": "Linux",
        "includePath": [
            "/usr/include/c++/7",
            "/usr/include/x86_64-linux-gnu/c++/7",
            "/usr/include/c++/7/backward",
            "/usr/lib/gcc/x86_64-linux-gnu/7/include",
            "/usr/local/include",
            "/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
            "/usr/include/x86_64-linux-gnu",
            "/usr/include",
            "/home/danny/Documents/C++_Projects/24_-_Classes/Cat.cpp",
            "${workspaceRoot}",
            "/home/danny/Documents/C++_Projects/24_-_Classes/",
            "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode",
            "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
        ],
        "defines": [],
        "intelliSenseMode": "clang-x64",
        "browse": {
            "path": [
                "/usr/include/c++/7",
                "/usr/include/x86_64-linux-gnu/c++/7",
                "/usr/include/c++/7/backward",
                "/usr/lib/gcc/x86_64-linux-gnu/7/include",
                "/usr/local/include",
                "/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
                "/usr/include/x86_64-linux-gnu",
                "/usr/include",
                "${workspaceRoot}",
                "/home/danny/Documents/C++_Projects/24_-_Classes/",
                "/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        }
    },
    {
        "name": "Win32",
        "includePath": [
            "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include",
            "${workspaceRoot}"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE"
        ],
        "intelliSenseMode": "msvc-x64",
        "browse": {
            "path": [
                "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*",
                "${workspaceRoot}"
            ],
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        }
    }
],
"version": 3
}

At one point I wondered if I need to add a double command in there to tell the compiler to build both .ccp files in the tasks.json but I haven't managed to figure out how to do that, or even if that's the right approach.

tasks.json

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
    {
        "label": "Build",
        "type": "shell",
        "command": "g++ -g /home/danny/Documents/C++_Projects/24_-_Classes/main.cpp -o Classes",
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "problemMatcher":"$gcc"
    }
]
}

Appreciate any help. And just in case you're wondering, the reason I don't just finish the tutorial in Codeblocks or VS Community is that I like to know what's going on under the hood in most things. Plus I'd like to get VS Code working for me as it's been great so far.

Body:
If you have multiple files and one depends on a cpp file for another, you need to tell g++ to compile it as well, so the linker can find it. The simplest way would be:

$ g++ Cat.cpp main.cpp -o Classes

As a side note, you should probably compile with warnings, minimally -Wall, likely -Wextra, and possibly -Wpedantic, so you know if something you're doing is problematic.


问:
How to run angular 2 build files on express.js
I want to run index.html and i get it from angular2 app after ng build.

I tried these two lines of code one by one but these are not working for me
app.use(express.static(path.resolve(__dirname+'/public/index.html')));
app.use(express.static(path.resolve(__dirname+'/public')));

Any idea how to resolve this?

Your help will greatly appreciated

答:
I will assume you already have the correct path to your public folder and also the ng build builds out to the public folder with the same path.

Do: app.use(express.static(path.join(__dirname, 'public')));


问:
How to map between int and property c#
In the project I'm working on, (.net Core) we are using a range slider (noUiSlider)to represent quality in a product filter.

Slider

The slider returns an array of numbers as an example [2, 4] would be returned if the slider was set to Good and Excellent and I would need to retrieve all the products that match Good, Very Good, and Excellent in quality.

Here in lies some of the unique problems with this.
The products are pulled from a third party service, and I only receive the quality as the string value. So I need a way to assign a number value to the string value I receive so I can check for all products that have a quality >= to qualityArray[0] and <= to qualityArray[1]

What would be the best way to map between string to int so I can do the >= and <= check with the quality range and at the same time map the int to a string so when displaying the list of products that match the range I only have to display the string value? (Very Good)

I was imagining using an Enum or a Dictionary but I'm not sure what the advantages of either would be.

答:
You need to cast the string value to an enum using Enum.Parse and then parse the enum to a string when required using Enum.ToString

Then you can say
QualitiyValues.Low >= myObject.Quality <= QualityValues.Medium.

Enum String Name from Value

Title: How to map between int and property c#


问:
Repeat Python function call on exception?
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

```<code>try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2
</code>```

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

答:
```<code>
for x in xrange(num_retries):
    try:
        myFunc()
    except MyError, err:
        continue
        #time.sleep(1)
    err = None
    break
if err:
    raise MyError2
#else:
#    print "Success!"

</code>```

Body:
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?