问:
Javascript to calculate aqi
I am trying to write a javascript for calculating the aqi of a place I am using the openweathermap.com api for fetching data like co, 03 and pm2.5 concentration but am not able to get the output for the aqiValue. I am including js, html and css code below:
note: I checked and I am encountering some error in the js when I am calling for the function calculateAQI, could anyone please check that part of the code and tell me what might the issue be?

js:

```<code>var input = document.querySelector('.input_text');
var main = document.querySelector('#name');
var temp = document.querySelector('.temp');
var desc = document.querySelector('.desc');
var lat = document.querySelector('.lat');
var long = document.querySelector('.long');
var aqi = document.querySelector('.aqi');
var hum = document.querySelector('.hum');
var co = document.querySelector('.co');
var feels = document.querySelector('.feels');
var clouds = document.querySelector('.clouds');
var button= document.querySelector('.submit');
var tempValue=null;
var nameValue=null;
var latValue=null;
var latValue=null;
var longValue=null;
var aqiValue=null;
var coValue=null;
var o3=null;
var pm25=null;
var aqiv = null;
var IHi = null;
var Ilo = null;
var BPHi = null;
var BPlo = null;
var Cp = null;
var o3Index = null;
var pm25Index = null;
var coIndex = null;

function a()
{
  fetch('https://api.openweathermap.org/data/2.5/weather?q='+input.value+'&appid=7031deafbb01e5bded284c1ab5dd580c')
.then(response => response.json())
.then(data => {
  var tempValue = data['main']['temp'];
  tempValue=parseInt(tempValue-273);
  var nameValue = data['name'];
  var descValue = data['weather'][0]['description'];
  var latValue = data['coord']['lat'];
  var longValue = data['coord']['lon'];
  var humValue = data['main']['humidity'];
  var feelsValue = data['main']['feels_like'];
  feelsValue=parseInt(feelsValue-273);
  main.innerHTML = nameValue;
  desc.innerHTML = "Desc - "+descValue;
  temp.innerHTML = "Temp - "+tempValue;
  feels.innerHTML = "Feels Like - "+feelsValue;
  hum.innerHTML = "Humidity - "+humValue+"%";
  lat.innerHTML = "Latitute - "+latValue;
  long.innerHTML = "Longitude - "+longValue;
  b(latValue,longValue);
})

}
function b(latValue,longValue)
{
  var ts = Math.round((new Date()).getTime() / 1000);
  fetch('http://api.openweathermap.org/data/2.5/air_pollution?lat='+latValue+'&lon='+longValue+'&appid=7031deafbb01e5bded284c1ab5dd580c')
  .then(responset => responset.json())
  .then(datat => {
    //var aqiValue = datat['list'][0]['main']['aqi'];
    var coValue = datat['list'][0]['components']['co']*0.00087;
    var o3Value = datat['list'][0]['components']['o3']*0.51;
    var pm25Value = datat['list'][0]['components']['pm2_5'];
    var aqiValue = calculateAQI(o3Value ,pm25Value, coValue);
    aqi.innerHTML = "AQI - "+aqiValue;
    co.innerHTML = "CO - "+coValue;
    exit(0);
  })
}

function calculateAQI(o3, pm25, co) {
  var aqiv = null;
  var IHi = null;
  var Ilo = null;
  var BPHi = null;
  var BPlo = null;
  var Cp = null;
  var o3Index = null;
  var pm25Index = null;
  var coIndex = null;
  // Ozone (O3) calculation

  if (o3>=0 && o3<=50)
  {
    IHi=50;
    Ilo=0;
    BPHi=50;
    BPlo=0;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=51 && o3<=100)
  {
    IHi=100;
    Ilo=51;
    BPHi=100;
    BPlo=51;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=101 && o3<=168)
  {
    IHi=200;
    Ilo=101;
    BPHi=168;
    BPlo=101;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=169 && o3<=208)
  {
    IHi=300;
    Ilo=201;
    BPHi=208;
    BPlo=169;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=209 && o3<=748)
  {
    IHi=400;
    Ilo=301;
    BPHi=748;
    BPlo=209;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=1000;
    BPlo=748;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, o3Index);

  // Particulate matter (PM2.5) calculation

  if(pm25>=0 && pm<=30)
  {
    IHi=50;
    Ilo=0;
    BPHi=30;
    BPlo=0;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=31 && pm<=60)
  {
    IHi=100;
    Ilo=51;
    BPHi=60;
    BPlo=31;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=61 && pm<=90)
  {
    IHi=200;
    Ilo=101;
    BPHi=90;
    BPlo=61;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=91 && pm<=120)
  {
    IHi=300;
    Ilo=201;
    BPHi=120;
    BPlo=91;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=121 && pm<=250)
  {
    IHi=400;
    Ilo=301;
    BPHi=250;
    BPlo=121;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=379;
    BPlo=250;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, pm25Index);

  // Carbon monoxide (CO) calculation

  if(co>=0 && co<=1)
  {
    IHi=50;
    Ilo=0;
    BPHi=1;
    BPlo=0;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=1.1 && co<=2)
  {
    IHi=100;
    Ilo=51;
    BPHi=2;
    BPlo=1.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=2.1 && co<=10)
  {
    IHi=200;
    Ilo=101;
    BPHi=10;
    BPlo=2.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=10.1 && co<=17)
  {
    IHi=300;
    Ilo=201;
    BPHi=17;
    BPlo=10.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=17.1 && co<=34)
  {
    IHi=400;
    Ilo=301;
    BPHi=34;
    BPlo=17.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=69;
    BPlo=34.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, coIndex);

  return aqiv;
}

button.addEventListener('click', function(name){

try{
  a();
  main.innerHTML = "Place not Found!";
}

catch(err)
{
  main.innerHTML = err.message;
}
})

</code>```

html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>OpenWeatherMap Api</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- <div class="main">
    <div class="header">
      <h1>OpenWeatherMap API</h1>
      <p>Enter any city name in the input box below to get the data</p>
    </div> -->

    <div class="input">
      <input type="text" placeholder="Enter the city" class="input_text">
      <input type="submit" value="Submit" class="submit">
    </div>
  </div>

  <div class="container">
    <div class="card">
      <h1 class="name" id="name"></h1>
      <p class="aqi"></p>
      <p class="temp"></p>
      <p class="feels"></p>
      <p class="hum"></p>
      <p class="clouds"></p>
      <p class="desc"></p>
      <p class="lat"></p>
      <p class="long"></p>
      <p class="co"></p>
    </div>
  </div>
<script src="app.js"></script>
</body>
</html>
</code>```

css:

```<code>*{
  margin:0;
  padding: 0;
  box-sizing: border-box;
}

body{
  font-family: "Nunito",sans-serif;
  background: #f8f8f8;
}

.input{
  text-align: center;
  margin: 100px auto;
}

input[type="submit"]{
  padding: 15px 30px;
  background: #e7e7e7;
  border: none;
  border-radius: 1px;
  font-family: "Nunito",sans-serif;
  font-weight:bold;
  font-size: 20px;
}

.input input[type="text"]{
  width: 600px;
  height: 55px;
  padding: 5px 10px;
  background: #e7e7e7;
  border: none;
  border-radius: 1px;
  font-family: "Nunito",sans-serif;
  font-weight:bold;
  font-size: 20px;
}

.card{
  width: 50%;
  background: #e7e7e7;
  height: 40vh;
  margin: 50px auto;
  border-radius: 2px;
}

.close{
  float: right;
  margin-top: -2px;
  cursor: pointer;
  margin-right: 20px;
}

.card h1{
  padding: 5px 0;
  text-align: center;
}

