问:
How to filter objects full of arrays based on the value of its property
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

```<code>objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
</code>```

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

```<code>objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];
</code>```

I thought about filtering:

but I am getting nowhere...

Body:
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];

I thought about filtering:

but I am getting nowhere...

Body:
Not the most elegant way, for sure, but it works:

temp_at_15=[];
vals=Object.values(data);
vals.forEach(function(el) {
if(Array.isArray(el))
el.forEach(function(o) {
if(o.dt_txt.includes('15:00:00'))
 temp_at_15.push(o.main.temp);
});
});

console.log(temp_at_15);

Demo:

data = {
  "cod": "200",
  "message": 0.0027,
  "cnt": 40,
  "list": [{
    "dt": 1512658800,
    "main": {
      "temp": 293.55,
      "temp_min": 283.891,
      "temp_max": 293.55,
      "pressure": 763.05,
      "sea_level": 1029.9,
      "grnd_level": 763.05,
      "humidity": 73,
      "temp_kf": 9.66
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.06,
      "deg": 198.002
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-07 15:00:00"
  }, {
    "dt": 1512669600,
    "main": {
      "temp": 299.19,
      "temp_min": 291.944,
      "temp_max": 299.19,
      "pressure": 762.15,
      "sea_level": 1025.76,
      "grnd_level": 762.15,
      "humidity": 45,
      "temp_kf": 7.24
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.31,
      "deg": 199.005
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-07 18:00:00"
  }, {
    "dt": 1512680400,
    "main": {
      "temp": 297.16,
      "temp_min": 292.327,
      "temp_max": 297.16,
      "pressure": 759.96,
      "sea_level": 1021.77,
      "grnd_level": 759.96,
      "humidity": 42,
      "temp_kf": 4.83
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02d"
    }],
    "clouds": {
      "all": 8
    },
    "wind": {
      "speed": 1.35,
      "deg": 205.503
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-07 21:00:00"
  }, {
    "dt": 1512691200,
    "main": {
      "temp": 290.34,
      "temp_min": 287.926,
      "temp_max": 290.34,
      "pressure": 760.22,
      "sea_level": 1023.05,
      "grnd_level": 760.22,
      "humidity": 57,
      "temp_kf": 2.41
    },
    "weather": [{
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02n"
    }],
    "clouds": {
      "all": 20
    },
    "wind": {
      "speed": 1.1,
      "deg": 214.51
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-08 00:00:00"
  }, {
    "dt": 1512702000,
    "main": {
      "temp": 279.389,
      "temp_min": 279.389,
      "temp_max": 279.389,
      "pressure": 761.16,
      "sea_level": 1026.01,
      "grnd_level": 761.16,
      "humidity": 89,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.96,
      "deg": 194.002
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-08 03:00:00"
  }, {
    "dt": 1512712800,
    "main": {
      "temp": 275.883,
      "temp_min": 275.883,
      "temp_max": 275.883,
      "pressure": 761.04,
      "sea_level": 1027.29,
      "grnd_level": 761.04,
      "humidity": 83,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.87,
      "deg": 199.002
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-08 06:00:00"
  }, {
    "dt": 1512723600,
    "main": {
      "temp": 274.217,
      "temp_min": 274.217,
      "temp_max": 274.217,
      "pressure": 760.17,
      "sea_level": 1027.31,
      "grnd_level": 760.17,
      "humidity": 83,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.82,
      "deg": 197
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-08 09:00:00"
  }, {
    "dt": 1512734400,
    "main": {
      "temp": 273.823,
      "temp_min": 273.823,
      "temp_max": 273.823,
      "pressure": 759.84,
      "sea_level": 1028.26,
      "grnd_level": 759.84,
      "humidity": 89,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.86,
      "deg": 191.004
    },
    "rain": {
      "3h": 0.02
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-08 12:00:00"
  }, {
    "dt": 1512745200,
    "main": {
      "temp": 282.332,
      "temp_min": 282.332,
      "temp_max": 282.332,
      "pressure": 760.71,
      "sea_level": 1029.16,
      "grnd_level": 760.71,
      "humidity": 86,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.22,
      "deg": 193.004
    },
    "rain": {
      "3h": 0.02
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-08 15:00:00"
  }, {
    "dt": 1512756000,
    "main": {
      "temp": 290.211,
      "temp_min": 290.211,
      "temp_max": 290.211,
      "pressure": 759.94,
      "sea_level": 1025.5,
      "grnd_level": 759.94,
      "humidity": 47,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.84,
      "deg": 198
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-08 18:00:00"
  }, {
    "dt": 1512766800,
    "main": {
      "temp": 290.473,
      "temp_min": 290.473,
      "temp_max": 290.473,
      "pressure": 758.28,
      "sea_level": 1022.47,
      "grnd_level": 758.28,
      "humidity": 41,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 2.38,
      "deg": 202.501
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-08 21:00:00"
  }, {
    "dt": 1512777600,
    "main": {
      "temp": 285.873,
      "temp_min": 285.873,
      "temp_max": 285.873,
      "pressure": 759.05,
      "sea_level": 1024.69,
      "grnd_level": 759.05,
      "humidity": 55,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.79,
      "deg": 202.509
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-09 00:00:00"
  }, {
    "dt": 1512788400,
    "main": {
      "temp": 278.749,
      "temp_min": 278.749,
      "temp_max": 278.749,
      "pressure": 760.62,
      "sea_level": 1028.57,
      "grnd_level": 760.62,
      "humidity": 85,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02n"
    }],
    "clouds": {
      "all": 8
    },
    "wind": {
      "speed": 1.32,
      "deg": 193.002
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-09 03:00:00"
  }, {
    "dt": 1512799200,
    "main": {
      "temp": 276.029,
      "temp_min": 276.029,
      "temp_max": 276.029,
      "pressure": 760.99,
      "sea_level": 1030.3,
      "grnd_level": 760.99,
      "humidity": 82,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02n"
    }],
    "clouds": {
      "all": 8
    },
    "wind": {
      "speed": 0.99,
      "deg": 197.501
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-09 06:00:00"
  }, {
    "dt": 1512810000,
    "main": {
      "temp": 273.727,
      "temp_min": 273.727,
      "temp_max": 273.727,
      "pressure": 760.62,
      "sea_level": 1030.77,
      "grnd_level": 760.62,
      "humidity": 82,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.86,
      "deg": 209.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-09 09:00:00"
  }, {
    "dt": 1512820800,
    "main": {
      "temp": 273.178,
      "temp_min": 273.178,
      "temp_max": 273.178,
      "pressure": 761.03,
      "sea_level": 1032.5,
      "grnd_level": 761.03,
      "humidity": 85,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10n"
    }],
    "clouds": {
      "all": 20
    },
    "wind": {
      "speed": 0.76,
      "deg": 257.502
    },
    "rain": {
      "3h": 0.015
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-09 12:00:00"
  }, {
    "dt": 1512831600,
    "main": {
      "temp": 278.661,
      "temp_min": 278.661,
      "temp_max": 278.661,
      "pressure": 763.45,
      "sea_level": 1034.75,
      "grnd_level": 763.45,
      "humidity": 82,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }],
    "clouds": {
      "all": 24
    },
    "wind": {
      "speed": 1.92,
      "deg": 359
    },
    "rain": {
      "3h": 0.08
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-09 15:00:00"
  }, {
    "dt": 1512842400,
    "main": {
      "temp": 284.912,
      "temp_min": 284.912,
      "temp_max": 284.912,
      "pressure": 763.85,
      "sea_level": 1031.38,
      "grnd_level": 763.85,
      "humidity": 59,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }],
    "clouds": {
      "all": 24
    },
    "wind": {
      "speed": 1.21,
      "deg": 3.00043
    },
    "rain": {
      "3h": 0.1
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-09 18:00:00"
  }, {
    "dt": 1512853200,
    "main": {
      "temp": 287.77,
      "temp_min": 287.77,
      "temp_max": 287.77,
      "pressure": 762.52,
      "sea_level": 1028.1,
      "grnd_level": 762.52,
      "humidity": 44,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }],
    "clouds": {
      "all": 48
    },
    "wind": {
      "speed": 1.2,
      "deg": 1.5011
    },
    "rain": {
      "3h": 0.015
    },
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-09 21:00:00"
  }, {
    "dt": 1512864000,
    "main": {
      "temp": 284.327,
      "temp_min": 284.327,
      "temp_max": 284.327,
      "pressure": 762.79,
      "sea_level": 1029.72,
      "grnd_level": 762.79,
      "humidity": 48,
      "temp_kf": 0
    },
    "weather": [{
      "id": 803,
      "main": "Clouds",
      "description": "broken clouds",
      "icon": "04n"
    }],
    "clouds": {
      "all": 56
    },
    "wind": {
      "speed": 0.71,
      "deg": 334.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-10 00:00:00"
  }, {
    "dt": 1512874800,
    "main": {
      "temp": 277.861,
      "temp_min": 277.861,
      "temp_max": 277.861,
      "pressure": 764.46,
      "sea_level": 1033.5,
      "grnd_level": 764.46,
      "humidity": 74,
      "temp_kf": 0
    },
    "weather": [{
      "id": 802,
      "main": "Clouds",
      "description": "scattered clouds",
      "icon": "03n"
    }],
    "clouds": {
      "all": 36
    },
    "wind": {
      "speed": 1.07,
      "deg": 353.501
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-10 03:00:00"
  }, {
    "dt": 1512885600,
    "main": {
      "temp": 274.729,
      "temp_min": 274.729,
      "temp_max": 274.729,
      "pressure": 764.78,
      "sea_level": 1035.66,
      "grnd_level": 764.78,
      "humidity": 84,
      "temp_kf": 0
    },
    "weather": [{
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.15,
      "deg": 7.50085
    },
    "rain": {
      "3h": 0.01
    },
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-10 06:00:00"
  }, {
    "dt": 1512896400,
    "main": {
      "temp": 272.021,
      "temp_min": 272.021,
      "temp_max": 272.021,
      "pressure": 764.35,
      "sea_level": 1036.56,
      "grnd_level": 764.35,
      "humidity": 87,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.14,
      "deg": 359.5
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-10 09:00:00"
  }, {
    "dt": 1512907200,
    "main": {
      "temp": 269.974,
      "temp_min": 269.974,
      "temp_max": 269.974,
      "pressure": 765.13,
      "sea_level": 1038.68,
      "grnd_level": 765.13,
      "humidity": 91,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.06,
      "deg": 357.5
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-10 12:00:00"
  }, {
    "dt": 1512918000,
    "main": {
      "temp": 274.3,
      "temp_min": 274.3,
      "temp_max": 274.3,
      "pressure": 766.45,
      "sea_level": 1040.19,
      "grnd_level": 766.45,
      "humidity": 72,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02d"
    }],
    "clouds": {
      "all": 8
    },
    "wind": {
      "speed": 1.31,
      "deg": 356
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-10 15:00:00"
  }, {
    "dt": 1512928800,
    "main": {
      "temp": 283.213,
      "temp_min": 283.213,
      "temp_max": 283.213,
      "pressure": 766.31,
      "sea_level": 1035.55,
      "grnd_level": 766.31,
      "humidity": 37,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.32,
      "deg": 359.001
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-10 18:00:00"
  }, {
    "dt": 1512939600,
    "main": {
      "temp": 286.15,
      "temp_min": 286.15,
      "temp_max": 286.15,
      "pressure": 764.65,
      "sea_level": 1031.43,
      "grnd_level": 764.65,
      "humidity": 32,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.18,
      "deg": 0.000457764
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-10 21:00:00"
  }, {
    "dt": 1512950400,
    "main": {
      "temp": 281.575,
      "temp_min": 281.575,
      "temp_max": 281.575,
      "pressure": 765.02,
      "sea_level": 1033.14,
      "grnd_level": 765.02,
      "humidity": 34,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.12,
      "deg": 347
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-11 00:00:00"
  }, {
    "dt": 1512961200,
    "main": {
      "temp": 273.151,
      "temp_min": 273.151,
      "temp_max": 273.151,
      "pressure": 766.48,
      "sea_level": 1037.42,
      "grnd_level": 766.48,
      "humidity": 46,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.96,
      "deg": 353.5
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-11 03:00:00"
  }, {
    "dt": 1512972000,
    "main": {
      "temp": 270.195,
      "temp_min": 270.195,
      "temp_max": 270.195,
      "pressure": 766.06,
      "sea_level": 1038.73,
      "grnd_level": 766.06,
      "humidity": 52,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.17,
      "deg": 356.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-11 06:00:00"
  }, {
    "dt": 1512982800,
    "main": {
      "temp": 268.356,
      "temp_min": 268.356,
      "temp_max": 268.356,
      "pressure": 765.05,
      "sea_level": 1038.9,
      "grnd_level": 765.05,
      "humidity": 66,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.05,
      "deg": 355.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-11 09:00:00"
  }, {
    "dt": 1512993600,
    "main": {
      "temp": 267.209,
      "temp_min": 267.209,
      "temp_max": 267.209,
      "pressure": 764.61,
      "sea_level": 1039.61,
      "grnd_level": 764.61,
      "humidity": 66,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.15,
      "deg": 354.003
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-11 12:00:00"
  }, {
    "dt": 1513004400,
    "main": {
      "temp": 276.151,
      "temp_min": 276.151,
      "temp_max": 276.151,
      "pressure": 765.81,
      "sea_level": 1040.01,
      "grnd_level": 765.81,
      "humidity": 37,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.43,
      "deg": 359.501
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-11 15:00:00"
  }, {
    "dt": 1513015200,
    "main": {
      "temp": 286.743,
      "temp_min": 286.743,
      "temp_max": 286.743,
      "pressure": 765.41,
      "sea_level": 1034.66,
      "grnd_level": 765.41,
      "humidity": 27,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.01,
      "deg": 1.50366
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-11 18:00:00"
  }, {
    "dt": 1513026000,
    "main": {
      "temp": 289.011,
      "temp_min": 289.011,
      "temp_max": 289.011,
      "pressure": 763.71,
      "sea_level": 1030.39,
      "grnd_level": 763.71,
      "humidity": 22,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.06,
      "deg": 355.501
    },
    "rain": {},
    "sys": {
      "pod": "d"
    },
    "dt_txt": "2017-12-11 21:00:00"
  }, {
    "dt": 1513036800,
    "main": {
      "temp": 282.558,
      "temp_min": 282.558,
      "temp_max": 282.558,
      "pressure": 764.15,
      "sea_level": 1032.17,
      "grnd_level": 764.15,
      "humidity": 30,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.87,
      "deg": 348.501
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-12 00:00:00"
  }, {
    "dt": 1513047600,
    "main": {
      "temp": 272.309,
      "temp_min": 272.309,
      "temp_max": 272.309,
      "pressure": 765.77,
      "sea_level": 1036.3,
      "grnd_level": 765.77,
      "humidity": 53,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.01,
      "deg": 348.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-12 03:00:00"
  }, {
    "dt": 1513058400,
    "main": {
      "temp": 268.631,
      "temp_min": 268.631,
      "temp_max": 268.631,
      "pressure": 765.93,
      "sea_level": 1037.68,
      "grnd_level": 765.93,
      "humidity": 65,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 1.06,
      "deg": 352
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-12 06:00:00"
  }, {
    "dt": 1513069200,
    "main": {
      "temp": 266.456,
      "temp_min": 266.456,
      "temp_max": 266.456,
      "pressure": 765.26,
      "sea_level": 1037.74,
      "grnd_level": 765.26,
      "humidity": 69,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.96,
      "deg": 355.001
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-12 09:00:00"
  }, {
    "dt": 1513080000,
    "main": {
      "temp": 265.114,
      "temp_min": 265.114,
      "temp_max": 265.114,
      "pressure": 764.99,
      "sea_level": 1038.29,
      "grnd_level": 764.99,
      "humidity": 73,
      "temp_kf": 0
    },
    "weather": [{
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }],
    "clouds": {
      "all": 0
    },
    "wind": {
      "speed": 0.98,
      "deg": 358.005
    },
    "rain": {},
    "sys": {
      "pod": "n"
    },
    "dt_txt": "2017-12-12 12:00:00"
  }],
  "city": {
    "id": 3526683,
    "name": "Mexico City",
    "coord": {
      "lat": 19.4326,
      "lon": -99.1334
    },
    "country": "MX"
  }
}

temp_at_15=[];
vals=Object.values(data);
vals.forEach(function(el) {
if(Array.isArray(el))
el.forEach(function(o) {
if(o.dt_txt.includes('15:00:00'))
 temp_at_15.push(o.main.temp);
});
});

console.log(temp_at_15);


来源: stackexchange

问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
There are two problems with your code:

(1) The scope of the variable assignInitial is limited within the if blocks, so you can't use it outside the if block

(2) Also, use else if as shown below instead of many if conditions (If you don't use else if, all the 38 other if conditions will be evaluated which is unnecessary)

```<code>public static String[] initial (String responsibleDepartment) {
    String[] assignInitial = null;
    if (responsibleDepartment.equals("Accounts Receivable")) {
        assignInitial = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
    } else if (responsibleDepartment.equals("Customer Service")) {
        assignInitial = new String[] {"Mary Wexler", "Turd Ferguson"};
    } // and 38 more if statements with the rest of the departments.
   return assignInitial;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
There are two problems with your code:

(1) The scope of the variable assignInitial is limited within the if blocks, so you can't use it outside the if block

(2) Also, use else if as shown below instead of many if conditions (If you don't use else if, all the 38 other if conditions will be evaluated which is unnecessary)

public static String[] initial (String responsibleDepartment) {
    String[] assignInitial = null;
    if (responsibleDepartment.equals("Accounts Receivable")) {
        assignInitial = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
    } else if (responsibleDepartment.equals("Customer Service")) {
        assignInitial = new String[] {"Mary Wexler", "Turd Ferguson"};
    } // and 38 more if statements with the rest of the departments.
   return assignInitial;
}


问:
How to create high performance SQL select query, if I need a condition for referrer table's records?
For example, I have 2 tables, which I need for my query, Property and Move for history of moving properties.

I must create a query which will return all properties + 1 additional boolean column, IsInService, which will have value true, in cases, when Move table has a record for property with DateTo = null and MoveTypeID = 1 ("In service").

I have created this query:

```<code>SELECT
    [ID], [Name],
    (SELECT COUNT(*)
     FROM [Move]
     WHERE PropertyID = p.ID
       AND DateTo IS NULL
       AND MoveTypeID = 1) AS IsInService
FROM
    [Property] as p
ORDER BY
    [Name] ASC
OFFSET 100500 ROWS FETCH NEXT 50 ROWS ONLY;
</code>```

I'm not so strong in SQL, but as I know, subqueries are the evil :)

How to create high performance SQL query in my case, if it is expected that these tables will include millions of records?

答:
I've updated the code based on your comment. If you need something else, please provide input and output data expected. This is about all I can do based on inference from the existing comments. Further, this isn't intended to give you an exact working solution. My intention was to give you a prototype from which you can build your solution.

That said:

The code below is the basic join that you need. However, keep in mind that indexing is probably going to play as big a part in performance as the structure of the table and the query. It doesn't matter how you query the tables if the indexes aren't there to support the queries once you reach a certain size. There are a lot of resources online for indexing but viewing querying plans should be at the top of your list.

As a note, your column [dbo].[Property] ([Name]) should probably be NVARCHAR to allow SQL to minimize data storage. Indexes on that column will then be smaller and searches/updates faster.

```<code>DECLARE @Property AS TABLE
  (
       [ID]     INT
       , [Name] NVARCHAR(100)
  );

INSERT INTO @Property
            ([ID]
             , [Name])
VALUES      (1,N'A'),
            (2,N'B'),
            (3,N'C');

DECLARE @Move AS TABLE
  (
       [ID]           INT
       , [DateTo]     DATE
       , [MoveTypeID] INT
       , [PropertyID] INT
  );

INSERT INTO @Move
            ([ID]
             , [DateTo]
             , [MoveTypeID]
             , [PropertyID])
VALUES      (1,NULL,1,1),
            (2,NULL,1,2),
            (3,N'2017-12-07',1,2);

SELECT [Property].[ID]     AS [property_id]
       , [Property].[Name] AS [property_name]
       , CASE
             WHEN [Move].[DateTo] IS NULL
                  AND [Move].[MoveTypeID] = 1 THEN
                 N'true'
             ELSE
                 N'false'
         END               AS [in_service]
FROM   @Property AS [Property]
       LEFT JOIN @Move AS [Move]
              ON [Move].[PropertyID] = [Property].[ID]
WHERE  [Move].[DateTo] IS NULL
       AND [Move].[MoveTypeID] = 1;
</code>```

Body:
For example, I have 2 tables, which I need for my query, Property and Move for history of moving properties.

I must create a query which will return all properties + 1 additional boolean column, IsInService, which will have value true, in cases, when Move table has a record for property with DateTo = null and MoveTypeID = 1 ("In service").

I have created this query:

SELECT
    [ID], [Name],
    (SELECT COUNT(*)
     FROM [Move]
     WHERE PropertyID = p.ID
       AND DateTo IS NULL
       AND MoveTypeID = 1) AS IsInService
FROM
    [Property] as p
ORDER BY
    [Name] ASC
OFFSET 100500 ROWS FETCH NEXT 50 ROWS ONLY;

I'm not so strong in SQL, but as I know, subqueries are the evil :)

How to create high performance SQL query in my case, if it is expected that these tables will include millions of records?

Body:
I've updated the code based on your comment. If you need something else, please provide input and output data expected. This is about all I can do based on inference from the existing comments. Further, this isn't intended to give you an exact working solution. My intention was to give you a prototype from which you can build your solution.

That said:

The code below is the basic join that you need. However, keep in mind that indexing is probably going to play as big a part in performance as the structure of the table and the query. It doesn't matter how you query the tables if the indexes aren't there to support the queries once you reach a certain size. There are a lot of resources online for indexing but viewing querying plans should be at the top of your list.

As a note, your column [dbo].[Property] ([Name]) should probably be NVARCHAR to allow SQL to minimize data storage. Indexes on that column will then be smaller and searches/updates faster.

DECLARE @Property AS TABLE
  (
       [ID]     INT
       , [Name] NVARCHAR(100)
  );

INSERT INTO @Property
            ([ID]
             , [Name])
VALUES      (1,N'A'),
            (2,N'B'),
            (3,N'C');

DECLARE @Move AS TABLE
  (
       [ID]           INT
       , [DateTo]     DATE
       , [MoveTypeID] INT
       , [PropertyID] INT
  );

INSERT INTO @Move
            ([ID]
             , [DateTo]
             , [MoveTypeID]
             , [PropertyID])
VALUES      (1,NULL,1,1),
            (2,NULL,1,2),
            (3,N'2017-12-07',1,2);

SELECT [Property].[ID]     AS [property_id]
       , [Property].[Name] AS [property_name]
       , CASE
             WHEN [Move].[DateTo] IS NULL
                  AND [Move].[MoveTypeID] = 1 THEN
                 N'true'
             ELSE
                 N'false'
         END               AS [in_service]
FROM   @Property AS [Property]
       LEFT JOIN @Move AS [Move]
              ON [Move].[PropertyID] = [Property].[ID]
WHERE  [Move].[DateTo] IS NULL
       AND [Move].[MoveTypeID] = 1;


问:
Temporarily disable an input field if second input field is filled
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

```<code>var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}
</code>```

HTML

```<code><input type="text" id="input1">
<input type="text" id="input2">
</code>```

答:
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )

So:

var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
    document.getElementById("input2").disabled = this.value != "";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input1">
<input type="text" id="input2"></code>```

...and then of course if you want it to be mutual, the same for input2.

Body:
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}

HTML

<input type="text" id="input1">
<input type="text" id="input2">

Body:
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )

So:

var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
    document.getElementById("input2").disabled = this.value != "";
});

<input type="text" id="input1">
<input type="text" id="input2">

...and then of course if you want it to be mutual, the same for input2.

ContentLicense: CC BY-SA 4.0


问:
bash find filenames with the same last four character
I'd like to write a script that will execute a command that finds every set of files that have the same last four characters.

So for example, given a directory with these files,

```<code>$ ls -1
GH010119.MP4
GH010120.MP4
GH010126.MP4
GH010127.MP4
GH020119.MP4
GH020126.MP4
GH020127.MP4
GH030119.MP4
GH030126.MP4
</code>```

I'd like my script to make out these groups:

```<code>GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010127.MP4
GH020127.MP4

GH010120.MP4
</code>```

My current solution is to make out each group manually using: find . -name "*0119*", so I'd also like to know if the script I'd have to come up with won't be overly complex in comparison....

答:
I'm assuming the filenames without extension are all 8 characters and contain no newlines:

```<code>printf "%s\n" * |
 sort -k1.5,1.8n |
 awk '{key = substr($0,5,4)} NR==1{prev=key} prev != key {print ""} {print; prev=key}'
</code>```

If the filename is not strictly 8 chars, then

```<code>for f in *; do
   root=${f%%.*}
   echo "${root: -4:4} $f"
done |
 sort -k1,1n |
 awk 'NR==1 {prev=$1} $1 != prev {print ""} {print $2; prev=$1}'
</code>```

Body:
I'd like to write a script that will execute a command that finds every set of files that have the same last four characters.

So for example, given a directory with these files,

$ ls -1
GH010119.MP4
GH010120.MP4
GH010126.MP4
GH010127.MP4
GH020119.MP4
GH020126.MP4
GH020127.MP4
GH030119.MP4
GH030126.MP4

I'd like my script to make out these groups:

GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010127.MP4
GH020127.MP4

GH010120.MP4

My current solution is to make out each group manually using: find . -name "*0119*", so I'd also like to know if the script I'd have to come up with won't be overly complex in comparison....

Body:
I'm assuming the filenames without extension are all 8 characters and contain no newlines:

printf "%s\n" * |
 sort -k1.5,1.8n |
 awk '{key = substr($0,5,4)} NR==1{prev=key} prev != key {print ""} {print; prev=key}'

If the filename is not strictly 8 chars, then

for f in *; do
   root=${f%%.*}
   echo "${root: -4:4} $f"
done |
 sort -k1,1n |
 awk 'NR==1 {prev=$1} $1 != prev {print ""} {print $2; prev=$1}'


问:
High Speed Capture Session Image Reader
I'm trying to use the camera2 api to get image data as often as possible and then process it using opencv. High Speed Capture Session should allow higher fps, but I'm couldn't find any resources to access the image data and honestly much information on High Speed Capture Session. Any help to point me in the right direction would be appreciated.</p>

答:
You can't access the data from a constrained high speed capture session; it only sends high-speed data to the video encoder; the preview output only receives 30fps.

This is because the high-speed mode on both devices uses too many resources to support other outputs.  Any device that does have enough resources can just expose a 240 / 120 fps option in regular aeTargetFpsRanges, and then you can use the API as usual.  But I'm not aware of any devices that can do this.

Title: High Speed Capture Session Image Reader


问:
R – How to calculate combinations of pairs?
From a number of items (n), how do I compute all possible combinations of pairs in R? I can calculate the number of possible combinations with (n-1)*(n-3)*(n-5)*…, but how to get the combinations themselves?

For example, I have

```<code>x <- c("A", "B", "C", "D")
</code>```

That would make 4-1=3 combinations of pairs, so I want to have something like

```<code>("AB","CD")
("AC","BD")
("AD","BC")
</code>```

Thanks a lot!

答:
First, let's get all pairs of pairs:

```<code>dat = t(combn(combn(x, 2, paste, collapse=""), 2))
</code>```

```<code>     [,1] [,2]
 [1,] "AB" "AC"
 [2,] "AB" "AD"
 [3,] "AB" "BC"
 [4,] "AB" "BD"
 [5,] "AB" "CD"
 [6,] "AC" "AD"
 [7,] "AC" "BC"
 [8,] "AC" "BD"
 [9,] "AC" "CD"
[10,] "AD" "BC"
[11,] "AD" "BD"
[12,] "AD" "CD"
[13,] "BC" "BD"
[14,] "BC" "CD"
[15,] "BD" "CD"
</code>```

We now have all pairs of pairs. But it looks like you want only pairs of pairs where each letter appears only once. The code below identifies rows that meet this condition (though it seems like the code is more complicated than it needs to be).

```<code>dat[sapply(strsplit(apply(dat, 1, paste, collapse=""), ""), function(i) length(unique(i)) == 4), ]
</code>```

```<code>     [,1] [,2]
[1,] "AB" "CD"
[2,] "AC" "BD"
[3,] "AD" "BC"
</code>```

Body:
From a number of items (n), how do I compute all possible combinations of pairs in R? I can calculate the number of possible combinations with (n-1)*(n-3)*(n-5)*…, but how to get the combinations themselves?

For example, I have

x <- c("A", "B", "C", "D")

That would make 4-1=3 combinations of pairs, so I want to have something like

("AB","CD")
("AC","BD")
("AD","BC")

Thanks a lot!

Body:
First, let's get all pairs of pairs:

dat = t(combn(combn(x, 2, paste, collapse=""), 2))

     [,1] [,2]
 [1,] "AB" "AC"
 [2,] "AB" "AD"
 [3,] "AB" "BC"
 [4,] "AB" "BD"
 [5,] "AB" "CD"
 [6,] "AC" "AD"
 [7,] "AC" "BC"
 [8,] "AC" "BD"
 [9,] "AC" "CD"
[10,] "AD" "BC"
[11,] "AD" "BD"
[12,] "AD" "CD"
[13,] "BC" "BD"
[14,] "BC" "CD"
[15,] "BD" "CD"

We now have all pairs of pairs. But it looks like you want only pairs of pairs where each letter appears only once. The code below identifies rows that meet this condition (though it seems like the code is more complicated than it needs to be).

dat[sapply(strsplit(apply(dat, 1, paste, collapse=""), ""), function(i) length(unique(i)) == 4), ]

     [,1] [,2]
[1,] "AB" "CD"
[2,] "AC" "BD"
[3,] "AD" "BC"


问:
Retrieve the session value and pass as required parameter of api Ajax
I want to retrieve the session value and pass that value as required parameter for the api. My session is $_SESSION['name']. And these are my codes

```<code>var uniqueName = **Here I want to retrieve session value**;
  if(**Then I want to check if uniqueName is null or undefined**) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

  return false;
});
</code>```

答:
```<code>var uniqueName = "<?php echo $_SESSION['name'] ?>";
  if(uniqueName) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

  return false;
});
</code>```

References:

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

http://www.dyn-web.com/tutorials/php-js/scalar.php

Body:
I want to retrieve the session value and pass that value as required parameter for the api. My session is $_SESSION['name']. And these are my codes

var uniqueName = **Here I want to retrieve session value**;
  if(**Then I want to check if uniqueName is null or undefined**) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

  return false;
});

Body:
var uniqueName = "<?php echo $_SESSION['name'] ?>";
  if(uniqueName) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

  return false;
});

References:

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

http://www.dyn-web.com/tutorials/php-js/scalar.php


问:
Java web service deployed in Glassfish accessible over http and https
I'm trying to create a Web Service using JAX-WS and Glassfish 2.1 that is listening to 2 enpoints, one over http and the other over https. First I have created the web service with the default settings (this means over http) and it worked fine. After that I have modified it to accept connections over https and this is working also but the initial case stopped working. Can anybody please tell me how to solve this issue? I know it is possible, but I couldn't find the way to do it.

Thanks.

答:
The only way I've been able to do this is via Apache's proxy pass.  I found this relatively easy to set up too.

Using CentOS, I yum installed apache (which comes with mod_proxy) and mod_ssl.

In the http.conf file, I had the following configuration:

```<code>Listen 8080
ProxyRequests On
SSLProxyEngine on

AllowCONNECT 8181

<Proxy *>
    Order deny,allow
    Allow from all
    Deny from all
</Proxy>
ProxyPass / https://radish:8181/
ProxyPassReverse / https://radish:8181/
</code>```

Using this configuration you obviously have to disable the 8080 listener in glassfish.

In the end, I used ProxyPass to forward both ports 80 and 443 from Apache to glassfish port 8181.

ContentLicense: CC BY-SA 2.5

Body:
The only way I've been able to do this is via Apache's proxy pass.  I found this relatively easy to set up too.

Using CentOS, I yum installed apache (which comes with mod_proxy) and mod_ssl.

In the http.conf file, I had the following configuration:

Listen 8080
ProxyRequests On
SSLProxyEngine on

AllowCONNECT 8181

<Proxy *>
    Order deny,allow
    Allow from all
    Deny from all
</Proxy>
ProxyPass / https://radish:8181/
ProxyPassReverse / https://radish:8181/

Using this configuration you obviously have to disable the 8080 listener in glassfish.

In the end, I used ProxyPass to forward both ports 80 and 443 from Apache to glassfish port 8181.


问:
accessing list in python 3
I'm storing key and value in a dictionary called campaign_name, then access the value using randvalue. That works fine. But when I try to access certain element in the randvalue, let's say randvalue[0] or randvalue[1] it would throw an error.

I can print(randvalue) perfectly and the value would show like this [[16949.070963, 2694507, 76606]]. But I can't print just 16949.070963. My complete section of code is as follows: Thanks for the help.

```<code>  def startchecking():
        storepast()
        # loading file into opepyxl
        ref_workbook = openpyxl.load_workbook(path)
        # Grab all the sheet name in the workbook
        workbook_tab = ref_workbook.get_sheet_names()
        for i in workbook_tab:
            ws = ref_workbook[i]
            randvalue=campaign_name.get(str(ws['B4'].value))
            print(randvalue)
            temptext = "Starting Check" + str(ws)
            textoutput(temptext)
        checkdaily(45, 52)
</code>```

答: Seems like your randvalue is a list of list, try using randvalue[0][0] to get 16949.070963.

Title: accessing list in python 3

Body:
I'm storing key and value in a dictionary called campaign_name, then access the value using randvalue. That works fine. But when I try to access certain element in the randvalue, let's say randvalue[0] or randvalue[1] it would throw an error.

I can print(randvalue) perfectly and the value would show like this [[16949.070963, 2694507, 76606]]. But I can't print just 16949.070963. My complete section of code is as follows: Thanks for the help.

  def startchecking():
        storepast()
        # loading file into opepyxl
        ref_workbook = openpyxl.load_workbook(path)
        # Grab all the sheet name in the workbook
        workbook_tab = ref_workbook.get_sheet_names()
        for i in workbook_tab:
            ws = ref_workbook[i]
            randvalue=campaign_name.get(str(ws['B4'].value))
            print(randvalue)
            temptext = "Starting Check" + str(ws)
            textoutput(temptext)
        checkdaily(45, 52)


问:
How to store RGB colour in variable?
I'm looking to store an RGB colour in a variable in an Excel VBA project, to set the background color of various cell/ranges throughout a sub.

I want to set the colour once in a variable, so if I decide to change it throughout I only need to do it in one place.

```<code>Dim clrBlue As ColorFormat
clrBlue = RGB(0, 0, 256)

Range("a2").Interior.Color = clrBlue
Range("b3").Interior.Color = clrBlue
</code>```

With the above code, I'm getting runtime error:

Object variable or With block variable not set

I could write separate functions  (SetBlue, SetRed, SetGreen) to apply each colour, but that feels messy.

Can anyone suggest what I'm doing wrong?

答:
I haven't tried this and I'm not disputing any of the previous commenters.

I do notice that the original code sample has: clrBlue = RGB(0, 0, 256)

The highest number allowed in RGB is 255.  That might be the problem.

Title: How to store RGB colour in variable?

Body:
I'm looking to store an RGB colour in a variable in an Excel VBA project, to set the background color of various cell/ranges throughout a sub.

I want to set the colour once in a variable, so if I decide to change it throughout I only need to do it in one place.

Dim clrBlue As ColorFormat
clrBlue = RGB(0, 0, 256)

Range("a2").Interior.Color = clrBlue
Range("b3").Interior.Color = clrBlue

With the above code, I'm getting runtime error:

Object variable or With block variable not set

I could write separate functions  (SetBlue, SetRed, SetGreen) to apply each colour, but that feels messy.

Can anyone suggest what I'm doing wrong?


问:
CSS Reset, default styles for common elements
After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.

Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.

I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).

答: I'm personally a big fan of BlueprintCSS. It resets styles across browsers and provides some really convenient defaults (that are what you want 90% of the time). It also provides a layout grid, but you don't have to use that if you don't need it.</p>

OwnerDisplayName: public static

LastEditorDisplayName: Sam Hasler

OwnerDisplayName: zenazn


问:
rails - REGEX for email validation
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

```<code>def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end
</code>```

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

答:
```<code>/\b[A-Z0-9._%a-z\-]+@(?:[A-Z0-9a-z\-]+\.)+[A-Za-z]{2,4}\z/
</code>```

This is what I use to validate email.

Source: http://www.regular-expressions.info/email.html

Title: rails - REGEX for email validation

Body:
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

Body:
/\b[A-Z0-9._%a-z\-]+@(?:[A-Z0-9a-z\-]+\.)+[A-Za-z]{2,4}\z/

This is what I use to validate email.

Source: http://www.regular-expressions.info/email.html


问:
Swift 3 GCD lock variable and block_and_release error
I am using Swift 3 GCD in order to perform some operations in my code. But I'm getting _dispatch_call_block_and_release error often. I suppose the reason behind this error is because different threads modify same variable, but I'm not sure how to fix problem. Here is my code and explanations:

I have one variable which is accessed and modified in different threads:

```<code>var queueMsgSent: Dictionary<Date,BTCommand>? = nil

func lock(obj: AnyObject, blk:() -> ()) {
    objc_sync_enter(obj)
    blk()
    objc_sync_exit(obj)
}

func addMsgSentToQueue(msg: BTCommands) {

    if queueMsgSent == nil {
        queueMsgSent = Dictionary.init()
    }
    let currentDate = Date()
    lock(obj: queueMsgSent as AnyObject) {
        queueMsgSent?.updateValue(msg, forKey: currentDate)
    }
}

func deleteMsgSentWithId(id: Int) {

    if queueMsgSent == nil { return }

    for (date, msg) in queueMsgSent! {

        if msg.isAck() == false && msg.getId()! == id {
            lock(obj: queueMsgSent as AnyObject) {
                queueMsgSent?.removeValue(forKey: date)
            }
        }
   }
}

func runSent() -> Void {

    while(true) {
        if queueMsgSent == nil { continue }

        for (date, msg) in queueMsgSent! {

            if msg.isSent() == false {
                 mainSearchView?.btCom?.write(str: msg.getCommand()!)
                 msg.setSent(val: true)
                lastMsgSent = Date()
                continue
            }

            if msg.isAck() == true {
                lock(obj: queueMsgSent as AnyObject) {
                    queueMsgSent?.removeValue(forKey: date)
                }
                continue
            }

        }
   }

}
</code>```

I start runSent method as:

```<code>  DispatchQueue.global().async(execute: runSent)
</code>```

I need that runSent continuously check some conditions withinn queueMsgSent, and other functions addMsgSentToQueueue and deleteMsgSentWithId are called in main thread id necessary. I am using some locking mechanism but its not working properly

答:
I strongly suggest you to use the DispatchQueue(s) provided by Grand Central Dispatch, they makes multithreading management much easier.

Command

Let's start with your command class

```<code>class Command {
    let id: String
    var isAck = false
    var isSent = false

    init(id:String) {
        self.id = id
    }
}
</code>```

Queue

Now we can build our Queue class, it will provide the following functionalities

This is our class should not be confused with the concept of DispatchQueue!

push a Command into the queue

delete a Command from the queue

start the processing of all the elements into the queue

And now the code:

```<code>class Queue {
    typealias Element = (date:Date, command:Command)
    private var storage: [Element] = []
    private let serialQueue = DispatchQueue(label: "serialQueue")

    func push(command:Command) {
        serialQueue.async {
            let newElement = (Date(), command)
            self.storage.append(newElement)
        }
    }

    func delete(by id: String) {
        serialQueue.async {
            guard let index = self.storage.index(where: { $0.command.id == id }) else { return }
            self.storage.remove(at: index)
        }
    }

    func startProcessing() {
        Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
            self.processElements()
        }
    }

    private func processElements() {
        serialQueue.async {
            // send messages where isSent == false
            let shouldBeSent = self.storage.filter { !$0.command.isSent }
            for elm in shouldBeSent {
                // TODO: add here code to send message
                elm.command.isSent = true
            }

            // remove from storage message where isAck == true
            self.storage = self.storage.filter { !$0.command.isAck }
        }
    }
}
</code>```

How does it work?

As you can see the storage property is an array holding a list of tuples, each tuple has 2 components: Date and Command.

Since the storage array is accesses by multiple threads we need to make sure it is accessed in a thread safe way.

So each time we access storage we wrap our code into this

```<code>serialQueue.async {
    // access self.storage safely
}
</code>```

Each code we write into the closure  shown above is added to our Serial Dispatch Queue.

The Serial Queue does process 1 closure at the time. That's why our storage property is accessed in a thread safe way!

Final consideration

The following block of code is evil

```<code>while true {
    ...
}
</code>```

It does use all the available CPU time, it does freeze the UI (when executed on the main thread) and discharge the battery.

As you can see I replaced it with

```<code>Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
    self.processElements()
}
</code>```

which calls self.processElements() every 10 seconds leaving plenty of time to the CPU to process other threads.

Of course it's up to you changing the number of seconds to better fit your scenario.

Body:
I am using Swift 3 GCD in order to perform some operations in my code. But I'm getting _dispatch_call_block_and_release error often. I suppose the reason behind this error is because different threads modify same variable, but I'm not sure how to fix problem. Here is my code and explanations:

I have one variable which is accessed and modified in different threads:

var queueMsgSent: Dictionary<Date,BTCommand>? = nil

func lock(obj: AnyObject, blk:() -> ()) {
    objc_sync_enter(obj)
    blk()
    objc_sync_exit(obj)
}

func addMsgSentToQueue(msg: BTCommands) {

    if queueMsgSent == nil {
        queueMsgSent = Dictionary.init()
    }
    let currentDate = Date()
    lock(obj: queueMsgSent as AnyObject) {
        queueMsgSent?.updateValue(msg, forKey: currentDate)
    }
}

func deleteMsgSentWithId(id: Int) {

    if queueMsgSent == nil { return }

    for (date, msg) in queueMsgSent! {

        if msg.isAck() == false && msg.getId()! == id {
            lock(obj: queueMsgSent as AnyObject) {
                queueMsgSent?.removeValue(forKey: date)
            }
        }
   }
}

func runSent() -> Void {

    while(true) {
        if queueMsgSent == nil { continue }

        for (date, msg) in queueMsgSent! {

            if msg.isSent() == false {
                 mainSearchView?.btCom?.write(str: msg.getCommand()!)
                 msg.setSent(val: true)
                lastMsgSent = Date()
                continue
            }

            if msg.isAck() == true {
                lock(obj: queueMsgSent as AnyObject) {
                    queueMsgSent?.removeValue(forKey: date)
                }
                continue
            }

        }
   }

}

I start runSent method as:

  DispatchQueue.global().async(execute: runSent)

I need that runSent continuously check some conditions withinn queueMsgSent, and other functions addMsgSentToQueueue and deleteMsgSentWithId are called in main thread id necessary. I am using some locking mechanism but its not working properly

Body:
I strongly suggest you to use the DispatchQueue(s) provided by Grand Central Dispatch, they makes multithreading management much easier.

Command

Let's start with your command class

class Command {
    let id: String
    var isAck = false
    var isSent = false

    init(id:String) {
        self.id = id
    }
}

Queue

Now we can build our Queue class, it will provide the following functionalities

This is our class should not be confused with the concept of DispatchQueue!

push a Command into the queue

delete a Command from the queue

start the processing of all the elements into the queue

And now the code:

class Queue {
    typealias Element = (date:Date, command:Command)
    private var storage: [Element] = []
    private let serialQueue = DispatchQueue(label: "serialQueue")

    func push(command:Command) {
        serialQueue.async {
            let newElement = (Date(), command)
            self.storage.append(newElement)
        }
    }

    func delete(by id: String) {
        serialQueue.async {
            guard let index = self.storage.index(where: { $0.command.id == id }) else { return }
            self.storage.remove(at: index)
        }
    }

    func startProcessing() {
        Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
            self.processElements()
        }
    }

    private func processElements() {
        serialQueue.async {
            // send messages where isSent == false
            let shouldBeSent = self.storage.filter { !$0.command.isSent }
            for elm in shouldBeSent {
                // TODO: add here code to send message
                elm.command.isSent = true
            }

            // remove from storage message where isAck == true
            self.storage = self.storage.filter { !$0.command.isAck }
        }
    }
}

How does it work?

As you can see the storage property is an array holding a list of tuples, each tuple has 2 components: Date and Command.

Since the storage array is accesses by multiple threads we need to make sure it is accessed in a thread safe way.

So each time we access storage we wrap our code into this

serialQueue.async {
    // access self.storage safely
}

Each code we write into the closure  shown above is added to our Serial Dispatch Queue.

The Serial Queue does process 1 closure at the time. That's why our storage property is accessed in a thread safe way!

Final consideration

The following block of code is evil

while true {
    ...
}

It does use all the available CPU time, it does freeze the UI (when executed on the main thread) and discharge the battery.

As you can see I replaced it with

Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
    self.processElements()
}

which calls self.processElements() every 10 seconds leaving plenty of time to the CPU to process other threads.

Of course it's up to you changing the number of seconds to better fit your scenario.


问:
Assembly: ecx not decreasing
I am using MASM and currently implementing a loop displaying Capital alphabets, small alphabets and ASCII in between

```<code>.386

.model flat, stdcall
option casemap :none

include c:\masm32\include\windows.inc
include c:\masm32\include\kernel32.inc
include c:\masm32\include\masm32.inc
includelib c:\masm32\lib\kernel32.lib
includelib c:\masm32\lib\masm32.lib

.data
    _ret sdword 13
    _car sdword 10
    _num sdword 0

.code
main:
    mov edx, 'A'
    mov ecx, 58
    jmp _end

_loop:
    push edx
    invoke StdOut, esp
    invoke StdOut, addr _ret
    invoke StdOut, addr _car
    pop edx

    inc edx
    dec ecx

_end:
    cmp ecx, 0
    jne _loop

_exit:
    invoke ExitProcess, 0
end main
</code>```

The problem here I am facing is that ECX is not decreasing during the body of the loop and the loop continue forever even after A-Z %somehere% a-z

答:
Your issue is one of calling convention. You've set the default convention to .model flat, stdcall which is not an issue. This means that unless otherwise specified stdcall calling convention will be used by the invoke directive. The stdcall calling convention includes these rules:

The volatile registers are: EAX, ECX, EDX, and ST0 - ST7

The non-volatile registers are: EBX, EBP, ESP, EDI, ESI, CS, DS, ES, FS and GS

This means that you can't assume that the values in EAX, ECX, and EDX will remain the same after a call/invoke. Your loop variable is ECX so it is likely the calls to StdOut clobbered ECX each time they were called leading to the infinite loop.

The best choice is to use one of the non-volatile registers  EBX, EDI, ESI (you cause other issues if you use EBP and ESP). If you run out of registers you can:

Save and restore the value of ECX before and after the calls to StdOut the same way that EDX was preserved in your code using PUSH/POP.

Store them in a global or stack based memory location and restore them after.

Write the code to avoid using an extra register for the loop.

Title: Assembly: ecx not decreasing

Body:
I am using MASM and currently implementing a loop displaying Capital alphabets, small alphabets and ASCII in between

.386

.model flat, stdcall
option casemap :none

include c:\masm32\include\windows.inc
include c:\masm32\include\kernel32.inc
include c:\masm32\include\masm32.inc
includelib c:\masm32\lib\kernel32.lib
includelib c:\masm32\lib\masm32.lib

.data
    _ret sdword 13
    _car sdword 10
    _num sdword 0

.code
main:
    mov edx, 'A'
    mov ecx, 58
    jmp _end

_loop:
    push edx
    invoke StdOut, esp
    invoke StdOut, addr _ret
    invoke StdOut, addr _car
    pop edx

    inc edx
    dec ecx

_end:
    cmp ecx, 0
    jne _loop

_exit:
    invoke ExitProcess, 0
end main

The problem here I am facing is that ECX is not decreasing during the body of the loop and the loop continue forever even after A-Z %somehere% a-z


问:
Positioning of annotations in subplots
I have to generate a plot of different sensor data. These should be printed in subplot each.  After generating the plot it should be annotated with some rectangles to highlight different features. Afterwards, these rectangles should be annotated with a text, describing the belonging class with a short word.

Surprisingly the same code is working in another script, where I don't use subplots, but only a single specgram.
I already replace the annotation(h,...) with annotation(gcf, ...), which should be the same. Adding tempplot instead of h, which makes sense to me,

```<code>Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'}
sampledExperiment = [10, 10, 0;
                 30,10, 1;
                 50,10, 0;
                 70,10, 1;
                 ]

experimentnaming = {0, 'classA';
                1, 'classB'
                }

samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
  tempplot = subplot(length(Sensorinput(1,:)),1,index);
  plot(Sensorinput(:,index));
  title(Naminginput(index));
  pos = get (tempplot, 'position')
  step = pos(3)/length(Sensorinput(:,index));

  for index=1:1:length(sampledExperiment)

    annotation(h, "rectangle",[pos(1)+step*sampledExperiment(index,1),pos(2),step*sampledExperiment(index,2),pos(4)]);
    y  = ylim;
    for namingindex=1:1:length(experimentnaming(:,1))
      if experimentnaming{namingindex,1}==sampledExperiment(index,3)
          text(sampledExperiment(index,1)/samplerate,y(2),experimentnaming(namingindex,2),'rotation',90);
      end
    end

  end

end
</code>```

I expect the boxes having the same height than the underlying subplot. Also, I am expecting the text (which is obviously printed as a stack) as an annotation to the box.
But this is the result I currently get: wrong result. Also, the boxes do not zoom correctly, when I resize the window. wrong_small_window.
This is mainly, what is working: working with single figure. Draw rectangles with the full height of the subplot and add text. This is created with the same code, but without subplots.

Hopefully you can help?

答:
Thanks for clarifying with a working example. Here's another simpler / more visually pleasing way to do it using the area function.

Sensor = struct ('input', num2cell (rand (6, 100), 2), ...
                 'name',  {'a'; 'b'; 'c'; 'd'; 'e'; 'f'});
Experiment = struct ('samplestart', { 10     ,  30     ,  50     ,  70}, ...
                     'samplewidth', { 10     ,  10     ,  10     ,  10}, ...
                     'classindex',  { 0      ,  1      ,  0      ,  1 });

ClassNames     = {'classA', 'classB'};
ClassColours   = {[1.0, 0.8, 0.8], [0.8, 0.8, 1.0]};

NumPlots = length (Sensor);
for n = 1 : NumPlots
  subplot(NumPlots, 1, n); hold on;
  for m = Experiment
    Hndl = area ([m.samplestart, m.samplestart + m.samplewidth], [1, 1]);
    set (Hndl, 'facecolor', ClassColours{m.classindex + 1});
    Hndl = text (m.samplestart+2, 1.2, ClassNames{m.classindex+1});
  end
  plot ([1:100], Sensor(n).input, 'k', 'linewidth', 2);
  text (-7.5, -0.25, Sensor(n).name, 'fontsize', 16, 'fontweight', 'bold');
end
```

Title: Positioning of annotations in subplots

Body:
I have to generate a plot of different sensor data. These should be printed in subplot each.  After generating the plot it should be annotated with some rectangles to highlight different features. Afterwards, these rectangles should be annotated with a text, describing the belonging class with a short word.

Surprisingly the same code is working in another script, where I don't use subplots, but only a single specgram.
I already replace the annotation(h,...) with annotation(gcf, ...), which should be the same. Adding tempplot instead of h, which makes sense to me,

Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'}
sampledExperiment = [10, 10, 0;
                 30,10, 1;
                 50,10, 0;
                 70,10, 1;
                 ]

experimentnaming = {0, 'classA';
                1, 'classB'
                }

samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
  tempplot = subplot(length(Sensorinput(1,:)),1,index);
  plot(Sensorinput(:,index));
  title(Naminginput(index));
  pos = get (tempplot, 'position')
  step = pos(3)/length(Sensorinput(:,index));

  for index=1:1:length(sampledExperiment)

    annotation(h, "rectangle",[pos(1)+step*sampledExperiment(index,1),pos(2),step*sampledExperiment(index,2),pos(4)]);
    y  = ylim;
    for namingindex=1:1:length(experimentnaming(:,1))
      if experimentnaming{namingindex,1}==sampledExperiment(index,3)
          text(sampledExperiment(index,1)/samplerate,y(2),experimentnaming(namingindex,2),'rotation',90);
      end
    end

  end

end

I expect the boxes having the same height than the underlying subplot. Also, I am expecting the text (which is obviously printed as a stack) as an annotation to the box.
But this is the result I currently get: wrong result. Also, the boxes do not zoom correctly, when I resize the window. wrong_small_window.
This is mainly, what is working: working with single figure. Draw rectangles with the full height of the subplot and add text. This is created with the same code, but without subplots.

Hopefully you can help?


问:
Google Cloud Folders with Permission Denied
I'm having this permissions issue on a setup I did on Google Cloud using Easy Engine.

The error is this: rm /etc/nginx/sites-available/mysite.com: permission denied

I do not know why this happens, I have other sites on Vultr and Digital Ocean and I have not had this problem.

If anyone can help me, I appreciate it.

Thank you.

答:
You should active su to have root access permissions.

try:

```<code>sudo su -
rm /etc/nginx/sites-available/mysite.com
</code>```

Body:
You should active su to have root access permissions.

try:

sudo su -
rm /etc/nginx/sites-available/mysite.com


问:
Pandas: create new column using condition df[variable].isnull on a list of variables
I want to create a mask column where 1 indicates there is data in a set of other columns and 0 when there is a blank in the same set

```<code> A  B   C   D   E   mask1
 0  13  2   45  96  1
 1  14  2   45  96  1
 2  15  9   1.  NaN 1
 3  16  9   1.0 NaN 1
 4  17  5   0.0 NaN 1
 5  18  6   1.0 967 1
 6  19  6   1.0 976 1
 7  20  9   1.0 294 1
 8  21  5   0.0 372 1
 9  13  5   NaN 170 0
10  62  5   NaN 100 0
11  22  20  NaN 170 0
12  13  NaN 0.0 996 0
</code>```

I managed to do it using the following code:

```<code>df2["mask1"] = np.where((df2['C'].isnull() | df2['D'].isnull()) , 0, 1)
</code>```

Now I want to automate this for a larger dataframe with more variables, i.e, I want to specify the variables I want to use for this mask. I was thinking to create a list of variables such as

```<code>var = [C, D, E]
</code>```

which I could use to perform this operation, but am not sure how to apply the same code I came up with using this list. for loop?

Body:
I want to create a mask column where 1 indicates there is data in a set of other columns and 0 when there is a blank in the same set

 A  B   C   D   E   mask1
 0  13  2   45  96  1
 1  14  2   45  96  1
 2  15  9   1.  NaN 1
 3  16  9   1.0 NaN 1
 4  17  5   0.0 NaN 1
 5  18  6   1.0 967 1
 6  19  6   1.0 976 1
 7  20  9   1.0 294 1
 8  21  5   0.0 372 1
 9  13  5   NaN 170 0
10  62  5   NaN 100 0
11  22  20  NaN 170 0
12  13  NaN 0.0 996 0

I managed to do it using the following code:

df2["mask1"] = np.where((df2['C'].isnull() | df2['D'].isnull()) , 0, 1)

Now I want to automate this for a larger dataframe with more variables, i.e, I want to specify the variables I want to use for this mask. I was thinking to create a list of variables such as

var = [C, D, E]

which I could use to perform this operation, but am not sure how to apply the same code I came up with using this list. for loop?

Body:
Select columns and apply isnull or notnull

cols = ['C', 'D', 'E']
df['mask1'] = df[cols].notnull().all(1).astype(int)

    A   B   C       D       E   mask1
0   0   13  2.0     45.0    96.0    1
1   1   14  2.0     45.0    96.0    1
2   2   15  9.0     1.0     NaN     0
3   3   16  9.0     1.0     NaN     0
4   4   17  5.0     0.0     NaN     0
5   5   18  6.0     1.0     967.0   1
6   6   19  6.0     1.0     976.0   1
7   7   20  9.0     1.0     294.0   1
8   8   21  5.0     0.0     372.0   1
9   9   13  5.0     NaN     170.0   0
10  10  62  5.0     NaN     100.0   0
11  11  22  20.0    NaN     170.0   0
12  12  13  NaN     0.0     996.0   0


问:
Thumbnail Image alt Attributes on Google Custom Search Engine Results Page
Running through some accessibility testing and seeing that GCSE results are displaying thumbnail images with no alt attribute. It looks like I'll have to use javascript to add this attribute, but I feel dirty in the way I've gone about doing this.

I know about firing a callback function via:

```<code>window.__gcse = {
  callback: myCallback
};
</code>```

And I am able to fire a function, but I seem to have to use a setTimeout() function to ensure the images are there. I've tried using both a jQuery load() as well as on.('load', fn...) but neither seem to do the job of adding the attribute. However, using a setTimeout to give the search results some time to generate does work, but I'm afraid of this being a dirty hack.

```<code>// add some alt tags after google custom search has loaded results
function myCallback() {
  setTimeout(function() {jQuery('.gs-image').attr('alt','Article Thumbnail');}, 500); // empty string better than generic text
  setTimeout(function() {jQuery("img.gsc-branding-img").attr('alt','Google');}, 500);
  setTimeout(function() {jQuery(".gsc-search-button-v2").attr('alt','Search');}, 500);
}
</code>```

Any ideas?

答:
I have been able to add alt text for accessibility for the magnifying glass search button, but so far I have not been able to add it for the Google branding image. I got this idea from https://productforums.google.com/forum/?hl=en#!topic/customsearch/Owey1Sj6oB8;context-place=forum/customsearch

(Be sure to replace 000000000000000000000:aaaaaaaaa with your own Google Custom Search Engine ID.)

```<code><script>var myCallback = function() {
document.getElementsByClassName('gsc-search-button gsc-search-button-v2')[0].alt = "Search Icon"; };
window.__gcse = {   callback: myCallback };
  (function() {
    var cx = '000000000000000000000:aaaaaaaaa';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:search linktarget="_parent"></gcse:search>
</code>```

Body:
Running through some accessibility testing and seeing that GCSE results are displaying thumbnail images with no alt attribute. It looks like I'll have to use javascript to add this attribute, but I feel dirty in the way I've gone about doing this.

I know about firing a callback function via:

window.__gcse = {
  callback: myCallback
};

And I am able to fire a function, but I seem to have to use a setTimeout() function to ensure the images are there. I've tried using both a jQuery load() as well as on.('load', fn...) but neither seem to do the job of adding the attribute. However, using a setTimeout to give the search results some time to generate does work, but I'm afraid of this being a dirty hack.

// add some alt tags after google custom search has loaded results
function myCallback() {
  setTimeout(function() {jQuery('.gs-image').attr('alt','Article Thumbnail');}, 500); // empty string better than generic text
  setTimeout(function() {jQuery("img.gsc-branding-img").attr('alt','Google');}, 500);
  setTimeout(function() {jQuery(".gsc-search-button-v2").attr('alt','Search');}, 500);
}

Any ideas?

Body:
I have been able to add alt text for accessibility for the magnifying glass search button, but so far I have not been able to add it for the Google branding image. I got this idea from https://productforums.google.com/forum/?hl=en#!topic/customsearch/Owey1Sj6oB8;context-place=forum/customsearch

(Be sure to replace 000000000000000000000:aaaaaaaaa with your own Google Custom Search Engine ID.)

<script>var myCallback = function() {
document.getElementsByClassName('gsc-search-button gsc-search-button-v2')[0].alt = "Search Icon"; };
window.__gcse = {   callback: myCallback };
  (function() {
    var cx = '000000000000000000000:aaaaaaaaa';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:search linktarget="_parent"></gcse:search>


答:
You can achieve this using focus and blur. Below it is done with JQuery.

$(function() {
    $('#input1').focus(function(){
      $('#input2').prop('disabled', 'disabled');
    }).blur(function(){
     $('#input2').prop('disabled', '');
    });

    $('#input2').focus(function(){
      $('#input1').prop('disabled', 'disabled');
    }).blur(function(){
     $('#input1').prop('disabled', '');
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2"></code>```

Title: Temporarily disable an input field if second input field is filled

Body:
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}

HTML

<input type="text" id="input1">
<input type="text" id="input2">

Body:
You can achieve this using focus and blur. Below it is done with JQuery.

$(function() {
    $('#input1').focus(function(){
      $('#input2').prop('disabled', 'disabled');
    }).blur(function(){
     $('#input2').prop('disabled', '');
    });

    $('#input2').focus(function(){
      $('#input1').prop('disabled', 'disabled');
    }).blur(function(){
     $('#input1').prop('disabled', '');
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">


问:
NSButton state not changing
The following code works perfect in my sandbox:

```<code>@IBAction func filterClicked(sender: NSButton) {
  println(sender.state)
  if let clickEvent = NSApp.currentEvent! {
    if Int(clickEvent.modifierFlags.rawValue) & Int(NSEventModifierFlags.ControlKeyMask.rawValue) != 0 {
      if sender.state == NSOffState {
        sender.state == NSOnState
      }
    }
  }
  println(sender.state)
}
</code>```

The connected button is an On-Off button. So when it's on and I ctrl-click it it will stay on.

Unfortunately in my app where I really need this it does not work. I checked that in both sandbox and prod app the bindings/settings are identically for both buttons. The debugger shows that

```<code>        sender.state == NSOnState
</code>```

is simply not performed. state stays NSOffState. Gnawing my keyboard did not help. Any idea?

答:
I know this already has an accepted answer, but sharing my scenario in case it trips up someone else:

I had the same issue where I couldn't programmatically set the state for my button in a custom table view cell.  MY issue, is that I was trying to set the state when my table first created the cell.  Instead, I had to make sure to override the layout method in my custom cell and set the state there.

Title: NSButton state not changing

Body:
The following code works perfect in my sandbox:

@IBAction func filterClicked(sender: NSButton) {
  println(sender.state)
  if let clickEvent = NSApp.currentEvent! {
    if Int(clickEvent.modifierFlags.rawValue) & Int(NSEventModifierFlags.ControlKeyMask.rawValue) != 0 {
      if sender.state == NSOffState {
        sender.state == NSOnState
      }
    }
  }
  println(sender.state)
}

The connected button is an On-Off button. So when it's on and I ctrl-click it it will stay on.

Unfortunately in my app where I really need this it does not work. I checked that in both sandbox and prod app the bindings/settings are identically for both buttons. The debugger shows that

        sender.state == NSOnState

is simply not performed. state stays NSOffState. Gnawing my keyboard did not help. Any idea?


问:
ASP.NET Core Identity Role, Claim and User
I am an ASP.NET Core beginner. I'm stuck in role, claim and user relationship.

I have a user Ben, user belongs to Admin role. Admin role has claims view-page and edit-page in database.

But I can't get claims and roles to be belonging to that user:

(Please see comment in code)

```<code>var user = await _userManager.FindByNameAsync(applicationUser.UserName);
if(user != null) {
    var userClaims = await _userManager.GetClaimsAsync(user); // empty, WHY ?
    var userRoles = await _userManager.GetRolesAsync(user); // ['admin']
    var adminRole = DbContext.Roles.FirstOrDefault(x => x.Name == "Admin");
    IList<Claim> adminClaims;
    if(adminRole != null)
    {
        adminClaims = await _roleManager.GetClaimsAsync(adminRole);
        // correct => ['view-page', 'edit-page']
    }
    }
}
</code>```

In my mind, I understand when a user is a member of a role, he inherit that role's claims.

Default ASP.NET Identity have 5 tables:

Users.

Roles.

UserRoles - A user can have many roles.

RoleClaims - A role can have many claims.

UserClaims - A user can have many claims.

Do i think correct ? Why userManager.GetClaimsAsync(user) returns empty claims ?

Any suggestion?

答:
I have had to deal with this issue recently and to solve the problem of locating Users by a particular Claim that came from a Role is to create a new Claim object with the values from the Role Claim:

```<code>var role = await roleManager.FindByNameAsync(yourRoleName);
if(role != null)
{
    var roleClaims = await roleManager.GetClaimsAsync(role);
    if(roleClaims != null && roleClaims.Count() > 0)
    {
        foreach(var claim in roleClaims.ToList())
        {
            var users = await userManager.GetUsersForClaimAsync(new Claim(claim.Type, claim.Value));
            if(users != null && users.Count() > 0)
            {
                foreach(var user in users.ToList())
                {
                   //This is an example of only removing a claim, but this is the
                   //area where you could remove/add the updated claim
                   await userManager.RemoveClaimAsync(user, new Claim(claim.Type, claim.Value));
                }
            }
        }
    }
}
</code>```

This allowed me to Update/Delete a role with claims and pass those changes to the Users to be Re-Issued/Removed that were assigned the roles and claims. However, I am still looking for something more elegant/easier with less code.

Body:
I am an ASP.NET Core beginner. I'm stuck in role, claim and user relationship.

I have a user Ben, user belongs to Admin role. Admin role has claims view-page and edit-page in database.

But I can't get claims and roles to be belonging to that user:

(Please see comment in code)

var user = await _userManager.FindByNameAsync(applicationUser.UserName);
if(user != null) {
    var userClaims = await _userManager.GetClaimsAsync(user); // empty, WHY ?
    var userRoles = await _userManager.GetRolesAsync(user); // ['admin']
    var adminRole = DbContext.Roles.FirstOrDefault(x => x.Name == "Admin");
    IList<Claim> adminClaims;
    if(adminRole != null)
    {
        adminClaims = await _roleManager.GetClaimsAsync(adminRole);
        // correct => ['view-page', 'edit-page']
    }
    }
}

In my mind, I understand when a user is a member of a role, he inherit that role's claims.

Default ASP.NET Identity have 5 tables:

Users.

Roles.

UserRoles - A user can have many roles.

RoleClaims - A role can have many claims.

UserClaims - A user can have many claims.

Do i think correct ? Why userManager.GetClaimsAsync(user) returns empty claims ?

Any suggestion?

Body:
I have had to deal with this issue recently and to solve the problem of locating Users by a particular Claim that came from a Role is to create a new Claim object with the values from the Role Claim:

var role = await roleManager.FindByNameAsync(yourRoleName);
if(role != null)
{
    var roleClaims = await roleManager.GetClaimsAsync(role);
    if(roleClaims != null && roleClaims.Count() > 0)
    {
        foreach(var claim in roleClaims.ToList())
        {
            var users = await userManager.GetUsersForClaimAsync(new Claim(claim.Type, claim.Value));
            if(users != null && users.Count() > 0)
            {
                foreach(var user in users.ToList())
                {
                   //This is an example of only removing a claim, but this is the
                   //area where you could remove/add the updated claim
                   await userManager.RemoveClaimAsync(user, new Claim(claim.Type, claim.Value));
                }
            }
        }
    }
}

This allowed me to Update/Delete a role with claims and pass those changes to the Users to be Re-Issued/Removed that were assigned the roles and claims. However, I am still looking for something more elegant/easier with less code.


问:
Angular2 Material : Custom Validation for Angular Material Input
In my Angular 2 and material application, I want to check whether username has already taken or not. If it is already taken then it should show the error.

I am following below guide.

https://material.angular.io/components/input/overview#error-messages

Typescript file

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

const existingUserNames = ['rohit', 'mohit', 'ronit'];

@Component({
   selector: 'input-errors-example',
   templateUrl: 'input-errors-example.html',
   styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {

    emailFormControl = new FormControl('', [
         Validators.required
    ]

    // I want to call below isUserNameTaken function but dont know
    // how to use it with Validators so that error message will be visible.

    isUserNameTaken() : boolean {
       this.attributeClasses = attributeClasseses;
       this.attributeClasses.find( object => {
           if(object.attributeClass === this.attributeClass) {
               console.log("found " + JSON.stringify(object));
               return true;
           }
       });
       return false;
   }
}
</code>```

HTML

```<code> <form class="example-form">
   <md-form-field class="example-full-width">
     <input mdInput placeholder="Email [formControl]="emailFormControl">
    <md-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </md-error>

  <!-- I want to make something like that - custom validation -->

     <md-error *ngIf="emailFormControl.hasError('username-already-taken')">
        Username is already taken. Please try another.
    </md-error>
  <!-- custom validation end -->

     </md-form-field>
</code>```

答:
You just have to change your function to receive a component as parameter and return null if everything is ok and an error object if it's not. Then, put it on the component validator's array.

```<code>// Control declaration
emailFormControl = new FormControl('', [
   Validators.required,
   isUserNameTaken
]

// Correct validator funcion
isUserNameTaken(component: Component): ValidationErrors {
    this.attributeClasses = attributeClasseses;
    this.attributeClasses.find( object => {
        if(object.attributeClass === this.attributeClass) {
            console.log("found " + JSON.stringify(object));
            // found the username
            return {
                username-already-taken: {
                    username: component.value
                }
            };
        }
    });
    // Everything is ok
    return null;
}
</code>```

It's explained in more depth in the link that Will Howell put on the comments. It also explains how to do the same for non reactive forms.

Tutorial

Body:
In my Angular 2 and material application, I want to check whether username has already taken or not. If it is already taken then it should show the error.

I am following below guide.

https://material.angular.io/components/input/overview#error-messages

Typescript file

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

const existingUserNames = ['rohit', 'mohit', 'ronit'];

@Component({
   selector: 'input-errors-example',
   templateUrl: 'input-errors-example.html',
   styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {

    emailFormControl = new FormControl('', [
         Validators.required
    ]

    // I want to call below isUserNameTaken function but dont know
    // how to use it with Validators so that error message will be visible.

    isUserNameTaken() : boolean {
       this.attributeClasses = attributeClasseses;
       this.attributeClasses.find( object => {
           if(object.attributeClass === this.attributeClass) {
               console.log("found " + JSON.stringify(object));
               return true;
           }
       });
       return false;
   }
}

HTML

 <form class="example-form">
   <md-form-field class="example-full-width">
     <input mdInput placeholder="Email [formControl]="emailFormControl">
    <md-error *ngIf="emailFormControl.hasError('required')">
      Email is required
    </md-error>

     <md-error *ngIf="emailFormControl.hasError('username-already-taken')">
        Username is already taken. Please try another.
    </md-error>

     </md-form-field>

Body:
You just have to change your function to receive a component as parameter and return null if everything is ok and an error object if it's not. Then, put it on the component validator's array.

// Control declaration
emailFormControl = new FormControl('', [
   Validators.required,
   isUserNameTaken
]

// Correct validator funcion
isUserNameTaken(component: Component): ValidationErrors {
    this.attributeClasses = attributeClasseses;
    this.attributeClasses.find( object => {
        if(object.attributeClass === this.attributeClass) {
            console.log("found " + JSON.stringify(object));
            // found the username
            return {
                username-already-taken: {
                    username: component.value
                }
            };
        }
    });
    // Everything is ok
    return null;
}

It's explained in more depth in the link that Will Howell put on the comments. It also explains how to do the same for non reactive forms.

Tutorial


问:
Git clone from remote ssh repository - change the machine on the remote network before executing the clone command
I'd like to clone a git repository from my company's servers to my personal computer. The only way to acces these servers from "outside" is by logging in per ssh to 'machine1'

```<code>ssh user@machine1.company.xy
</code>```

Unfortunately, git ist not installed on that specific machine. So a git clone like

```<code>git clone ssh://user@machine1.company.xy/path/to/repo <local-repo-path>
</code>```

won't work. What I would have to do is to change to another machine 'machine2' where git is installed after having logged in to the network via 'machine1'. So to get the clone working I would have to execute a command like

```<code>ssh machine2
</code>```

before actually executing the git command. Is there any way to do that? Something like a pre-clone hook maybe?

Is it possible to somehow pack the remote repository into a file (patch?), to copy that file onto the local machine and to clone from that file?

Looking forward to your hints and suggestions!

答:
You can do this by configuring a ssh proxy command. Note: this assumes netcat is available on the proxy server; you can replace netcat with a similar script in perl or whatever if needed.

Add the following to your ~/.ssh/config, creating it if needed:

```<code>Host machine1
User yourusername
HostName machine1.yourcompany.com

Host machine2
User yourusername
ProxyCommand ssh machine1 nc %h %p
HostName machine2.internal.network
</code>```

Now you can ssh machine2 and it will automatically tunnel through machine1. This means using git is as simple as git clone ssh://machine2/path.

It is also possible to bundle the repository into a single file, using the git bundle command. This shouldn't be necessary with a proper ssh proxy setup though.

Body:
I'd like to clone a git repository from my company's servers to my personal computer. The only way to acces these servers from "outside" is by logging in per ssh to 'machine1'

ssh user@machine1.company.xy

Unfortunately, git ist not installed on that specific machine. So a git clone like

git clone ssh://user@machine1.company.xy/path/to/repo <local-repo-path>

won't work. What I would have to do is to change to another machine 'machine2' where git is installed after having logged in to the network via 'machine1'. So to get the clone working I would have to execute a command like

ssh machine2

before actually executing the git command. Is there any way to do that? Something like a pre-clone hook maybe?

Is it possible to somehow pack the remote repository into a file (patch?), to copy that file onto the local machine and to clone from that file?

Looking forward to your hints and suggestions!

Body:
You can do this by configuring a ssh proxy command. Note: this assumes netcat is available on the proxy server; you can replace netcat with a similar script in perl or whatever if needed.

Add the following to your ~/.ssh/config, creating it if needed:

Host machine1
User yourusername
HostName machine1.yourcompany.com

Host machine2
User yourusername
ProxyCommand ssh machine1 nc %h %p
HostName machine2.internal.network

Now you can ssh machine2 and it will automatically tunnel through machine1. This means using git is as simple as git clone ssh://machine2/path.

It is also possible to bundle the repository into a single file, using the git bundle command. This shouldn't be necessary with a proper ssh proxy setup though.