.card p{
  text-align: center;
  margin:40px 40px;
  font-size:20px;
}
</code>```

I am very new to js and am rquesting for suggestions for fixes in my code.

Title: Javascript to calculate aqi

Body:
I am trying to write a javascript for calculating the aqi of a place I am using the openweathermap.com api for fetching data like co, 03 and pm2.5 concentration but am not able to get the output for the aqiValue. I am including js, html and css code below:
note: I checked and I am encountering some error in the js when I am calling for the function calculateAQI, could anyone please check that part of the code and tell me what might the issue be?

js:

var input = document.querySelector('.input_text');
var main = document.querySelector('#name');
var temp = document.querySelector('.temp');
var desc = document.querySelector('.desc');
var lat = document.querySelector('.lat');
var long = document.querySelector('.long');
var aqi = document.querySelector('.aqi');
var hum = document.querySelector('.hum');
var co = document.querySelector('.co');
var feels = document.querySelector('.feels');
var clouds = document.querySelector('.clouds');
var button= document.querySelector('.submit');
var tempValue=null;
var nameValue=null;
var latValue=null;
var latValue=null;
var longValue=null;
var aqiValue=null;
var coValue=null;
var o3=null;
var pm25=null;
var aqiv = null;
var IHi = null;
var Ilo = null;
var BPHi = null;
var BPlo = null;
var Cp = null;
var o3Index = null;
var pm25Index = null;
var coIndex = null;

function a()
{
  fetch('https://api.openweathermap.org/data/2.5/weather?q='+input.value+'&appid=7031deafbb01e5bded284c1ab5dd580c')
.then(response => response.json())
.then(data => {
  var tempValue = data['main']['temp'];
  tempValue=parseInt(tempValue-273);
  var nameValue = data['name'];
  var descValue = data['weather'][0]['description'];
  var latValue = data['coord']['lat'];
  var longValue = data['coord']['lon'];
  var humValue = data['main']['humidity'];
  var feelsValue = data['main']['feels_like'];
  feelsValue=parseInt(feelsValue-273);
  main.innerHTML = nameValue;
  desc.innerHTML = "Desc - "+descValue;
  temp.innerHTML = "Temp - "+tempValue;
  feels.innerHTML = "Feels Like - "+feelsValue;
  hum.innerHTML = "Humidity - "+humValue+"%";
  lat.innerHTML = "Latitute - "+latValue;
  long.innerHTML = "Longitude - "+longValue;
  b(latValue,longValue);
})

}
function b(latValue,longValue)
{
  var ts = Math.round((new Date()).getTime() / 1000);
  fetch('http://api.openweathermap.org/data/2.5/air_pollution?lat='+latValue+'&lon='+longValue+'&appid=7031deafbb01e5bded284c1ab5dd580c')
  .then(responset => responset.json())
  .then(datat => {
    //var aqiValue = datat['list'][0]['main']['aqi'];
    var coValue = datat['list'][0]['components']['co']*0.00087;
    var o3Value = datat['list'][0]['components']['o3']*0.51;
    var pm25Value = datat['list'][0]['components']['pm2_5'];
    var aqiValue = calculateAQI(o3Value ,pm25Value, coValue);
    aqi.innerHTML = "AQI - "+aqiValue;
    co.innerHTML = "CO - "+coValue;
    exit(0);
  })
}

function calculateAQI(o3, pm25, co) {
  var aqiv = null;
  var IHi = null;
  var Ilo = null;
  var BPHi = null;
  var BPlo = null;
  var Cp = null;
  var o3Index = null;
  var pm25Index = null;
  var coIndex = null;
  // Ozone (O3) calculation

  if (o3>=0 && o3<=50)
  {
    IHi=50;
    Ilo=0;
    BPHi=50;
    BPlo=0;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=51 && o3<=100)
  {
    IHi=100;
    Ilo=51;
    BPHi=100;
    BPlo=51;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=101 && o3<=168)
  {
    IHi=200;
    Ilo=101;
    BPHi=168;
    BPlo=101;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=169 && o3<=208)
  {
    IHi=300;
    Ilo=201;
    BPHi=208;
    BPlo=169;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(o3>=209 && o3<=748)
  {
    IHi=400;
    Ilo=301;
    BPHi=748;
    BPlo=209;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=1000;
    BPlo=748;
    Cp=o3;
    o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, o3Index);

  // Particulate matter (PM2.5) calculation

  if(pm25>=0 && pm<=30)
  {
    IHi=50;
    Ilo=0;
    BPHi=30;
    BPlo=0;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=31 && pm<=60)
  {
    IHi=100;
    Ilo=51;
    BPHi=60;
    BPlo=31;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=61 && pm<=90)
  {
    IHi=200;
    Ilo=101;
    BPHi=90;
    BPlo=61;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=91 && pm<=120)
  {
    IHi=300;
    Ilo=201;
    BPHi=120;
    BPlo=91;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(pm25>=121 && pm<=250)
  {
    IHi=400;
    Ilo=301;
    BPHi=250;
    BPlo=121;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=379;
    BPlo=250;
    Cp=pm25;
    pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, pm25Index);

  // Carbon monoxide (CO) calculation

  if(co>=0 && co<=1)
  {
    IHi=50;
    Ilo=0;
    BPHi=1;
    BPlo=0;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=1.1 && co<=2)
  {
    IHi=100;
    Ilo=51;
    BPHi=2;
    BPlo=1.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=2.1 && co<=10)
  {
    IHi=200;
    Ilo=101;
    BPHi=10;
    BPlo=2.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=10.1 && co<=17)
  {
    IHi=300;
    Ilo=201;
    BPHi=17;
    BPlo=10.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else if(co>=17.1 && co<=34)
  {
    IHi=400;
    Ilo=301;
    BPHi=34;
    BPlo=17.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  else
  {
    IHi=500;
    Ilo=401;
    BPHi=69;
    BPlo=34.1;
    Cp=co;
    coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
  }
  aqiv = Math.max(aqiv, coIndex);

  return aqiv;
}

button.addEventListener('click', function(name){

try{
  a();
  main.innerHTML = "Place not Found!";
}

catch(err)
{
  main.innerHTML = err.message;
}
})

html:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>OpenWeatherMap Api</title>
  <link rel="stylesheet" href="style.css">

      <input type="text" placeholder="Enter the city" class="input_text">
      <input type="submit" value="Submit" class="submit">

css:

*{
  margin:0;
  padding: 0;
  box-sizing: border-box;
}

body{
  font-family: "Nunito",sans-serif;
  background: #f8f8f8;
}

.input{
  text-align: center;
  margin: 100px auto;
}

input[type="submit"]{
  padding: 15px 30px;
  background: #e7e7e7;
  border: none;
  border-radius: 1px;
  font-family: "Nunito",sans-serif;
  font-weight:bold;
  font-size: 20px;
}

.input input[type="text"]{
  width: 600px;
  height: 55px;
  padding: 5px 10px;
  background: #e7e7e7;
  border: none;
  border-radius: 1px;
  font-family: "Nunito",sans-serif;
  font-weight:bold;
  font-size: 20px;
}

.card{
  width: 50%;
  background: #e7e7e7;
  height: 40vh;
  margin: 50px auto;
  border-radius: 2px;
}

.close{
  float: right;
  margin-top: -2px;
  cursor: pointer;
  margin-right: 20px;
}

.card h1{
  padding: 5px 0;
  text-align: center;
}

.card p{
  text-align: center;
  margin:40px 40px;
  font-size:20px;
}

I am very new to js and am rquesting for suggestions for fixes in my code.


来源: stackexchange

问:
Can a Form Recogniser Model be trained in the SDK environment?
I've set up an sdk environment running to use azure form recogniser that is currently using the pre-built document layout model as an example.

Is it possible to use this environment to train a new custom model? I can't find any documentation relating to how I might start. I can't use the form recogniser studio to train the model, as it won't allow me to access the correct subscription to do the work in.

ContentLicense: CC BY-SA 4.0


问:
Authorize.net SDK for iOS and BBPOS terminals
Is there any way to embed authorize.net iOS SDK into iOS application compatible with recent iOS version and BBPOS terminals?
#authorize.net

https://github.com/AuthorizeNet/inperson-sdk-ios this SDK is not supported by Xcode 14.1 and we can't integrate it into our project.


问:
Pytest monkeypatch mock leak
I have a module that I am trying to unit test, and when running individual tests by themselves, each test will pass. When I try to run the full set of tests together in a single test session using pytest test_some_module.py, some tests will fail due to a monkeypatch mock that is leaking across tests.

I have an example module, handler.py that is as follows:

import os

from redis import Redis

host = os.environ["REDIS_HOSTNAME"]
r = Redis(host=host, db=0)

def lambda_handler(event, context):
    """Lambda Handler"""

    for key, value in event.items():
        r.set(key, value)

    keys = r.keys()
    return keys

```
<p>Then I have a test module, <code>test_redis.py</code>, with the following code:</p>
<pre class="lang-py prettyprint-override"><code>
import pytest
import redis
from fakeredis import FakeRedis

@pytest.fixture()
def hostname():
    return "a fake host"

@pytest.fixture()
def fake_redis(hostname):
    return FakeRedis(host=hostname, db=0)

@pytest.fixture(autouse=True)
def mock_redis(monkeypatch, fake_redis, hostname):
    def _redis(*args, **kwargs):
        return fake_redis

    monkeypatch.setattr(redis, "Redis", _redis)
    monkeypatch.setattr(redis, "StrictRedis", _redis)
    monkeypatch.setenv("REDIS_HOSTNAME", hostname)

def test_cache_is_set(hostname):
    from handler import lambda_handler

    result = lambda_handler({"a_key": "value"}, {})
    assert len(result) == 1

def test_cache_is_empty(hostname):
    from handler import lambda_handler

    result = lambda_handler({}, {})
    assert len(result) == 0

</code>```

When I go to run either of the test functions by themselves, they will pass.
However, when I run pytest test_redis.py, the test_cache_is_empty unit test will fail due to keys being present in the monkeypatched Redis database using FakeRedis.

This is failing for me on Linux. Is there a good way to do this to ensure that mocked objects don't leak across unit tests?

I'm using pytest 6.2.4 and fakeredis 1.6.0.

For context, I have tried adding the following code to the mock_redis test fixture and it still won't work as intended.

@pytest.fixture(autouse=True)
def mock_redis(monkeypatch, fake_redis, hostname):
    def _redis(*args, **kwargs):
        return fake_redis

    monkeypatch.setattr(redis, "Redis", _redis)
    monkeypatch.setattr(redis, "StrictRedis", _redis)
    monkeypatch.setenv("REDIS_HOSTNAME", hostname)
    yield
    fake_redis.flushall()  # <- This should work and flush the db for the next test function to use
```

Title: Pytest monkeypatch mock leak

Body:
I have a module that I am trying to unit test, and when running individual tests by themselves, each test will pass. When I try to run the full set of tests together in a single test session using pytest test_some_module.py, some tests will fail due to a monkeypatch mock that is leaking across tests.

I have an example module, handler.py that is as follows:

import os

from redis import Redis

host = os.environ["REDIS_HOSTNAME"]
r = Redis(host=host, db=0)

def lambda_handler(event, context):
    """Lambda Handler"""

    for key, value in event.items():
        r.set(key, value)

    keys = r.keys()
    return keys

Then I have a test module, test_redis.py, with the following code:

import pytest
import redis
from fakeredis import FakeRedis

@pytest.fixture()
def hostname():
    return "a fake host"

@pytest.fixture()
def fake_redis(hostname):
    return FakeRedis(host=hostname, db=0)

@pytest.fixture(autouse=True)
def mock_redis(monkeypatch, fake_redis, hostname):
    def _redis(*args, **kwargs):
        return fake_redis

    monkeypatch.setattr(redis, "Redis", _redis)
    monkeypatch.setattr(redis, "StrictRedis", _redis)
    monkeypatch.setenv("REDIS_HOSTNAME", hostname)

def test_cache_is_set(hostname):
    from handler import lambda_handler

    result = lambda_handler({"a_key": "value"}, {})
    assert len(result) == 1

def test_cache_is_empty(hostname):
    from handler import lambda_handler

    result = lambda_handler({}, {})
    assert len(result) == 0

When I go to run either of the test functions by themselves, they will pass.
However, when I run pytest test_redis.py, the test_cache_is_empty unit test will fail due to keys being present in the monkeypatched Redis database using FakeRedis.

This is failing for me on Linux. Is there a good way to do this to ensure that mocked objects don't leak across unit tests?

I'm using pytest 6.2.4 and fakeredis 1.6.0.

For context, I have tried adding the following code to the mock_redis test fixture and it still won't work as intended.

@pytest.fixture(autouse=True)
def mock_redis(monkeypatch, fake_redis, hostname):
    def _redis(*args, **kwargs):
        return fake_redis

    monkeypatch.setattr(redis, "Redis", _redis)
    monkeypatch.setattr(redis, "StrictRedis", _redis)
    monkeypatch.setenv("REDIS_HOSTNAME", hostname)
    yield
    fake_redis.flushall()  # <- This should work and flush the db for the next test function to use


问:
Intellij Console Excess Output
Here is an output to a simple piece of code:

/Library/Java/JavaVirtualMachines/jdk-18.0.2.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=60596:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/IdeaProjects/StringFormatting/out/production/StringFormatting Main
Print a Bulleted List:• First Point• Sub Point

Process finished with exit code 0

How do I remove the javaagent, jar, encoding and classpath from the output console?

Title: Intellij Console Excess Output


问:
Study purpose: Set value true/false by clicking on task
Hello i have component Vue, taskdone.php and todo.json.

At moment i can create new tasks from input in vue(frontend), send it on php(backend) and store it in todo.json.

I m trying to add feature that i click on text with the task and the value "completed" change from true to false but dont work.

Can someone explain me the fixes and the reason ?

Thanks for your time

todo.VUE

```<code><script >
import axios from 'axios';
const API_URL = "http://localhost/";
export default {
data(){
  return{
    task : "",
    todoList : []
  }
},
methods: {
  getAll(){
    axios.get(API_URL + "api.php")
    .then(res => {
      const data = res.data;
      this.todoList = data;
    });

  },
  addNew(e){
    e.preventDefault();
    const params = { params: {
      "newTask" : this.task
    }};
    axios.get(API_URL + "newtask.php",params)
    .then(() => {
      this.getAll();
    })
    this.task = "";
  },
  taskDone(i){
    const params = { params: {
      "id" : i
    }}
    axios.get(API_URL + "newtask.php", params)
    console.log(i);
  }
},
mounted(){
  this.getAll();
}
}

</script>

<template>
    <form action="" @submit="addNew">
      <label for="">Inserisci task: </label>
      <input type="text" v-model="task">
      <input type="submit" value="Add" >
    </form>
    <ul>
      <li v-for="(task,index) in todoList" :key="index" :class="task.completed == true ? 'taskDone': ''" @click="taskDone(index)">
        {{ task.text }}
        {{ task.completed }}
      </li>
    </ul>
</template>

<style scoped>
.taskDone{
  text-decoration:line-through;
}

</style>
</code>```

taskdone.php

```<code><?php
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Headers: X-Requested-With");

header("Content-Type: application/json");
$id = $_GET["id"];

$jsonTodoList = file_get_contents("todo.json");
$todoList = json_decode($jsonTodoList);

$todoList=$todoList[$id]["completed"] = !$todoList[$id]["completed"];

$jsonTodoList = json_encode($todoList);
file_put_contents("todo.json" , $jsonTodoList);
</code>```

todo.json

```<code>[
{"text":"take a break",
 "completed":false
},
{"text":"buy a coffee",
"completed":false
}
]
</code>```

Body:
Hello i have component Vue, taskdone.php and todo.json.

At moment i can create new tasks from input in vue(frontend), send it on php(backend) and store it in todo.json.

I m trying to add feature that i click on text with the task and the value "completed" change from true to false but dont work.

Can someone explain me the fixes and the reason ?

Thanks for your time

todo.VUE

<template>
    <form action="" @submit="addNew">
      Inserisci task:
      <input type="text" v-model="task">
      <input type="submit" value="Add" >
    </form>

        {{ task.text }}
        {{ task.completed }}

</template>

taskdone.php

<?php
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Headers: X-Requested-With");

header("Content-Type: application/json");
$id = $_GET["id"];

$jsonTodoList = file_get_contents("todo.json");
$todoList = json_decode($jsonTodoList);

$todoList=$todoList[$id]["completed"] = !$todoList[$id]["completed"];

$jsonTodoList = json_encode($todoList);
file_put_contents("todo.json" , $jsonTodoList);

todo.json

[
{"text":"take a break",
 "completed":false
},
{"text":"buy a coffee",
"completed":false
}
]


问:
Sending email to a list of users using mailx in subprocess
This code works to send email to a single or more users:

```<code>msg="My text message"
p1=subprocess.run(["echo",msg],stdout=subprocess.PIPE)
subprocess.run(["mailx -s 'Subject: Hive Alert' 'email1@email.com' 'email2@email.com'< /dev/stdin"],stdout=subprocess.PIPE,input=p1.stdout,shell=True)
</code>```

I have a python list

```<code>users=['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']
</code>```

How do I send email to a python list by modifying the above code or any other code using mailx in subprocess?

TIA
Shari

Body:
This code works to send email to a single or more users:

msg="My text message"
p1=subprocess.run(["echo",msg],stdout=subprocess.PIPE)
subprocess.run(["mailx -s 'Subject: Hive Alert' 'email1@email.com' 'email2@email.com'< /dev/stdin"],stdout=subprocess.PIPE,input=p1.stdout,shell=True)

I have a python list

users=['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']

How do I send email to a python list by modifying the above code or any other code using mailx in subprocess?

TIA
Shari


问:
Flutter: BottomNavigationBar malfunctions when referring to the same page/widget
I have a BottomNavigationBar and realized that when I was changing the index I was displaying pretty much the exact same page/widget except for a 2 parameters. So I decided to consolidate the widgets into one that take in the parameters, but the issue is that now that I did that it doesn't work. I assume it has something to do with the page already being initialized and having a state? Here is what my widget with the BottomNavigationBar looks like:

```<code>class SpeedPage extends StatefulWidget {
  const SpeedPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedPageState();
  }
}

class _SpeedPageState extends State<SpeedPage> {
  int _currentIndex = 0;
  static const List<Widget> _widgetOptions = <Widget>[
    WorkoutListPage(categoryIndex: 0, subCategories: Utils.srsDropdown),
    WorkoutListPage(categoryIndex: 1, subCategories: Utils.ddsDropdown),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [_widgetOptions.elementAt(_currentIndex)],
      )),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        items: const [
          BottomNavigationBarItem(
              icon: Icon(Icons.looks_one_outlined),
              label: 'Single rope',
              backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
          BottomNavigationBarItem(
              icon: Icon(Icons.looks_two_outlined),
              label: 'Double dutch',
              backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
        ],
        onTap: _onItemTapped,
      ),
    );
  }

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}
</code>```

and here is what my WorkoutListPage widget looks like:

```<code>class WorkoutListPage extends StatefulWidget {
  final int categoryIndex;
  final List<String> subCategories;
  const WorkoutListPage(
      {Key? key, required this.categoryIndex, required this.subCategories})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _WorkoutListPageState();
  }
}

class _WorkoutListPageState extends State<WorkoutListPage> {
  bool isLoading = true;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(widget.categoryIndex, widget.subCategories)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}
</code>```

and this doesn't work – it lags between tabs or the page simply doesn't change. Ironically, if in my SpeedPage I change my _widgetOptions to be the following:

```<code>static const List<Widget> _widgetOptions = <Widget>[
    SpeedSRPage(),
    SpeedDDPage()
  ];
</code>```

where my SpeedSRPage() and SpeedDDPage() are:

```<code>class SpeedSRPage extends StatefulWidget {
  const SpeedSRPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedSRPageState();
  }
}

class _SpeedSRPageState extends State<SpeedSRPage> {
  var isLoading = true;

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(0, Utils.srsDropdown)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}
</code>```

and

```<code>class SpeedDDPage extends StatefulWidget {
  const SpeedDDPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedDDPageState();
  }
}

class _SpeedDDPageState extends State<SpeedDDPage> {
  var isLoading = true;

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(1, Utils.ddsDropdown)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}
</code>```

respectively, it works. I also know that it isn't a problem with the WorkoutListPage because if I change my _widgetOptions to something like:

```<code>static const List<Widget> _widgetOptions = <Widget>[
    WorkoutListPage(categoryIndex: 0, subCategories: Utils.srsDropdown),
    SpeedDDPage(),
  ];
</code>```

it also works. So the issue seems to be that I am using the same widget (WorkoutListPage) twice in one BottomNavigationBar. I suspect it has something to do with the state initiation; if I add this line to the workoutListPageState():

```<code>void initState() {
    print("Initiated state");
    super.initState();
  }
</code>```

"Initiated state" only prints once if I switch tabs and the items in my _widgetOptions are both a WorkoutListPage. But if I switch my _widgetOptions to have different widgets "Initiated state" prints out every time I change tabs.

Body:
I have a BottomNavigationBar and realized that when I was changing the index I was displaying pretty much the exact same page/widget except for a 2 parameters. So I decided to consolidate the widgets into one that take in the parameters, but the issue is that now that I did that it doesn't work. I assume it has something to do with the page already being initialized and having a state? Here is what my widget with the BottomNavigationBar looks like:

class SpeedPage extends StatefulWidget {
  const SpeedPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedPageState();
  }
}

class _SpeedPageState extends State<SpeedPage> {
  int _currentIndex = 0;
  static const List<Widget> _widgetOptions = <Widget>[
    WorkoutListPage(categoryIndex: 0, subCategories: Utils.srsDropdown),
    WorkoutListPage(categoryIndex: 1, subCategories: Utils.ddsDropdown),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [_widgetOptions.elementAt(_currentIndex)],
      )),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        items: const [
          BottomNavigationBarItem(
              icon: Icon(Icons.looks_one_outlined),
              label: 'Single rope',
              backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
          BottomNavigationBarItem(
              icon: Icon(Icons.looks_two_outlined),
              label: 'Double dutch',
              backgroundColor: Color.fromRGBO(204, 16, 138, 1)),
        ],
        onTap: _onItemTapped,
      ),
    );
  }

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

and here is what my WorkoutListPage widget looks like:

class WorkoutListPage extends StatefulWidget {
  final int categoryIndex;
  final List<String> subCategories;
  const WorkoutListPage(
      {Key? key, required this.categoryIndex, required this.subCategories})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _WorkoutListPageState();
  }
}

class _WorkoutListPageState extends State<WorkoutListPage> {
  bool isLoading = true;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(widget.categoryIndex, widget.subCategories)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}

and this doesn't work – it lags between tabs or the page simply doesn't change. Ironically, if in my SpeedPage I change my _widgetOptions to be the following:

static const List<Widget> _widgetOptions = <Widget>[
    SpeedSRPage(),
    SpeedDDPage()
  ];

where my SpeedSRPage() and SpeedDDPage() are:

class SpeedSRPage extends StatefulWidget {
  const SpeedSRPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedSRPageState();
  }
}

class _SpeedSRPageState extends State<SpeedSRPage> {
  var isLoading = true;

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(0, Utils.srsDropdown)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}

and

class SpeedDDPage extends StatefulWidget {
  const SpeedDDPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SpeedDDPageState();
  }
}

class _SpeedDDPageState extends State<SpeedDDPage> {
  var isLoading = true;

  @override
  Widget build(BuildContext context) =>
      FutureBuilder<List<Map<String, dynamic>>>(
        future: MyCard.getData(1, Utils.ddsDropdown)!
            .whenComplete(() => setState(() {
                  isLoading = false;
                })),
        builder: ((context, snapshot) {
          if (snapshot.hasData && snapshot.data!.isNotEmpty) {
            return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: card.length,
                        itemBuilder: (context, index) {
                          return MyCard.buildCard(card[index], context);
                        },
                      ),
                    );
                  } else {
                    return const Text("No data");
                  }
                });
          } else {
            return isLoading
                ? Column(
                    children: const [CircularProgressIndicator()],
                  )
                : const Text("You do not have any workouts yet");
          }
        }),
      );
}

respectively, it works. I also know that it isn't a problem with the WorkoutListPage because if I change my _widgetOptions to something like:

static const List<Widget> _widgetOptions = <Widget>[
    WorkoutListPage(categoryIndex: 0, subCategories: Utils.srsDropdown),
    SpeedDDPage(),
  ];

it also works. So the issue seems to be that I am using the same widget (WorkoutListPage) twice in one BottomNavigationBar. I suspect it has something to do with the state initiation; if I add this line to the workoutListPageState():

void initState() {
    print("Initiated state");
    super.initState();
  }

"Initiated state" only prints once if I switch tabs and the items in my _widgetOptions are both a WorkoutListPage. But if I switch my _widgetOptions to have different widgets "Initiated state" prints out every time I change tabs.


问:
Should APK Signature Scheme v3 be avoided in favor of v3.1?
Android 9/Pie/API 28 introduced APK Signature Scheme v3. From Android 9 release notes:

This scheme has the option to include a proof-of-rotation record in its signing block for each signing certificate. This capability enables your app to be signed with a new signing certificate by linking the APK file's past signing certificates to the one with which it is now signed.

Key rotation can be helpful for old apps originally created with insecure keys. My understanding is that key rotation with APK Signature Scheme v3 requires manually managing the old and new keys and using apksigner. From a May 2020 dev rel article on App Signing:

the current key upgrade process does not take advantage of the key rotation feature introduced in Android 9 (Pie) and above. We are currently investigating support for key rotation using app signing v3 for devices on these OS versions and will let the developer community know once it’s ready in a separate announcement.

The APK Signature Scheme v3 docs also have this warning that I don't understand:

APK key rotation is not recommended before the release of Android 11.

When I look at Android 11 release notes, I see:

Several CLI commands for signing builds for release are changed in Android 11.

I can't find additional details. This seems to be just about tooling so I don't think it's relevant anymore.

Now I've found a section on APK Signature Scheme v3.1 in the Android 13 release notes:

This scheme is used by default when signing an APK with a rotated signing key and signing lineage, and allows a single APK to target rotation on Android 13 and later while avoiding the known issues with rotation on previous platform versions by using the original signing key in the v3.0 signature block.

What are the tradeoffs between:

using key rotation with v3 and being able to have more devices using app updates signed with a stronger key

using the v3.1 scheme and getting the stronger key out only to Android 13+ users

In particular, what are the "known issues" with v3 and how might those affect an app that uses it?


问:
Kafka consumer group's offset stuck for one topic
I have an application that uses fs2-kafka for reading business events from a kafka cluster. In that application, I have multiple fs2-kafka consumers, each subscribed to a different topic. But one of the consumers seems to be stuck, as it does not consume any events.

Checking the consumer group's offsets yielded the following results:

```<code>GROUP      TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                             HOST             CLIENT-ID
consumer   topic   0          -               5               -               consumer-consumer-1-99c1c19a-faaf-40e6-a3dc-75b7d04e96f9 /10.0.3.2       consumer-consumer-1
</code>```

(edited this slightly cause privacy)

I have also managed to get the CURRENT-OFFSET to be 1 (though, it seems like no actual consuming happened because none of my logs were triggered), but regardless - the group does not seem to want to move its offset.

The topic has just one partition and there's only one consumer/consumer group reading from that topic. There is no reason I can see for kafka to hold consumers from consuming. If it matters - that topic, as well as any other topic in this cluster, is created automatically, using kafka's "AUTO_CREATE_TOPICS". (this is a dev environment, it's simply more convinient than creating topics by hand)

The strangest thing is this - the same code, working on a different topic, works. Also, as it is always the case with these things, on my laptop the issue does not reproduce. There's barely any differences between my local kafka and the kafka in our dev cluster.

Originally, I had just one consumer group for the entire application. I have now tried multiple consumer groups per consumer and even sharing a consumer for reading from multiple topics. The only topic that's stuck is this one, every other topic works.

I have also tried:

Restarting kafka and the app, updating kafka to a newer version

Manually resetting the consumer group's offsets

Deleting the topic

Apart from deleting all the data of kafka, I believe I have tried everything on my and kafka's side.

Body:
I have an application that uses fs2-kafka for reading business events from a kafka cluster. In that application, I have multiple fs2-kafka consumers, each subscribed to a different topic. But one of the consumers seems to be stuck, as it does not consume any events.

Checking the consumer group's offsets yielded the following results:

GROUP      TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                             HOST             CLIENT-ID
consumer   topic   0          -               5               -               consumer-consumer-1-99c1c19a-faaf-40e6-a3dc-75b7d04e96f9 /10.0.3.2       consumer-consumer-1

(edited this slightly cause privacy)

I have also managed to get the CURRENT-OFFSET to be 1 (though, it seems like no actual consuming happened because none of my logs were triggered), but regardless - the group does not seem to want to move its offset.

The topic has just one partition and there's only one consumer/consumer group reading from that topic. There is no reason I can see for kafka to hold consumers from consuming. If it matters - that topic, as well as any other topic in this cluster, is created automatically, using kafka's "AUTO_CREATE_TOPICS". (this is a dev environment, it's simply more convinient than creating topics by hand)

The strangest thing is this - the same code, working on a different topic, works. Also, as it is always the case with these things, on my laptop the issue does not reproduce. There's barely any differences between my local kafka and the kafka in our dev cluster.

Originally, I had just one consumer group for the entire application. I have now tried multiple consumer groups per consumer and even sharing a consumer for reading from multiple topics. The only topic that's stuck is this one, every other topic works.

I have also tried:

Restarting kafka and the app, updating kafka to a newer version

Manually resetting the consumer group's offsets

Deleting the topic

Apart from deleting all the data of kafka, I believe I have tried everything on my and kafka's side.


问:
Nest.js hanging after a certain time without any logs
We are currently using Nest.JS as our backend solution for almost 2 years now. It worked pretty fine at all and didn’t gave us any big issues until this last week. As the title describes, it hangs out all on a sudden, without returning us any kind of log. We use it combined with pm2 and it is hosted on a aws t3.medium machine running ubuntu.

We are using the exception filter provided by nest.js in their documentation:

```<code>import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: unknown, host: ArgumentsHost): void {
    // In certain situations `httpAdapter` might not be available in the
    // constructor method, thus we should resolve it here.
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      statusCode: httpStatus,
      timestamp: new Date().toISOString(),
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
    };

    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
  }
}
</code>```

It’s possible to log the reason why the application was shutdown and the specific route that gave us problem? It would be easier to fix that way.

Edit: We also have subscribed to Sentry, but those logs doesn't reach it as well.

Body:
We are currently using Nest.JS as our backend solution for almost 2 years now. It worked pretty fine at all and didn’t gave us any big issues until this last week. As the title describes, it hangs out all on a sudden, without returning us any kind of log. We use it combined with pm2 and it is hosted on a aws t3.medium machine running ubuntu.

We are using the exception filter provided by nest.js in their documentation:

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: unknown, host: ArgumentsHost): void {
    // In certain situations `httpAdapter` might not be available in the
    // constructor method, thus we should resolve it here.
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      statusCode: httpStatus,
      timestamp: new Date().toISOString(),
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
    };

    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
  }
}

It’s possible to log the reason why the application was shutdown and the specific route that gave us problem? It would be easier to fix that way.

Edit: We also have subscribed to Sentry, but those logs doesn't reach it as well.


问:
plotting geom_segment using a functional form for the interpolation using ggplot2
I am trying to plot segments of start->end using ggplot2 with a custom function for the interpolation. I know the functional form of the field and I would like the segments to follow that. I think this simple example will help explain:

library(tibble)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
tibble(
    x = seq(-pi, pi, .01),
    x0 = x*.5,
    x1 = x*1.5,
    random_shift = runif(length(x)),
    y0 = sin(x0) + random_shift,
    y1 = sin(x1) + random_shift
) %>%
    ggplot(aes(x0, y0, xend = x1, yend = y1)) +
    geom_segment()
```

Created on 2023-01-13 with reprex v2.0.2

In this simple case, I am trying to plot the local function for each point (define for a range around it) but geom_segment does linear extrapolation between start and end. I could use geom_curve but then I would need to estimate local curvature (and this will not be very feasible for more complex functions e.g., higher order polynomial, non-linear fields, etc). Alternatively I could use stat_function but it always extrapolates over the x-axis.

Is there a way to define the interpolation using a functional form (e.g. ~f(.x, theta) where theta are local function parameters) for the interpolation? In this case the functional form is the sine function.
Noteworthy, I would like to avoid producing large number of points with small linear interpolations to approximate the functional form.

Body:
I am trying to plot segments of start->end using ggplot2 with a custom function for the interpolation. I know the functional form of the field and I would like the segments to follow that. I think this simple example will help explain:

library(tibble)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
tibble(
    x = seq(-pi, pi, .01),
    x0 = x*.5,
    x1 = x*1.5,
    random_shift = runif(length(x)),
    y0 = sin(x0) + random_shift,
    y1 = sin(x1) + random_shift
) %>%
    ggplot(aes(x0, y0, xend = x1, yend = y1)) +
    geom_segment()

Created on 2023-01-13 with reprex v2.0.2

In this simple case, I am trying to plot the local function for each point (define for a range around it) but geom_segment does linear extrapolation between start and end. I could use geom_curve but then I would need to estimate local curvature (and this will not be very feasible for more complex functions e.g., higher order polynomial, non-linear fields, etc). Alternatively I could use stat_function but it always extrapolates over the x-axis.

Is there a way to define the interpolation using a functional form (e.g. ~f(.x, theta) where theta are local function parameters) for the interpolation? In this case the functional form is the sine function.
Noteworthy, I would like to avoid producing large number of points with small linear interpolations to approximate the functional form.


问:
Is there a way to click on a grid and have it expand larger in material UI
I have multiple grids showing information, but I thought it would be neat to have the end user click on one of the grids and expands it to view larger. Maybe adding a button on each grid to expand it, but is there a way to just click on the grid to maximize and then minimize.

```<code>import React  from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Radio from '@mui/material/Radio';
import Typography from '@mui/material/Typography';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import { TrendLine, Gauge, InfoCard } from '@backstage/core-components';

const PeriodSelector = (children?: React.ReactNode):JSX.Element | null => {
   return (
       <FormControl >
           <FormLabel id="period" title="Trends">Trend Period</FormLabel>
        <RadioGroup
            row
            aria-labelledby="period"
            name="period-radio-buttons-group"
        >
            <FormControlLabel value="today" control={<Radio />} label="today" />
            <FormControlLabel value="week" control={<Radio />} label="week" />
            <FormControlLabel value="month" control={<Radio />} label="month" />
            <FormControlLabel value="year" control={<Radio />} label="year" />
        </RadioGroup>
    </FormControl>
   );
}

// They do not export InfoCard.Props up through the modules.
const StatsInfoCard = (props?:any):JSX.Element | null => {
    return (
        <InfoCard variant={"fullHeight"}  title={props.title} titleTypographyProps={{variant: 'p'}}>
            {props.children}
        </InfoCard>
    );
}

// Again they do not export props from their libraries which is a pain for extensibility and
// typescript safety so I anonymize it.
const StatsTrendCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard title={props.title}>
            <TrendLine
                data={props.data}
                color={props.color}
                title={props.title} >
            </TrendLine>
        </StatsInfoCard>
    );
}

const StatsGaugeCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard title={props.title}>
            <Gauge getColor={ () => { return props.color} } fractional={false} {...props} />
        </StatsInfoCard>
    );
}
const TotalCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard {...props}  >
            <Typography variant="h2" align="center" {...props}>
                {props.value}
            </Typography>
        </StatsInfoCard>
    );
}

export function analysisgrids() {
  return (
      <Box sx={{ flexGrow: 1 }}>
          <Grid container spacing={2}>
              <Grid item xs={12}>
                  <div align="center">
                    <PeriodSelector />
                  </div>
              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="red"
                      title="Average build execution time" />
              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="green"
                      title="Green Builds per day trend" />
              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="black"
                      title="Total Builds per day trend" />

              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="purple"
                      title="Total Active Branches" />
              </Grid>
              <Grid item xs={3}>
                <TotalCard title="Total builds" value="234" color="green" unit="" />
              </Grid>
              <Grid item xs={3}>
                  <TotalCard title="Broken build recover time" value="1" unit="hrs" color="purple"/>
              </Grid>
              <Grid item xs={3}>
                  <StatsGaugeCard title="% failed builds" value="50" color="red"/>
              </Grid>
              <Grid item xs={3}>
                  <TotalCard title="Avg Test Execution time" value="21" unit="minutes" color="blue"/>
              </Grid>
          </Grid>
      </Box>
  );
}

export default {
    title: 'demos/staticanalysis',
    component: analysisgrids,
};
</code>```

I did some digging around material ui page and couldn't find a specific justification on.

Body:
I have multiple grids showing information, but I thought it would be neat to have the end user click on one of the grids and expands it to view larger. Maybe adding a button on each grid to expand it, but is there a way to just click on the grid to maximize and then minimize.

import React  from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Radio from '@mui/material/Radio';
import Typography from '@mui/material/Typography';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import { TrendLine, Gauge, InfoCard } from '@backstage/core-components';

const PeriodSelector = (children?: React.ReactNode):JSX.Element | null => {
   return (
       <FormControl >
           <FormLabel id="period" title="Trends">Trend Period</FormLabel>
        <RadioGroup
            row
            aria-labelledby="period"
            name="period-radio-buttons-group"
        >
            <FormControlLabel value="today" control={<Radio />} label="today" />
            <FormControlLabel value="week" control={<Radio />} label="week" />
            <FormControlLabel value="month" control={<Radio />} label="month" />
            <FormControlLabel value="year" control={<Radio />} label="year" />
        </RadioGroup>
    </FormControl>
   );
}

// They do not export InfoCard.Props up through the modules.
const StatsInfoCard = (props?:any):JSX.Element | null => {
    return (
        <InfoCard variant={"fullHeight"}  title={props.title} titleTypographyProps={{variant: 'p'}}>
            {props.children}
        </InfoCard>
    );
}

// Again they do not export props from their libraries which is a pain for extensibility and
// typescript safety so I anonymize it.
const StatsTrendCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard title={props.title}>
            <TrendLine
                data={props.data}
                color={props.color}
                title={props.title} >
            </TrendLine>
        </StatsInfoCard>
    );
}

const StatsGaugeCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard title={props.title}>
            <Gauge getColor={ () => { return props.color} } fractional={false} {...props} />
        </StatsInfoCard>
    );
}
const TotalCard = (props?:any):JSX.Element | null => {
    return (
        <StatsInfoCard {...props}  >
            <Typography variant="h2" align="center" {...props}>
                {props.value}
            </Typography>
        </StatsInfoCard>
    );
}

export function analysisgrids() {
  return (
      <Box sx={{ flexGrow: 1 }}>
          <Grid container spacing={2}>
              <Grid item xs={12}>

                    <PeriodSelector />

              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="red"
                      title="Average build execution time" />
              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="green"
                      title="Green Builds per day trend" />
              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="black"
                      title="Total Builds per day trend" />

              </Grid>
              <Grid item xs={3}>
                  <StatsTrendCard
                      data={[0.1, 0.5, 0.9, 1.0]}
                      color="purple"
                      title="Total Active Branches" />
              </Grid>
              <Grid item xs={3}>
                <TotalCard title="Total builds" value="234" color="green" unit="" />
              </Grid>
              <Grid item xs={3}>
                  <TotalCard title="Broken build recover time" value="1" unit="hrs" color="purple"/>
              </Grid>
              <Grid item xs={3}>
                  <StatsGaugeCard title="% failed builds" value="50" color="red"/>
              </Grid>
              <Grid item xs={3}>
                  <TotalCard title="Avg Test Execution time" value="21" unit="minutes" color="blue"/>
              </Grid>
          </Grid>
      </Box>
  );
}

export default {
    title: 'demos/staticanalysis',
    component: analysisgrids,
};

I did some digging around material ui page and couldn't find a specific justification on.


问:
Making text linkable via Tampermonkey script
I have written this code for a tampermonkey, got TM to execute the code using mutation observers, but nothing is changing on the page.  the goal is to turn text that passes the regex into a link to a site to lookup that value.

```<code>async function addeelinks(jnode) {
    /* regular expression to find all ee */
    const regex = new RegExp("^S[a-zA-Z0-9]{9}_001_v$")
    /* gets an array of all html elements where ee are known to hang out*/
    var cells = document.getElementsByTagName('td');
    /* steps through all the items in the array looking at each one individually */
    for (var i = 1; 1 > cells.length; i++) {
        /* grabs the contents of the td */
        var cellvalue = cells[i].firstChild.data;
        /* if the contents look like a ee then... */
        if (regex.test(cellvalue)){
            /* wrap the ee in a link to site for the ee */
            cells[i].firstChild.data = "'<a href='https://example.com/search?value='" + cellvalue + "' target='example' >'" + cellvalue + "'</a>'";
        }
    }
}
</code>```

I tried validating my regex with example data, and its solid.  I tried swapping firstChild.data with .innerHTML based on some other question/answers I found on stack exchange, and even found suggestions to use .replace, but hitting a brick wall here.  I'm not very familiar with javascript so I assume I'm making a very basic error.

Body:
I have written this code for a tampermonkey, got TM to execute the code using mutation observers, but nothing is changing on the page.  the goal is to turn text that passes the regex into a link to a site to lookup that value.

async function addeelinks(jnode) {
    /* regular expression to find all ee */
    const regex = new RegExp("^S[a-zA-Z0-9]{9}_001_v$")
    /* gets an array of all html elements where ee are known to hang out*/
    var cells = document.getElementsByTagName('td');
    /* steps through all the items in the array looking at each one individually */
    for (var i = 1; 1 > cells.length; i++) {
        /* grabs the contents of the td */
        var cellvalue = cells[i].firstChild.data;
        /* if the contents look like a ee then... */
        if (regex.test(cellvalue)){
            /* wrap the ee in a link to site for the ee */
            cells[i].firstChild.data = "''" + cellvalue + "''";
        }
    }
}

I tried validating my regex with example data, and its solid.  I tried swapping firstChild.data with .innerHTML based on some other question/answers I found on stack exchange, and even found suggestions to use .replace, but hitting a brick wall here.  I'm not very familiar with javascript so I assume I'm making a very basic error.


问:
Failed implicit conversion from Object<T> to Object<const T>
As practice I tried to make a wrapper around raw pointers to have cleaner memory management when using CUDA. Basically I made a PointerBase template that has a PointerBase specialization for const pointers. This template is the base template for a HostPointer and a DevicePointer template that manage memory on CPU side and GPU side respectively (but this is out of scope of this question). I struggle with the conversion from a PointerBase<T> object into the PointerBase<const T> specialization.

(Keep in mind this is more about practicing C++ templates than production use).

Here is a simple code demonstrating the behavior.

template <typename T>
struct Pointer
{
    T* ptr_;

    Pointer() = default;
    Pointer<T>& operator=(const Pointer<T>& other) = default;

    operator Pointer<const T>() const { return Pointer<const T>(ptr_); }

    T* get() const { return ptr_; }
};

template <typename T>
struct Pointer<const T>
{
    const T* ptr_;

    Pointer() = default;
    Pointer<const T>& operator=(const Pointer<const T>& other) = default;

    const T* get() const { return ptr_; }
};

template <typename T>
T dereference(Pointer<const T> data)
{
    return *data.get();
}

int main()
{
    int value = 7.0;
    Pointer<int> ptr{&value};
    //int tmp3 = dereference(ptr); // not compiling
    int tmp4 = dereference(Pointer<const int>(ptr)); // compiling

    return 0;
}
```
<p>This code fails to compile with the following error (gcc 8.4.0 on ubuntu 20.4, with c++14 standard)</p>
<pre class="lang-cpp prettyprint-override"><code>main.cpp: In function ‘int main()’:
main.cpp:41:31: error: no matching function for call to ‘dereference(Pointer<int>&)’
     int tmp3 = dereference(ptr); // not compiling
                               ^
main.cpp:32:3: note: candidate: ‘template<class T> T dereference(Pointer<const T>)’
 T dereference(Pointer<const T> data)
   ^~~~~~~~~~~
main.cpp:32:3: note:   template argument deduction/substitution failed:
main.cpp:41:31: note:   types ‘const T’ and ‘int’ have incompatible cv-qualifiers
     int tmp3 = dereference(ptr); // not compiling
                               ^
</code>```

Why is the conversion operator not considered for calling the dereference function ?

I feel there is a connection to the fact that the Pointer<const T> type is a specialization of the Pointer template. But I still don't understand why a conversion is not happening.

I get the same result when defining a constructor in Pointer<const T> taking a Pointer<T> as a parameter.

Any help ?

PS : Interestingly, I get the same behavior with std::shared_ptr.

#include <memory>

template <typename T>
T dereference(std::shared_ptr<const T> data)
{
    return *data.get();
}

int main()
{
    std::shared_ptr<int> sptr(new int[10]);
    int tmp1 = dereference(sptr); // not compiling
    //int tmp2 = dereference(std::shared_ptr<const int>(sptr)); //compiling

    return 0;
}
```
<pre class="lang-cpp prettyprint-override"><code>main.cpp: In function ‘int main()’:
main.cpp:9:32: error: no matching function for call to ‘dereference(std::shared_ptr<int>&)’
     int tmp1 = dereference(sptr); // not compiling
                                ^
main.cpp:4:3: note: candidate: ‘template<class T> T dereference(std::shared_ptr<const _Tp>)’
 T dereference(std::shared_ptr<const T> data) { return *data.get(); }
   ^~~~~~~~~~~
main.cpp:4:3: note:   template argument deduction/substitution failed:
main.cpp:9:32: note:   types ‘const _Tp’ and ‘int’ have incompatible cv-qualifiers
     int tmp1 = dereference(sptr); // not compiling
                                ^
</code>```

Body:
As practice I tried to make a wrapper around raw pointers to have cleaner memory management when using CUDA. Basically I made a PointerBase template that has a PointerBase specialization for const pointers. This template is the base template for a HostPointer and a DevicePointer template that manage memory on CPU side and GPU side respectively (but this is out of scope of this question). I struggle with the conversion from a PointerBase<T> object into the PointerBase<const T> specialization.

(Keep in mind this is more about practicing C++ templates than production use).

Here is a simple code demonstrating the behavior.

template <typename T>
struct Pointer
{
    T* ptr_;

    Pointer() = default;
    Pointer<T>& operator=(const Pointer<T>& other) = default;

    operator Pointer<const T>() const { return Pointer<const T>(ptr_); }

    T* get() const { return ptr_; }
};

template <typename T>
struct Pointer<const T>
{
    const T* ptr_;

    Pointer() = default;
    Pointer<const T>& operator=(const Pointer<const T>& other) = default;

    const T* get() const { return ptr_; }
};

template <typename T>
T dereference(Pointer<const T> data)
{
    return *data.get();
}

int main()
{
    int value = 7.0;
    Pointer<int> ptr{&value};
    //int tmp3 = dereference(ptr); // not compiling
    int tmp4 = dereference(Pointer<const int>(ptr)); // compiling

    return 0;
}

This code fails to compile with the following error (gcc 8.4.0 on ubuntu 20.4, with c++14 standard)

main.cpp: In function ‘int main()’:
main.cpp:41:31: error: no matching function for call to ‘dereference(Pointer<int>&)’
     int tmp3 = dereference(ptr); // not compiling
                               ^
main.cpp:32:3: note: candidate: ‘template<class T> T dereference(Pointer<const T>)’
 T dereference(Pointer<const T> data)
   ^~~~~~~~~~~
main.cpp:32:3: note:   template argument deduction/substitution failed:
main.cpp:41:31: note:   types ‘const T’ and ‘int’ have incompatible cv-qualifiers
     int tmp3 = dereference(ptr); // not compiling
                               ^

Why is the conversion operator not considered for calling the dereference function ?

I feel there is a connection to the fact that the Pointer<const T> type is a specialization of the Pointer template. But I still don't understand why a conversion is not happening.

I get the same result when defining a constructor in Pointer<const T> taking a Pointer<T> as a parameter.

Any help ?

PS : Interestingly, I get the same behavior with std::shared_ptr.

#include <memory>

template <typename T>
T dereference(std::shared_ptr<const T> data)
{
    return *data.get();
}

int main()
{
    std::shared_ptr<int> sptr(new int[10]);
    int tmp1 = dereference(sptr); // not compiling
    //int tmp2 = dereference(std::shared_ptr<const int>(sptr)); //compiling

    return 0;
}

main.cpp: In function ‘int main()’:
main.cpp:9:32: error: no matching function for call to ‘dereference(std::shared_ptr<int>&)’
     int tmp1 = dereference(sptr); // not compiling
                                ^
main.cpp:4:3: note: candidate: ‘template<class T> T dereference(std::shared_ptr<const _Tp>)’
 T dereference(std::shared_ptr<const T> data) { return *data.get(); }
   ^~~~~~~~~~~
main.cpp:4:3: note:   template argument deduction/substitution failed:
main.cpp:9:32: note:   types ‘const _Tp’ and ‘int’ have incompatible cv-qualifiers
     int tmp1 = dereference(sptr); // not compiling
                                ^


问:
Adding borders in word with Range.Paste Method
I have been looking to add borders to a word table that I am copying from an excel file. Below is the code that I am using-
I am looking to add borders to this table in the same subroutine, can anyone please help me with this. Thanks

Dim ObjWord As Object
Dim ws As Worksheet

Set ObjWord = CreateObject("Word.Application")
ObjWord.Visible = True
Dim docWord As Object
Dim oCC As ContentControl
ObjWord.Activate

Set docWord = ObjWord.Documents.Open(Filename:="\\\CPFSPRDAPAWSE01\userdata$\NTiwari\Desktop\Automations\abc Memo.docx", ReadOnly:=False)
docWord.Activate
For Each oCC In ActiveDocument.ContentControls

        Select Case oCC.Title
            Case "IssuerName" 'This is the Title being referenced for CC in Word
                oCC.Range.Text = "abc" & Right(xyz, 3) & " pqr" 'This is the named cell being referenced in excel
            Case "CommitteeType"
                     oCC.LockContents = False
                     oCC.DropdownListEntries(2).Select
                     oCC.LockContents = True
            Case "CommitteeDate"
                    oCC.Range.Text = Date
            Case "Methodology"
                oCC.Range.Text = "fgs"
            Case "Methodology2"
                oCC.Range.Text = "NA"
            Case "ESGYesNo"
                oCC.DropdownListEntries(1).Select
            Case "ESGComments"
                oCC.DropdownListEntries(1).Select
            Case "FinancialObsYesNo"
                oCC.DropdownListEntries(1).Select
             Case "ContractualPayObsYesNo"
                oCC.DropdownListEntries(1).Select
            Case "DataChecksYesNo"
                oCC.DropdownListEntries(1).Select
            Case "DataCheckResult"
                oCC.DropdownListEntries(1).Select
            Case "FinancialObsYesNo"
                oCC.DropdownListEntries(1).Select
             Case "RatingAction"
                oCC.DropdownListEntries(2).Select
             Case "BasisForAction"
                oCC.Range.Text = "text"

         End Select
    Next oCC

ThisWorkbook.Sheets("Participants - C").Range("C7:D13").Copy
docWord.Bookmarks("TransParties").Range.Paste
docWord.SaveAs "\\CPFSPRDAPAWSE01\userdata$\NTiwari\Desktop\Automations\abc Docs\" & "DealName " & " abc Memo.docx"

docWord.Close

End Sub
```


问:
addEventListener to an element gets removed
I have an ASP.net webForms, using .NET 4.7.2 TreeView.

I'm using the TreeView component to render a webpage.  this renders the tree as a series of tables for node labels and div elements containing child nodes.

I'm trying to add a click event to the node, which is an  element located in the table.
The TreeNode has been overriden, to make use of RenderPreText, which adds an attribute role="treeitem" to each of these node's label.

ie

```<code>protected override void RenderPreText(HtmlTextWriter writer) {
   writer.AddAttribute("role", "treeitem");
}
</code>```

The following code is what I'm using to add the click event to each node's label element:

```<code>window.addEventListener("load", (event) =>    {
   var treeItems = document.querySelectorAll('[role="treeitem"]');
      for (var i = 0; i < treeItems.length; i++)
      {
         treeItems[i].addEventListener('click', OnNodeSelect);
      }
   });
function OnNodeSelect(event)  { alert('Node Selected'); }
</code>```

The issue i'm having, is that when the node is selected, the event fires and is then removed, so can only be clicked a single time.

What am I doing wrong, how do I add an event that doesn't get removed after single activation?

Body:
I have an ASP.net webForms, using .NET 4.7.2 TreeView.

I'm using the TreeView component to render a webpage.  this renders the tree as a series of tables for node labels and div elements containing child nodes.

I'm trying to add a click event to the node, which is an  element located in the table.
The TreeNode has been overriden, to make use of RenderPreText, which adds an attribute role="treeitem" to each of these node's label.

ie

protected override void RenderPreText(HtmlTextWriter writer) {
   writer.AddAttribute("role", "treeitem");
}

The following code is what I'm using to add the click event to each node's label element:

window.addEventListener("load", (event) =>    {
   var treeItems = document.querySelectorAll('[role="treeitem"]');
      for (var i = 0; i < treeItems.length; i++)
      {
         treeItems[i].addEventListener('click', OnNodeSelect);
      }
   });
function OnNodeSelect(event)  { alert('Node Selected'); }

The issue i'm having, is that when the node is selected, the event fires and is then removed, so can only be clicked a single time.

What am I doing wrong, how do I add an event that doesn't get removed after single activation?


问:
Invoke function still trow an exception for cross thread operation
I find a simple example for collecting information from an industrial equipment via MTConnect standard and adapted to my equipment. The example received periodically, via network, a variable lenght text buffer and display in a listbox. I modify the original code to display meaningfull information by searching and parsing the received buffer to be display in textbox and progress bar.The receiving function, running on an event, is the following:

```<code>public void OnRecievedData( IAsyncResult ar )
{
    Socket sock = (Socket)ar.AsyncState;

    // Check if any data was received
    try
    {
        int nBytesRec = sock.EndReceive( ar );
        if( nBytesRec > 0 )
        {
            // Add the data to the List
            string sRecieved = Encoding.ASCII.GetString( m_byBuff, 0, nBytesRec );
                    //sRecieved = Encoding.ASCII.GetString(m_byBuff, 0, nBytesRec);

                    // WARNING : The following line is NOT thread safe. Invoke is
                    // m_lbRecievedData.Items.Add( sRecieved );
                    //Invoke( m_AddMessage, new string [] { sRecieved } );
                    Invoke(myDelegate, sRecieved);
                    // If the connection is still usable restablish the callback
                    SetupRecieveCallback( sock );
        }
        else
        {
            // If no data was recieved then the connection is probably dead
            Console.WriteLine( "Client {0}, disconnected", sock.RemoteEndPoint );
            sock.Shutdown( SocketShutdown.Both );
            sock.Close();
        }
    }
    catch( Exception ex )
    {
        MessageBox.Show( this, ex.Message, "Unknown error on Recieve!" );
    }
}

</code>```

m_AddMessage process the RX buffer and fill in the most simpler example just m_lbRecieveData list box while in my code the buffer is first parse then the interesting data display in variuos text box.

As seen in commented lines, I try to use Invoke directly on m_AddMessage function then in the latest try using a delegate. The code run correctly for a variable length of time then trow an exception :

Cross-thread operation not valid: FormMain accessed from a thread
other than the thread it was created on

No helpfull information on which thread raised the exception are available. I search any info related to the problem (include this forum) and follow several example on using Invoke but I always obtain the same result. I really appreciate any help on resolving this issue

Body:
I find a simple example for collecting information from an industrial equipment via MTConnect standard and adapted to my equipment. The example received periodically, via network, a variable lenght text buffer and display in a listbox. I modify the original code to display meaningfull information by searching and parsing the received buffer to be display in textbox and progress bar.The receiving function, running on an event, is the following:

public void OnRecievedData( IAsyncResult ar )
{
    Socket sock = (Socket)ar.AsyncState;

    // Check if any data was received
    try
    {
        int nBytesRec = sock.EndReceive( ar );
        if( nBytesRec > 0 )
        {
            // Add the data to the List
            string sRecieved = Encoding.ASCII.GetString( m_byBuff, 0, nBytesRec );
                    //sRecieved = Encoding.ASCII.GetString(m_byBuff, 0, nBytesRec);

                    // WARNING : The following line is NOT thread safe. Invoke is
                    // m_lbRecievedData.Items.Add( sRecieved );
                    //Invoke( m_AddMessage, new string [] { sRecieved } );
                    Invoke(myDelegate, sRecieved);
                    // If the connection is still usable restablish the callback
                    SetupRecieveCallback( sock );
        }
        else
        {
            // If no data was recieved then the connection is probably dead
            Console.WriteLine( "Client {0}, disconnected", sock.RemoteEndPoint );
            sock.Shutdown( SocketShutdown.Both );
            sock.Close();
        }
    }
    catch( Exception ex )
    {
        MessageBox.Show( this, ex.Message, "Unknown error on Recieve!" );
    }
}

m_AddMessage process the RX buffer and fill in the most simpler example just m_lbRecieveData list box while in my code the buffer is first parse then the interesting data display in variuos text box.

As seen in commented lines, I try to use Invoke directly on m_AddMessage function then in the latest try using a delegate. The code run correctly for a variable length of time then trow an exception :

Cross-thread operation not valid: FormMain accessed from a thread
other than the thread it was created on

No helpfull information on which thread raised the exception are available. I search any info related to the problem (include this forum) and follow several example on using Invoke but I always obtain the same result. I really appreciate any help on resolving this issue


问:
Using OpenCSV I can't read first column
I have a problem reading CSV

Dear everybody

I have a CSV with following format in SFTP

Date;Risk 11/01/2020;C4 12/01/2020;C4

I am using Intellij but when I download with java code this File I don't know why receive this content:

Date;Risk 11/01/2020;C4;0,22;N;O;178 12/01/2020;C4;0,22;N;O;178

I think thas is problem for my Intellij when I download file but I don't have any idea why this happened.

I use OpenCSV with version 5.3

```<code>List<FieldsCSV> listFieldsCSV = new CsvToBeanBuilder<FieldsCSV>(inStrReader)
        .withType(FieldsCSV.class)
        .withSeparator(Constants.SEPARATOR_FIELDS)
        .withIgnoreQuotations(true)
        .withSkipLines(1).build()
        .parse();
</code>```

Title: Using OpenCSV I can't read first column

Body:
I have a problem reading CSV

Dear everybody

I have a CSV with following format in SFTP

Date;Risk 11/01/2020;C4 12/01/2020;C4

I am using Intellij but when I download with java code this File I don't know why receive this content:

Date;Risk 11/01/2020;C4;0,22;N;O;178 12/01/2020;C4;0,22;N;O;178

I think thas is problem for my Intellij when I download file but I don't have any idea why this happened.

I use OpenCSV with version 5.3

List<FieldsCSV> listFieldsCSV = new CsvToBeanBuilder<FieldsCSV>(inStrReader)
        .withType(FieldsCSV.class)
        .withSeparator(Constants.SEPARATOR_FIELDS)
        .withIgnoreQuotations(true)
        .withSkipLines(1).build()
        .parse();


问:
The animation of switching between Activities does not work if the Activity has the "taskAffinity =""" parameter or before Picture in Picture
After I had the need to move the Activity to a separate process using " taskAffinity="" ", the transition animations that I specified in the style stopped working. I tried using overridePendingTransition and ActivityOptions.makeCustomAnimation but that didn't help. Also, the animations I set in code with overridePendingTransition don't work after I switch to Picture In Picture mode and then back again. As far as I understand, the point is that the animations do not work when switching between different processes, but it seems to me that there must be some way to do this. I will be very grateful if someone knows how to implement the animation when moving between aActivity , when they have different process.

Manifest my Activity:

```<code><activity
      android:name=".modules.media.video.player.VideoPlayerActivity"
      android:configChanges="screenSize|smallestScreenSize|screenLayout"
      android:exported="false"
      android:launchMode="singleTask"
      android:resizeableActivity="true"
      android:taskAffinity =""
      android:supportsPictureInPicture="true"
      android:theme="@style/VideoPlayerTheme"
      tools:targetApi="n">
</code>```

Body:
After I had the need to move the Activity to a separate process using " taskAffinity="" ", the transition animations that I specified in the style stopped working. I tried using overridePendingTransition and ActivityOptions.makeCustomAnimation but that didn't help. Also, the animations I set in code with overridePendingTransition don't work after I switch to Picture In Picture mode and then back again. As far as I understand, the point is that the animations do not work when switching between different processes, but it seems to me that there must be some way to do this. I will be very grateful if someone knows how to implement the animation when moving between aActivity , when they have different process.

Manifest my Activity:

<activity
      android:name=".modules.media.video.player.VideoPlayerActivity"
      android:configChanges="screenSize|smallestScreenSize|screenLayout"
      android:exported="false"
      android:launchMode="singleTask"
      android:resizeableActivity="true"
      android:taskAffinity =""
      android:supportsPictureInPicture="true"
      android:theme="@style/VideoPlayerTheme"
      tools:targetApi="n">


问:
Disable new "Diff view" IntelliCode suggestions?
After updating Visual Studio 2022 there seem to be a new style of IntelliCode that Peter Groenewegen referees to on twitter.
I find it very intrusive and want to get rid of it but cant seem to find a setting.
Am I missing something or is it one more of the new bloats in VS that you can't get rid of unless you kill the whole feature?

I'm really trying to like intelicode but it is slow and often suggest garbage so it is hard for me to like it. And now this.

VS staring to look like a three year old kid with crayons went over it and I would like to tone it down but not kill the features unless there is absolutely no other way.

Does anyone know if there is a setting somewhere?

Update: The settings (or it is just my settings) has ben largely removed so I don't have a lot of options to try.

Images of all my settings


问:
Auto.arima modeled on multiple data points
I am trying to run auto.arima on a dataset containing thousands of rows. In the dataset there are hundreds of unique domains, i'd like auto.arima to run on each domain individually and return the forecast results in a data.frame.

Here's an example of the dataset:

```<code>| Date     |   Domain       | Impressions |
| -------- | -------------- | ---------   |
| 1/13/2023| red.com        | 957         |
| 1/14/2023| red.com        | 1015        |
| 1/13/2023| blue.com       | 800         |
| 1/14/2023| blue.com       | 936         |
| 1/13/2023| pink.com       | 970         |
| 1/14/2023| pink.com       | 712         |

these_domains <- test$domain %>% unique()
yup_rate_delivery <- these_domains %>%
  map(function(this_domain){
    test <- test %>% filter(domain == this_domain)
    {rate <- ts(test[,'net_cpm'],start =c(2021,11), frequency = 12)
      autoplot(rate) +ggtitle("net_cpm_rate") + ylab("rate")
      fit_ARIMA <- auto.arima(net_cpm, seasonal = TRUE)}
  }) %>% set_names(these_domains)
</code>```

I have tried auto.arima as part of a map function but it just returns the results in a list that can't be converted into a data frame. I also don't think it ran correctly as i can't seem to see the forecast when i view the list.

Body:
I am trying to run auto.arima on a dataset containing thousands of rows. In the dataset there are hundreds of unique domains, i'd like auto.arima to run on each domain individually and return the forecast results in a data.frame.

Here's an example of the dataset:

| Date     |   Domain       | Impressions |
| -------- | -------------- | ---------   |
| 1/13/2023| red.com        | 957         |
| 1/14/2023| red.com        | 1015        |
| 1/13/2023| blue.com       | 800         |
| 1/14/2023| blue.com       | 936         |
| 1/13/2023| pink.com       | 970         |
| 1/14/2023| pink.com       | 712         |

these_domains <- test$domain %>% unique()
yup_rate_delivery <- these_domains %>%
  map(function(this_domain){
    test <- test %>% filter(domain == this_domain)
    {rate <- ts(test[,'net_cpm'],start =c(2021,11), frequency = 12)
      autoplot(rate) +ggtitle("net_cpm_rate") + ylab("rate")
      fit_ARIMA <- auto.arima(net_cpm, seasonal = TRUE)}
  }) %>% set_names(these_domains)

I have tried auto.arima as part of a map function but it just returns the results in a list that can't be converted into a data frame. I also don't think it ran correctly as i can't seem to see the forecast when i view the list.


问:
expo-av not displaying livestream
I am using expo-av video to display livestream on webpage but does not work . I have used the template code provided by the docs but changed uri to youtube livestream . any help to get this to work?

```<code>import React from 'react';
import { View,SafeAreaView, StyleSheet, Button } from 'react-native';
import { Video} from 'expo-av';

export default function App() {

  const video = React.useRef(null);
  const [status, setStatus] = React.useState({});

  return(
    <SafeAreaView style={styles.container}>
    <Video
        ref={video}
        style={{ width: 500, height: 500 }}
        source={{
          uri: 'https://www.youtube.com/watch?v=GEumHK0hfdo',
        }}
        useNativeControls
        resizeMode="contain"
        isLooping
        onPlaybackStatusUpdate={status => setStatus(() => status)}
      />
      <View style={styles.buttons}>
        <Button
          title={status.isPlaying ? 'Pause' : 'Play'}
          onPress={() =>
            status.isPlaying ? video.current.pauseAsync() : video.current.playAsync()
          }
        />
        </View>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

expecting stream to be shwown

Title: expo-av not displaying livestream

Body:
I am using expo-av video to display livestream on webpage but does not work . I have used the template code provided by the docs but changed uri to youtube livestream . any help to get this to work?

import React from 'react';
import { View,SafeAreaView, StyleSheet, Button } from 'react-native';
import { Video} from 'expo-av';

export default function App() {

  const video = React.useRef(null);
  const [status, setStatus] = React.useState({});

  return(
    <SafeAreaView style={styles.container}>
    <Video
        ref={video}
        style={{ width: 500, height: 500 }}
        source={{
          uri: 'https://www.youtube.com/watch?v=GEumHK0hfdo',
        }}
        useNativeControls
        resizeMode="contain"
        isLooping
        onPlaybackStatusUpdate={status => setStatus(() => status)}
      />
      <View style={styles.buttons}>
        <Button
          title={status.isPlaying ? 'Pause' : 'Play'}
          onPress={() =>
            status.isPlaying ? video.current.pauseAsync() : video.current.playAsync()
          }
        />
        </View>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

expecting stream to be shwown


问:
C# Postgresql returning max connections using UnitOfWork - AWS Lambda
Im using UnitOfWork pattern to manage the connections to a postgresql database. When I run my e2e tests, the connections rise up and stay idle, though I close them everytime I open them. I already set the property "Pooling=False" in the connection string, but it didn't helped. It can reach over 70 connections idle. This happens in my AWS Lambda Functions.</p>


问:
Training internet data as a dataset to Model
How do I train AI model through the data available in the internet in python ?

I need to know how arrange the data and train the model


问:
Error in .local(x, y, ...) : extents do not overlap moveVis
After I run the frames_spatial command, I get the following error
"Error in .local(x, y, ...) : extents do not overlap"

I'm not sure what is going on since the code above it seems to run with no issues.

Also, I am trying to find code to uniquely color code individuals but I am trying to find a way to color code by species instead of individual. I have created two columns in my dataframe. One column is titled 'species' and the other is titled 'colour' which is the color I want the species to be coded with.

I have looked at previous questions on Stackoverflow and looked at the the GitHub page.

```<code>library(moveVis)
library(move)
library(magrittr)
library(lubridate)

palmertest1 <- read.csv("palmertest1.csv", stringsAsFactors = F)
palmertest1$time <- as.POSIXct(palmertest1$time, format="%Y-%m-%d %H:%M:%S", tz="UTC")

m.move <- df2move(palmertest1,
        proj = "+init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0",
        x = "coords.x1", y = "coords.x2", time = "timestamps", track_id = "trackId")

m.move <- m.move[[sapply(split(m.move), length) > 1]]

res <- m.move %>%
  timeLag(units = "secs") %>%
  sapply(function(x) (median(x)/60)/60) %>%
  median() %>%
  round()

m <- align_move(m = m.move, res = res, unit = "hours")

n <- n.indiv(m)
color = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
unique.colors <- sample(color, n)
pie(rep(1,n), col=unique.colors)

frames <- frames_spatial(m, path_colours = unique.colors, map_service = "osm", map_type = "streets", alpha = 0.5,
                         path_legend = F) %>%
  add_labels(x = "Longitude", y = "Latitude") %>% # add some customizations, such as axis labels
  add_northarrow() %>%
  add_scalebar() %>%
  add_timestamps(m, type = "label") %>%
  add_progress()

</code>```

Body:
After I run the frames_spatial command, I get the following error
"Error in .local(x, y, ...) : extents do not overlap"

I'm not sure what is going on since the code above it seems to run with no issues.

Also, I am trying to find code to uniquely color code individuals but I am trying to find a way to color code by species instead of individual. I have created two columns in my dataframe. One column is titled 'species' and the other is titled 'colour' which is the color I want the species to be coded with.

I have looked at previous questions on Stackoverflow and looked at the the GitHub page.

library(moveVis)
library(move)
library(magrittr)
library(lubridate)

palmertest1 <- read.csv("palmertest1.csv", stringsAsFactors = F)
palmertest1$time <- as.POSIXct(palmertest1$time, format="%Y-%m-%d %H:%M:%S", tz="UTC")

m.move <- df2move(palmertest1,
        proj = "+init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0",
        x = "coords.x1", y = "coords.x2", time = "timestamps", track_id = "trackId")

m.move <- m.move[[sapply(split(m.move), length) > 1]]

res <- m.move %>%
  timeLag(units = "secs") %>%
  sapply(function(x) (median(x)/60)/60) %>%
  median() %>%
  round()

m <- align_move(m = m.move, res = res, unit = "hours")

n <- n.indiv(m)
color = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
unique.colors <- sample(color, n)
pie(rep(1,n), col=unique.colors)

frames <- frames_spatial(m, path_colours = unique.colors, map_service = "osm", map_type = "streets", alpha = 0.5,
                         path_legend = F) %>%
  add_labels(x = "Longitude", y = "Latitude") %>% # add some customizations, such as axis labels
  add_northarrow() %>%
  add_scalebar() %>%
  add_timestamps(m, type = "label") %>%
  add_progress()