问:
How can I run reghdfe with concatenation with many features from Stata in Python?
I want to translate this Stata code into Python :

```<code>reghdfe ever_delinq fintech i.loanpurp fico ltv dti fico_miss ltv_miss dti_miss ln_loanamt nr_borrowers intrate ///
if sample, absorb(firstpmtdt#statenr) vce(clu issuerid)
</code>```

However, when trying to run OLS model running the following lines of code:

```<code>formula = 'ever_delinq ~ fintech + C(loan_purpose) + credit_score + loan_to_value + total_dept + original_principal_balance + number_of_borrowers + property_type + down_payment_assistance'

model = smf.ols(formula, df).fit()
</code>```

I get the following error message :

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/statsmodels/base/model.py", line 200, in from_formula
    tmp = handle_formula_data(data, None, formula, depth=eval_env,
  File "/usr/local/lib/python3.8/dist-packages/statsmodels/formula/formulatools.py", line 63, in handle_formula_data
    result = dmatrices(formula, Y, depth, return_type='dataframe',
  File "/usr/local/lib/python3.8/dist-packages/patsy/highlevel.py", line 309, in dmatrices
    (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
  File "/usr/local/lib/python3.8/dist-packages/patsy/highlevel.py", line 167, in _do_highlevel_design
    return build_design_matrices(design_infos, data,
  File "/usr/local/lib/python3.8/dist-packages/patsy/build.py", line 931, in build_design_matrices
    results.append(_build_design_matrix(design_info,
  File "/usr/local/lib/python3.8/dist-packages/patsy/build.py", line 762, in _build_design_matrix
    m = DesignMatrix(np.empty(shape, dtype=dtype), design_info)
numpy.core._exceptions.MemoryError: Unable to allocate 462. GiB for an array with shape (4097569, 15140) and data type float64

</code>```

I tried to run Lasso on my columns in order to reduce the size and then re run the OLS model however, it still doesn't work.

Body:
I want to translate this Stata code into Python :

reghdfe ever_delinq fintech i.loanpurp fico ltv dti fico_miss ltv_miss dti_miss ln_loanamt nr_borrowers intrate ///
if sample, absorb(firstpmtdt#statenr) vce(clu issuerid)

However, when trying to run OLS model running the following lines of code:

formula = 'ever_delinq ~ fintech + C(loan_purpose) + credit_score + loan_to_value + total_dept + original_principal_balance + number_of_borrowers + property_type + down_payment_assistance'

model = smf.ols(formula, df).fit()

I get the following error message :

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/statsmodels/base/model.py", line 200, in from_formula
    tmp = handle_formula_data(data, None, formula, depth=eval_env,
  File "/usr/local/lib/python3.8/dist-packages/statsmodels/formula/formulatools.py", line 63, in handle_formula_data
    result = dmatrices(formula, Y, depth, return_type='dataframe',
  File "/usr/local/lib/python3.8/dist-packages/patsy/highlevel.py", line 309, in dmatrices
    (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
  File "/usr/local/lib/python3.8/dist-packages/patsy/highlevel.py", line 167, in _do_highlevel_design
    return build_design_matrices(design_infos, data,
  File "/usr/local/lib/python3.8/dist-packages/patsy/build.py", line 931, in build_design_matrices
    results.append(_build_design_matrix(design_info,
  File "/usr/local/lib/python3.8/dist-packages/patsy/build.py", line 762, in _build_design_matrix
    m = DesignMatrix(np.empty(shape, dtype=dtype), design_info)
numpy.core._exceptions.MemoryError: Unable to allocate 462. GiB for an array with shape (4097569, 15140) and data type float64

I tried to run Lasso on my columns in order to reduce the size and then re run the OLS model however, it still doesn't work.


来源: stackexchange

问:
Unit test - Object reference not set to an instance of an object
So, I'm working on some unit tests, and don't understand why this is happening...

That's the method I am trying to test:

```<code>public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
        {
            var products = _repository.GetAllProducts().ToList();

            List<Produtos> produtos = new List<Produtos>();

            products.ForEach(produto =>
                {
                    if (produto.Nome.Contains(term))
                    {
                        produtos.Add(produto);
                    }
                }
            );

            if (!(produtos.Count > 0))
            {
                throw new Exception();
            }

            return produtos.Skip((page - 1) * pageSize).Take(pageSize);
        }
</code>```

That is the Test Class I wrote:

```<code>[TestClass]
    public class ProductTests
    {
        private readonly ProductsService _service;

        public ProductTests()
        {
            _service = new ProductsService();
        }
        [TestMethod]
        public void GetAll_RequestProducts_ReturnsProduts()
        {
            var result = _service.GetAll("camisa", 1, 1);

            Assert.IsNotNull(result);
        }
    }
</code>```

and those are the results:

ContentLicense: CC BY-SA 4.0

Body:
So, I'm working on some unit tests, and don't understand why this is happening...

That's the method I am trying to test:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
        {
            var products = _repository.GetAllProducts().ToList();

            List<Produtos> produtos = new List<Produtos>();

            products.ForEach(produto =>
                {
                    if (produto.Nome.Contains(term))
                    {
                        produtos.Add(produto);
                    }
                }
            );

            if (!(produtos.Count > 0))
            {
                throw new Exception();
            }

            return produtos.Skip((page - 1) * pageSize).Take(pageSize);
        }

That is the Test Class I wrote:

[TestClass]
    public class ProductTests
    {
        private readonly ProductsService _service;

        public ProductTests()
        {
            _service = new ProductsService();
        }
        [TestMethod]
        public void GetAll_RequestProducts_ReturnsProduts()
        {
            var result = _service.GetAll("camisa", 1, 1);

            Assert.IsNotNull(result);
        }
    }

and those are the results:


问:
I can't see the data saved on database table when running php artisan test
This is Laravel 7, I have this phpunit.xml

```<code><server name="APP_ENV" value="testing"/>
<server name="APP_IMAGES_PATH" value=""/>
<server name="FILESYSTEM_DRIVER" value="tests"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="LOG_CHANNEL" value="tests"/>
<server name="DB_CONNECTION" value="test_db"/>
<server name="DB_DATABASE" value="test_db"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="redis"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</code>```

and my .env

```<code>TEST_DB_CONNECTION=pgsql
TEST_DB_HOST=127.0.0.1
TEST_DB_PORT=5432
TEST_DB_DATABASE=test_db
TEST_DB_USERNAME=laravel
TEST_DB_PASSWORD=password

APP_ENV=testing
</code>```

but when this code

```<code>$item = new OrderData;
$item->integration = 'integration';
$item->external_reference = $this->xml_contents["order"]["order_id"];
$item->order_id = $this->xml_contents["order"]["order_id"];
$item->save();
</code>```

was executed when running

```<code>php artisan test
</code>```

I can't see it was save in database table order_data but on the next line

```<code>$orderData = OrderData::query()->where('external_reference', $orderId)->first();
</code>```

$orderData contains data.

Why is that?

Body:
This is Laravel 7, I have this phpunit.xml

<server name="APP_ENV" value="testing"/>
<server name="APP_IMAGES_PATH" value=""/>
<server name="FILESYSTEM_DRIVER" value="tests"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="LOG_CHANNEL" value="tests"/>
<server name="DB_CONNECTION" value="test_db"/>
<server name="DB_DATABASE" value="test_db"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="redis"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>

and my .env

TEST_DB_CONNECTION=pgsql
TEST_DB_HOST=127.0.0.1
TEST_DB_PORT=5432
TEST_DB_DATABASE=test_db
TEST_DB_USERNAME=laravel
TEST_DB_PASSWORD=password

APP_ENV=testing

but when this code

$item = new OrderData;
$item->integration = 'integration';
$item->external_reference = $this->xml_contents["order"]["order_id"];
$item->order_id = $this->xml_contents["order"]["order_id"];
$item->save();

was executed when running

php artisan test

I can't see it was save in database table order_data but on the next line

$orderData = OrderData::query()->where('external_reference', $orderId)->first();

$orderData contains data.

Why is that?


问:
Setting different properties in E2E tests causes ResourceAccessException when running with maven
I have added a feature flag to my project in the form of an environment variable FEATURE_FLAG_FOO.
Now I need to integrate the feature flag into my tests. Every E2E test needs the feature flag set to some value. Most of them are not affected, so for them I just set it to true:

```<code>@SpringBootTest(classes = MyApp.class,
                webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
                properties = { "FEATURE_FLAG_FOO=true" })
public class UnrelatedE2ETest {
</code>```

But for the tests that are affected, I want to test both values. So duplicate them and set the feature flag to false in the original and to true in the duplicate. I end up with both, tests that have FEATURE_FLAG_FOO set to true and tests that have it set to false.

Now if I set FEATURE_FLAG_FOO to the same value for all tests, all tests pass. If I use different values the tests still pass as long as I execute them via IntelliJ run all tests or if I execute them with maven but isolated (mvn test -Dtest=SingleE2ETest). But when I run all of them with mvn test I run into problems.

Many tests, even unrelated ones get Unexpected status code,  expected:<200> but was:<500> so something goes wrong internally and that happens only because the tests run together.

For one such unrelated test the stacktrace is:

```<code>java.net.ConnectException: Connection refused: connect
    at sun.nio.ch.Net.connect0(Net.java)
    at sun.nio.ch.Net.connect(Net.java:579)
    at sun.nio.ch.Net.connect(Net.java:568)
    at sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
    at java.net.Socket.connect(Socket.java:633)
    at java.net.Socket.connect(Socket.java:583)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:183)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:498)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:603)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:246)
    at sun.net.www.http.HttpClient.New(HttpClient.java:351)
    at sun.net.www.http.HttpClient.New(HttpClient.java:373)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1309)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1242)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1128)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1057)
    at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:109)
    ... 7 frames truncated
    ... 270 common frames omitted
Wrapped by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for \"http://0.0.0.0:55760/api/v1/unrelatedendpoint\": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:631)
[...]
</code>```

http://0.0.0.0:55760/api/v1/unrelatedendpoint is a mock (autowired and stubbed with Wiremock) that the E2E test calls. So I assume that this mock is blocked, maybe due to a race condition? However upon running the tests several times it is always the same tests that fail in the same order. I can even make all of them run by renaming some test classes and the packages they are in.
I would like to know why this is happening and how I can resolve it.

Body:
I have added a feature flag to my project in the form of an environment variable FEATURE_FLAG_FOO.
Now I need to integrate the feature flag into my tests. Every E2E test needs the feature flag set to some value. Most of them are not affected, so for them I just set it to true:

@SpringBootTest(classes = MyApp.class,
                webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
                properties = { "FEATURE_FLAG_FOO=true" })
public class UnrelatedE2ETest {

But for the tests that are affected, I want to test both values. So duplicate them and set the feature flag to false in the original and to true in the duplicate. I end up with both, tests that have FEATURE_FLAG_FOO set to true and tests that have it set to false.

Now if I set FEATURE_FLAG_FOO to the same value for all tests, all tests pass. If I use different values the tests still pass as long as I execute them via IntelliJ run all tests or if I execute them with maven but isolated (mvn test -Dtest=SingleE2ETest). But when I run all of them with mvn test I run into problems.

Many tests, even unrelated ones get Unexpected status code,  expected:<200> but was:<500> so something goes wrong internally and that happens only because the tests run together.

For one such unrelated test the stacktrace is:

java.net.ConnectException: Connection refused: connect
    at sun.nio.ch.Net.connect0(Net.java)
    at sun.nio.ch.Net.connect(Net.java:579)
    at sun.nio.ch.Net.connect(Net.java:568)
    at sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
    at java.net.Socket.connect(Socket.java:633)
    at java.net.Socket.connect(Socket.java:583)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:183)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:498)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:603)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:246)
    at sun.net.www.http.HttpClient.New(HttpClient.java:351)
    at sun.net.www.http.HttpClient.New(HttpClient.java:373)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1309)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1242)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1128)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1057)
    at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:109)
    ... 7 frames truncated
    ... 270 common frames omitted
Wrapped by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for \"http://0.0.0.0:55760/api/v1/unrelatedendpoint\": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:631)
[...]

http://0.0.0.0:55760/api/v1/unrelatedendpoint is a mock (autowired and stubbed with Wiremock) that the E2E test calls. So I assume that this mock is blocked, maybe due to a race condition? However upon running the tests several times it is always the same tests that fail in the same order. I can even make all of them run by renaming some test classes and the packages they are in.
I would like to know why this is happening and how I can resolve it.


问:
Add/update ACF fields with Woocommerce Rest API
I am trying to update ACF fields via Woocommerce rest api and I can't make it work.

Here is what I have.

```<code>$data['acf']['acf_field1_name']=$acf_field1_value;
$data['acf']['acf_field2_name']=$acf_field2_value;
$data['acf']['acf_field3_name']=$acf_field3_value;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, "$ckey:$csecret");
$resp = curl_exec($curl);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
</code>```

Everything works, but the ACF fields don't get inserted or updated.
Changing data['acf'] to data['fields'] also does not work.

Thank you.

Body:
I am trying to update ACF fields via Woocommerce rest api and I can't make it work.

Here is what I have.

$data['acf']['acf_field1_name']=$acf_field1_value;
$data['acf']['acf_field2_name']=$acf_field2_value;
$data['acf']['acf_field3_name']=$acf_field3_value;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, "$ckey:$csecret");
$resp = curl_exec($curl);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

Everything works, but the ACF fields don't get inserted or updated.
Changing data['acf'] to data['fields'] also does not work.

Thank you.


问:
how to fech IPTV api in node.js
How fech IPTV api with axios ("https://iptv-org.github.io/api/channels.json")

fech this api with axiosn in node.js

Title: how to fech IPTV api in node.js


问:
omnet ext interface in the inet framework
When I run the omnet ini file, I encounter the following problem
Cannot change network namespace -- in module (inet::ExtEthernetTapDevice) ExternalCommunication.host0.eth[0].tap  (id=24), during network initialization
Before that I ran setup..
The picture contains my ini code
[enter image description here](https://i.stack.imgur.com/s9B4H.png)</p>


问:
How, if it's reasonably possible, can you use .NET 7 Azure Functions in a Docker container (as opposed to .NET Core 3.1)?
We've been using a Linux Dockerfile for a .NET Core 3.1 Azure Functions app.  It starts like this:

```<code>FROM mcr.microsoft.com/azure-functions/dotnet:3.0 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
</code>```

Now we're looking to upgrade to .NET 7 - if Azure Functions is fairly compatible with it, including in Docker containers.  (In the past, I think Azure Functions has lagged in compatibility at least a time or two with .NET upgrades.)  Upgrading the Functions app to .NET 7 without changing the Dockerfile, we get this error:

```<code>error MSB3971: The reference assemblies for ".NETFramework,Version=v7.0" were not found.
</code>```

So I tried upgrading the Dockerfile.  When trying to create a new, temporary Functions project in Visual Studio, to get it to generate a starter Dockerfile for me, I see that only up to .NET 6 is on the list of options:

So that doesn't appear to work, and if anything, it indicates that Azure Functions is probably not ready for .NET 7 yet.  But looking here, I see an SDK version 7 image, and looking here, I see a Functions version 4 image.  So then this is what I tried:

```<code>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/azure-functions/dotnet:4 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
</code>```

Now I'm getting this error:

```<code>error : You must install or update .NET to run this application. [/src/<folder>/<project name>.csproj]
</code>```

Is Azure Functions just not ready yet, for .NET 7 and/or a Linux Docker container?  If it is ready, how do you make this transition from .NET Core 3.1 to .NET 7?

Body:
We've been using a Linux Dockerfile for a .NET Core 3.1 Azure Functions app.  It starts like this:

FROM mcr.microsoft.com/azure-functions/dotnet:3.0 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src

Now we're looking to upgrade to .NET 7 - if Azure Functions is fairly compatible with it, including in Docker containers.  (In the past, I think Azure Functions has lagged in compatibility at least a time or two with .NET upgrades.)  Upgrading the Functions app to .NET 7 without changing the Dockerfile, we get this error:

error MSB3971: The reference assemblies for ".NETFramework,Version=v7.0" were not found.

So I tried upgrading the Dockerfile.  When trying to create a new, temporary Functions project in Visual Studio, to get it to generate a starter Dockerfile for me, I see that only up to .NET 6 is on the list of options:

So that doesn't appear to work, and if anything, it indicates that Azure Functions is probably not ready for .NET 7 yet.  But looking here, I see an SDK version 7 image, and looking here, I see a Functions version 4 image.  So then this is what I tried:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/azure-functions/dotnet:4 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build

Now I'm getting this error:

error : You must install or update .NET to run this application. [/src/<folder>/<project name>.csproj]

Is Azure Functions just not ready yet, for .NET 7 and/or a Linux Docker container?  If it is ready, how do you make this transition from .NET Core 3.1 to .NET 7?


问:
Started developing en ecommerce website in "Angular" and got an error. Tried many ways but couldn't resolve it

The above link is the image that displays the error in the terminal. In the initial stages the app runned well. To display certain images i have copied some images from my local system and pasted in assets folder. then the started getting appeared.

After running the app by ng serve command i am getting this error instead of opening in localhost 4200

Error: Module not found: Error: Can't resolve 'C:\ecommerce\03-frontend\angular-ecommerce' in 'C:\ecommerce\03-frontend\angular-ecommerce'


问:
Is there any way to trigger the locate pointer on gnome using command line?
In Ubuntu 22.04 at least, there is a feature called locate pointer. That is toggle-able via Settings. By pressing the Control key, it will show a ripple effect around the pointer. I wonder if there's a way to trigger this without pressing a Control key, like using a command or anything to do to achieve that.

I don't mean to simulating a Control key using xdotool via terminal because it is blocking some keys. Bytheway, I need to trigger this effect when doing the left click, for recording purposes.


问:
Difference between "Modular architecture" and "Plug-in Architecture"
Is a modular architecture and a Plug-in Architecture the same thing? What are the differences between Module and Plugin? For example, if I were to make a project and if we thought that this project is a wordpress style application; Can we say that the add-ons there are actually a module? What exactly is the correct nomenclature here.</p>


问:
Laravel RabbitMQ multithread batching
I'm new to queues, trying to solve the following task:
There are several dozens xml feeds to be parsed. Each feed parsing uses 9 different laravel jobs that should be executed one by one. If one of them fails - dont run others. Also dont run next step before previous is success, but queue goes wrong.

Here is my code to make queues
`

```<code>do {
    $feed_ids = Feed::whereEnabled(true)
        ->skip($offset)
        ->take($limit)
        ->pluck('id')
        ->toArray();
    if (!empty($feed_ids)) {
        foreach ($feed_ids as $feed_id) {
            Bus::batch([
                new Download($feed_id),
                new XMLProcess($feed_id),
                //new EndProcess($feed_id),
            ])->dispatch();
            echo 'Processed: ' . ++$processed . "\n";
        }
    }
    $offset += $limit;
} while (!empty($feed_ids));

echo 'Done!' . "\n";
</code>```

`
Also ive set Download job to work 5 seconds and process work 1 second.

So im trying to run feed parallel using 2 consuming processes, but they work wrong. First process takes only Download tasks, second - only XMLProcess, process tasks goes much faster and run before download job is done.
CHECK IMAGE
Also as u can see first 2 jobs are run almost at same time, but there should be 5 seconds delay.

Also, if first I create queue and run consumers one by one, only first consumer processes jobs, second do nothing.

If I add third job, it works another, but also incorrect
CHECK IMAGE

Ive also tried chains instead of batch - in this case by the first consumers process only download jobs for all feeds, only after process job and so on, that is also not good.

Also ive tried nested batch with same result. Could you help me. Thanks.

Title: Laravel RabbitMQ multithread batching

Body:
I'm new to queues, trying to solve the following task:
There are several dozens xml feeds to be parsed. Each feed parsing uses 9 different laravel jobs that should be executed one by one. If one of them fails - dont run others. Also dont run next step before previous is success, but queue goes wrong.

Here is my code to make queues
`

do {
    $feed_ids = Feed::whereEnabled(true)
        ->skip($offset)
        ->take($limit)
        ->pluck('id')
        ->toArray();
    if (!empty($feed_ids)) {
        foreach ($feed_ids as $feed_id) {
            Bus::batch([
                new Download($feed_id),
                new XMLProcess($feed_id),
                //new EndProcess($feed_id),
            ])->dispatch();
            echo 'Processed: ' . ++$processed . "\n";
        }
    }
    $offset += $limit;
} while (!empty($feed_ids));

echo 'Done!' . "\n";

`
Also ive set Download job to work 5 seconds and process work 1 second.

So im trying to run feed parallel using 2 consuming processes, but they work wrong. First process takes only Download tasks, second - only XMLProcess, process tasks goes much faster and run before download job is done.
CHECK IMAGE
Also as u can see first 2 jobs are run almost at same time, but there should be 5 seconds delay.

Also, if first I create queue and run consumers one by one, only first consumer processes jobs, second do nothing.

If I add third job, it works another, but also incorrect
CHECK IMAGE

Ive also tried chains instead of batch - in this case by the first consumers process only download jobs for all feeds, only after process job and so on, that is also not good.

Also ive tried nested batch with same result. Could you help me. Thanks.


问:
SQL id auto reset command in PHP not working
I want to reset a database table id by the SQL command in PHP when I click a button but unfortunately, the SQL command work on the PHPmyadmin SQL option, not working in PHP.

I am getting the error:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE wordmeanings_table SET id = @num := (@num+1); ALTER TABLE wordmeanings...' at line 1 in E:\xampp\htdocs\php-ajax\index.php:98 Stack trace: #0 E:\xampp\htdocs\php-ajax\index.php(98): mysqli_query(Object(mysqli), 'SET @num := 0;...') #1 {main} thrown in E:\xampp\htdocs\php-ajax\index.php on line 98

Check out the PHP codes, I don't know what's wrong with the codes:

```<code><?php
if(isset($_POST['submit']))
{
  $sql = "SET  @num := 0; UPDATE wordmeanings_table SET id = @num := (@num+1); ALTER TABLE wordmeanings_table AUTO_INCREMENT =1";

  mysqli_query($conn, $sql);

};
?>
</code>```

Body:
I want to reset a database table id by the SQL command in PHP when I click a button but unfortunately, the SQL command work on the PHPmyadmin SQL option, not working in PHP.

I am getting the error:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE wordmeanings_table SET id = @num := (@num+1); ALTER TABLE wordmeanings...' at line 1 in E:\xampp\htdocs\php-ajax\index.php:98 Stack trace: #0 E:\xampp\htdocs\php-ajax\index.php(98): mysqli_query(Object(mysqli), 'SET @num := 0;...') #1 {main} thrown in E:\xampp\htdocs\php-ajax\index.php on line 98

Check out the PHP codes, I don't know what's wrong with the codes:

<?php
if(isset($_POST['submit']))
{
  $sql = "SET  @num := 0; UPDATE wordmeanings_table SET id = @num := (@num+1); ALTER TABLE wordmeanings_table AUTO_INCREMENT =1";

  mysqli_query($conn, $sql);

};
?>


问:
Flutter - animating text
I am trying to animate some text. I would like the text to be typed out, with some parts of the text having a different style applied to them.

I found the AnimatedTextKit package an tried using it.

```<code>child: AnimatedTextKit(
    animatedTexts: [
        TyperAnimatedText(
            'Hello world!',
            textStyle: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
            ),
        ),
    ],
    totalRepeatCount: 1,
),
</code>```

This does take care of my first requirement, typing out the text. However I cannot find a way to add different styles to different parts of the text. If I add a second TyperAnimatedText to the list, the animation deletes the first text before showing the second.

Whay would be the best approach to solve this?

Title: Flutter - animating text

Body:
I am trying to animate some text. I would like the text to be typed out, with some parts of the text having a different style applied to them.

I found the AnimatedTextKit package an tried using it.

child: AnimatedTextKit(
    animatedTexts: [
        TyperAnimatedText(
            'Hello world!',
            textStyle: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
            ),
        ),
    ],
    totalRepeatCount: 1,
),

This does take care of my first requirement, typing out the text. However I cannot find a way to add different styles to different parts of the text. If I add a second TyperAnimatedText to the list, the animation deletes the first text before showing the second.

Whay would be the best approach to solve this?


问:
I try to get background app package name using foreground service with UsageEvent in android 12
```<code>long endTime = System.currentTimeMillis();
        long beginTime = endTime - 10000;
        String result = "";
        UsageEvents.Event event = new UsageEvents.Event();
        UsageEvents usageEvents = sUsageStatsManager.queryEvents(beginTime, endTime);
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
            if (event.getEventType() == UsageEvents.Event.MOVE_TO_BACKGROUND) {
                result = event.getPackageName();
            }
        }
</code>```

in the above method in usage events.hasNextEvent() is return only true in below android 11 and android 12 in return always false, so I need to true in android 12.

Body:
long endTime = System.currentTimeMillis();
        long beginTime = endTime - 10000;
        String result = "";
        UsageEvents.Event event = new UsageEvents.Event();
        UsageEvents usageEvents = sUsageStatsManager.queryEvents(beginTime, endTime);
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
            if (event.getEventType() == UsageEvents.Event.MOVE_TO_BACKGROUND) {
                result = event.getPackageName();
            }
        }

in the above method in usage events.hasNextEvent() is return only true in below android 11 and android 12 in return always false, so I need to true in android 12.


问:
execute function in list every time the variable is called
I would like to execute the symbols_list functions every time I call the commands variable. How would I do that? Now it is called only when commands is defined.</p>
```<code>Bot1Console = ConsoleDialog()

    sl1 = ["arg61a", "arg61b", "arg61c"]
    def symbols_list1():
        l = [str(symbol).lower() for symbol in sl1]
        return l

    sl2 = ["arg70a", "arg70b", "arg70c"]
    def symbols_list2():
        l = [str(symbol).lower() for symbol in sl2]
        return l

    Bot1Console.commands = [
        # All strings have to be in lower case
        ["help"],                           # 00 Help: first element in list
        ["arg10", "arg11"],                 # 01 2 arguments
        ["arg20", ["arg21a", "arg21b"]],    # 02 argument with 2 options
        ["arg30", [float, "arg31b"]],       # 03 argument with 2 options
        ["arg40", str, float],              # 04 type str, type float
        ["arg50", float, str],              # 05 type float, type str
        ["arg60", symbols_list1],           # 06 argument using a function return
        [symbols_list2, "arg71"],           # 07 argument using a function return
        ["arg80", "arg81"],                 # 08 argument using a function return
        ["append", str],                    # 09 append to arg60
        ["exit"]                            # 10 Exit: Last element in List
    ]
</code>```

Body:
I would like to execute the symbols_list functions every time I call the commands variable. How would I do that? Now it is called only when commands is defined.

Bot1Console = ConsoleDialog()

    sl1 = ["arg61a", "arg61b", "arg61c"]
    def symbols_list1():
        l = [str(symbol).lower() for symbol in sl1]
        return l

    sl2 = ["arg70a", "arg70b", "arg70c"]
    def symbols_list2():
        l = [str(symbol).lower() for symbol in sl2]
        return l

    Bot1Console.commands = [
        # All strings have to be in lower case
        ["help"],                           # 00 Help: first element in list
        ["arg10", "arg11"],                 # 01 2 arguments
        ["arg20", ["arg21a", "arg21b"]],    # 02 argument with 2 options
        ["arg30", [float, "arg31b"]],       # 03 argument with 2 options
        ["arg40", str, float],              # 04 type str, type float
        ["arg50", float, str],              # 05 type float, type str
        ["arg60", symbols_list1],           # 06 argument using a function return
        [symbols_list2, "arg71"],           # 07 argument using a function return
        ["arg80", "arg81"],                 # 08 argument using a function return
        ["append", str],                    # 09 append to arg60
        ["exit"]                            # 10 Exit: Last element in List
    ]


问:
In which subject area transactions are not needed?
It's just a question from interview. I can't find an answer. The first part of the question is "what is a transaction and what is it for" - it's not a problem to answer.

More exactly - "give an example of the subject area where transactions are not needed".


问:
Not getting DB connection using mongoose on a deta micro
I'm trying to deploy a simple (almost CRUD) node API project on a deta micro.

My server.js file starts the app and is (with some "consol.logs" for debugging):

```<code>const mongoose = require("mongoose");
const dotenv = require("dotenv");

console.log("Punto 1");
dotenv.config({ path: "./config.env" });
const app = require("./app");

const DB = process.env.DATABASE.replace(
  "<PASSWORD>",
  process.env.DATABASE_PASSWORD
);
console.log("Punto 2");
mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then(() => console.log("DB connection successful!"));

console.log(process.env.PORT + " Esto");
const port = process.env.PORT || 3000;
console.log("Punto 3");
console.log("port es: " + port);
app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});
console.log("pasé!");
</code>```

Here the application:

```<code>const express = require("express");
require("express-async-errors");
const morgan = require("morgan");
const compression = require("compression");
const eventRouter = require("./routes/eventRoutes");
const userRouter = require("./routes/userRoutes");

const app = express();
console.log("Hello from here ");
// 1) MIDDLEWARES
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

app.use(express.json());
app.use(express.static(`${__dirname}/public`));

app.use((req, res, next) => {
  console.log("Hello from the middleware ");
  next();
});

app.use(compression());

app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();
  next();
});

// 3) ROUTES
app.use("/api/v1/events", eventRouter);
app.use("/api/v1/users", userRouter);

module.exports = app;

</code>```

Using mongoose 5.13.15 it gives:

```<code>
[2022-12-30T10:16:56-03:00] 2022-12-30T13:16:56.778Z    undefined   INFO    Punto 1

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.024Z    undefined   INFO    Hello from the here

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.025Z    undefined   INFO    Punto 2

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.031Z    undefined   INFO    3000 Esto

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.033Z    undefined   INFO    pasé!

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.034Z    undefined   INFO    App running on port 3000...

[2022-12-30T10:16:57-03:00]     ERROR   Invoke Error    {"errorType":"Error","errorMessage":"Unsupported framework","stack":["Error: Unsupported framework","    at getFramework (/opt/nodejs/node_modules/serverless-http/lib/framework/get-framework.js:63:9)","    at module.exports (/opt/nodejs/node_modules/serverless-http/serverless-http.js:14:21)","    at Object.handleCustom (/opt/nodejs/node_modules/detalib/deta/internal/handlers.js:20:19)","    at handler (/opt/nodejs/node_modules/detalib/deta/lib/handler.js:13:46)","    at Object.handler (/opt/nodejs/node_modules/detalib/deta/internal/debug/debugger.js:145:14)","    at Runtime.module.exports.handler (/var/task/_entry.js:11:18)","    at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:74:25)"]}

</code>```

Using mongoose 6.8.2 it gives:

```<code>[2022-12-30T10:26:47-03:00] [ERROR] [1672406807505] LAMBDA_RUNTIME Failed to get next invocation. Http Response code: 403

[2022-12-30T10:26:47-03:00] 2022-12-30T13:26:47.506Z    undefined   INFO    Unexpected Top Level Error: Error: Failed to get next invocation, error 403

[2022-12-30T10:26:47-03:00] Unknown application error occurred
Runtime.UnhandledPromiseRejection

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.218Z    undefined   INFO    Punto 1

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.444Z    undefined   INFO    Hello from the here

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.445Z    undefined   INFO    Punto 2

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.465Z    undefined   INFO    3000 Esto

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.467Z    undefined   INFO    pasé!

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.468Z    undefined   ERROR   (node:8) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.470Z    undefined   ERROR   Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoParseError: options usecreateindex, usefindandmodify are not supported","reason":{"errorType":"MongoParseError","errorMessage":"options usecreateindex, usefindandmodify are not supported","stack":["MongoParseError: options usecreateindex, usefindandmodify are not supported","    at parseOptions (/opt/nodejs/node_modules/mongoose/node_modules/mongodb/lib/connection_string.js:282:15)","    at new MongoClient (/opt/nodejs/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:45:63)","    at /opt/nodejs/node_modules/mongoose/lib/connection.js:802:16","    at new Promise (<anonymous>)","    at NativeConnection.Connection.openUri (/opt/nodejs/node_modules/mongoose/lib/connection.js:799:19)","    at /opt/nodejs/node_modules/mongoose/lib/index.js:409:10","    at /opt/nodejs/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5","    at new Promise (<anonymous>)","    at promiseOrCallback (/opt/nodejs/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)","    at Mongoose._promiseOrCallback (/opt/nodejs/node_modules/mongoose/lib/index.js:1262:10)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoParseError: options usecreateindex, usefindandmodify are not supported","    at process.<anonymous> (/var/runtime/index.js:35:15)","    at process.emit (events.js:400:28)","    at processPromiseRejections (internal/process/promises.js:245:33)","    at processTicksAndRejections (internal/process/task_queues.js:96:32)"]}

[2022-12-30T10:26:48-03:00] [ERROR] [1672406808504] LAMBDA_RUNTIME Failed to get next invocation. Http Response code: 403

</code>```

When is locally deployed it works properly.
This question is very similar to Aman Sharman's:
.
I've tried to be clear on my question.
I'm hopefully waiting for any help or comment
Thank you

I've tried to vary the mongoose version
Check my DB's IP whitelist (is able to receive from any IP)
Passed the environment variables (database and DBpassword among others) using deta update <namefile.env>

Body:
I'm trying to deploy a simple (almost CRUD) node API project on a deta micro.

My server.js file starts the app and is (with some "consol.logs" for debugging):

const mongoose = require("mongoose");
const dotenv = require("dotenv");

console.log("Punto 1");
dotenv.config({ path: "./config.env" });
const app = require("./app");

const DB = process.env.DATABASE.replace(
  "<PASSWORD>",
  process.env.DATABASE_PASSWORD
);
console.log("Punto 2");
mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then(() => console.log("DB connection successful!"));

console.log(process.env.PORT + " Esto");
const port = process.env.PORT || 3000;
console.log("Punto 3");
console.log("port es: " + port);
app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});
console.log("pasé!");

Here the application:

const express = require("express");
require("express-async-errors");
const morgan = require("morgan");
const compression = require("compression");
const eventRouter = require("./routes/eventRoutes");
const userRouter = require("./routes/userRoutes");

const app = express();
console.log("Hello from here ");
// 1) MIDDLEWARES
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

app.use(express.json());
app.use(express.static(`${__dirname}/public`));

app.use((req, res, next) => {
  console.log("Hello from the middleware ");
  next();
});

app.use(compression());

app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();
  next();
});

// 3) ROUTES
app.use("/api/v1/events", eventRouter);
app.use("/api/v1/users", userRouter);

module.exports = app;

Using mongoose 5.13.15 it gives:

[2022-12-30T10:16:56-03:00] 2022-12-30T13:16:56.778Z    undefined   INFO    Punto 1

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.024Z    undefined   INFO    Hello from the here

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.025Z    undefined   INFO    Punto 2

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.031Z    undefined   INFO    3000 Esto

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.033Z    undefined   INFO    pasé!

[2022-12-30T10:16:57-03:00] 2022-12-30T13:16:57.034Z    undefined   INFO    App running on port 3000...

[2022-12-30T10:16:57-03:00]     ERROR   Invoke Error    {"errorType":"Error","errorMessage":"Unsupported framework","stack":["Error: Unsupported framework","    at getFramework (/opt/nodejs/node_modules/serverless-http/lib/framework/get-framework.js:63:9)","    at module.exports (/opt/nodejs/node_modules/serverless-http/serverless-http.js:14:21)","    at Object.handleCustom (/opt/nodejs/node_modules/detalib/deta/internal/handlers.js:20:19)","    at handler (/opt/nodejs/node_modules/detalib/deta/lib/handler.js:13:46)","    at Object.handler (/opt/nodejs/node_modules/detalib/deta/internal/debug/debugger.js:145:14)","    at Runtime.module.exports.handler (/var/task/_entry.js:11:18)","    at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:74:25)"]}

Using mongoose 6.8.2 it gives:

[2022-12-30T10:26:47-03:00] [ERROR] [1672406807505] LAMBDA_RUNTIME Failed to get next invocation. Http Response code: 403

[2022-12-30T10:26:47-03:00] 2022-12-30T13:26:47.506Z    undefined   INFO    Unexpected Top Level Error: Error: Failed to get next invocation, error 403

[2022-12-30T10:26:47-03:00] Unknown application error occurred
Runtime.UnhandledPromiseRejection

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.218Z    undefined   INFO    Punto 1

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.444Z    undefined   INFO    Hello from the here

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.445Z    undefined   INFO    Punto 2

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.465Z    undefined   INFO    3000 Esto

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.467Z    undefined   INFO    pasé!

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.468Z    undefined   ERROR   (node:8) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)

[2022-12-30T10:26:48-03:00] 2022-12-30T13:26:48.470Z    undefined   ERROR   Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoParseError: options usecreateindex, usefindandmodify are not supported","reason":{"errorType":"MongoParseError","errorMessage":"options usecreateindex, usefindandmodify are not supported","stack":["MongoParseError: options usecreateindex, usefindandmodify are not supported","    at parseOptions (/opt/nodejs/node_modules/mongoose/node_modules/mongodb/lib/connection_string.js:282:15)","    at new MongoClient (/opt/nodejs/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:45:63)","    at /opt/nodejs/node_modules/mongoose/lib/connection.js:802:16","    at new Promise (<anonymous>)","    at NativeConnection.Connection.openUri (/opt/nodejs/node_modules/mongoose/lib/connection.js:799:19)","    at /opt/nodejs/node_modules/mongoose/lib/index.js:409:10","    at /opt/nodejs/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5","    at new Promise (<anonymous>)","    at promiseOrCallback (/opt/nodejs/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)","    at Mongoose._promiseOrCallback (/opt/nodejs/node_modules/mongoose/lib/index.js:1262:10)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoParseError: options usecreateindex, usefindandmodify are not supported","    at process.<anonymous> (/var/runtime/index.js:35:15)","    at process.emit (events.js:400:28)","    at processPromiseRejections (internal/process/promises.js:245:33)","    at processTicksAndRejections (internal/process/task_queues.js:96:32)"]}

[2022-12-30T10:26:48-03:00] [ERROR] [1672406808504] LAMBDA_RUNTIME Failed to get next invocation. Http Response code: 403

When is locally deployed it works properly.
This question is very similar to Aman Sharman's:
.
I've tried to be clear on my question.
I'm hopefully waiting for any help or comment
Thank you

I've tried to vary the mongoose version
Check my DB's IP whitelist (is able to receive from any IP)
Passed the environment variables (database and DBpassword among others) using deta update <namefile.env>


问:
Build IConfiguration in MVC targeting .NET 4.8
A constructor has this signature:

```<code>private readonly IConfiguration _configuration;
public SomeClass(IConfiguration configuration)
{
    _configuration = configuration;
}
</code>```

This code belongs to class from a Nuget package targeting .Net Standard 2.0

I have to use this in a MVC application targeting 4.8

Tried this in a controller action method, just to test:

```<code>    IConfiguration config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
.AddXmlFile("web.config")
.Build();
</code>```

The web.config has xmlns like so:

```<code><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
</code>```

Any meddling with this tag will break the app so it will stay, no options here.

The above code can't read it and gives this error:

```<code>FormatException: XML namespaces are not supported
</code>```

XmlConfigurationProvider and MemoryConfigurationBuilder are not available in .NET Framework 4.8.

What are my options to build IConfiguration in a .Net 4.8 MVC application?

Appreciate any guidance here and thanks in advance.

Body:
A constructor has this signature:

private readonly IConfiguration _configuration;
public SomeClass(IConfiguration configuration)
{
    _configuration = configuration;
}

This code belongs to class from a Nuget package targeting .Net Standard 2.0

I have to use this in a MVC application targeting 4.8

Tried this in a controller action method, just to test:

    IConfiguration config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
.AddXmlFile("web.config")
.Build();

The web.config has xmlns like so:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

Any meddling with this tag will break the app so it will stay, no options here.

The above code can't read it and gives this error:

FormatException: XML namespaces are not supported

XmlConfigurationProvider and MemoryConfigurationBuilder are not available in .NET Framework 4.8.

What are my options to build IConfiguration in a .Net 4.8 MVC application?

Appreciate any guidance here and thanks in advance.


问:
I get "InvalidSignatureException: Signature expired" when Lambda is invoked
I have the following architecture:

S3 ---> S3 Notification ---> SQS ---> Lambda

Sometimes, I'm getting the following error message from the Lambda (of course the times are different):

```<code>"errorType": "Runtime.UnhandledPromiseRejection"
"errorMessage": "InvalidSignatureException: Signature expired: 20221230T132433Z is now earlier than 20221230T132603Z (20221230T133103Z - 5 min.)"
</code>```

I have a retry policy in the SQS, so when the error occurs, the message returns to the SQS, and the Lambda process it again. When it processes it again, the same message, it succeeds and is processed successfully.

Any idea why?

Body:
I have the following architecture:

S3 ---> S3 Notification ---> SQS ---> Lambda

Sometimes, I'm getting the following error message from the Lambda (of course the times are different):

"errorType": "Runtime.UnhandledPromiseRejection"
"errorMessage": "InvalidSignatureException: Signature expired: 20221230T132433Z is now earlier than 20221230T132603Z (20221230T133103Z - 5 min.)"

I have a retry policy in the SQS, so when the error occurs, the message returns to the SQS, and the Lambda process it again. When it processes it again, the same message, it succeeds and is processed successfully.

Any idea why?


问:
Invalid project path
Project path 'C:\Users\ererd\OneDrive\Рабочий стол\Cars2' contains non-ASCII characters at position 24, Android Tools don't work properly with non-ASCII paths. Please move your project to path containing only ASCII characters.

I tried to create an Android folder and tried to change the parameters in unity.

Title: Invalid project path


问:
How to run the service Using a kebernetes service
I've a service running on my Kubernetes with the type loadBalancer.

```<code>    apiVersion: v1
kind: Service
metadata:
  name: flask-app-services-dashboard
spec:
  type: LoadBalancer
  ports:
    - port: 5005
      targetPort: 5005
  externalIPs:
    - 1.2.4.120
  selector:
    app: flask-app-dashboard
</code>```

It has created the External-IP 127.0.0.1. But I need to provide my own External-IP for that I've given 1.2.4.120 as there on the above code.

It also generates the External-IP which I gave. but, I'm Unable to access it and showing This site can’t be reached1.2.4.120 took too long to respond.

How can I access the application using the External-IP which I've given?

Body:
I've a service running on my Kubernetes with the type loadBalancer.

    apiVersion: v1
kind: Service
metadata:
  name: flask-app-services-dashboard
spec:
  type: LoadBalancer
  ports:
    - port: 5005
      targetPort: 5005
  externalIPs:
    - 1.2.4.120
  selector:
    app: flask-app-dashboard

It has created the External-IP 127.0.0.1. But I need to provide my own External-IP for that I've given 1.2.4.120 as there on the above code.

It also generates the External-IP which I gave. but, I'm Unable to access it and showing This site can’t be reached1.2.4.120 took too long to respond.

How can I access the application using the External-IP which I've given?


问:
java1.8_45 ThreadPoolExecutor use ArrayBlockingQueue occur deadlock

Now, threadpool is full, workQueue is full, many thread blocking at workQueue's lock, and the consumer thread pool, all consumer thread, are waiting to take task.
I'm sure the ArrayBlockingQueue's lock can be acquire, but when released, head can't unpark,

I don't know why, now the application is dead. If I send request to it, I just get this: java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@2bfa7c15 rejected.

I must find out the reason.


问:
The picture element not working as expected
What is wrong with my code when I change the width images are not changing. Only the image which is within the  tag is appearing

As I am a beginner may I am not able to spot the mistake

```<code><main>
        <div class="portions first-part">
          <picture>
            <source srcset="images/image-hero-mobile.png" media="(max-width:500px)">
            <img src="images/image-hero-desktop.png">
          </picture>
        </div>
        <div class="portions second-part"> <h1>Make remote work</h1>

      <p>Get your team in sync, no matter your location. Streamline processes,
  create team rituals, and watch productivity soar.</p>

      <button class="button">learn more</button></div>
      </main>
</code>```

Body:
What is wrong with my code when I change the width images are not changing. Only the image which is within the  tag is appearing

As I am a beginner may I am not able to spot the mistake

          <picture>
            <source srcset="images/image-hero-mobile.png" media="(max-width:500px)">

          </picture>

Make remote work

Get your team in sync, no matter your location. Streamline processes,
  create team rituals, and watch productivity soar.

      <button class="button">learn more</button>


问:
Best way to update the local state of a component in react on some external event
Here's the scenario. I have a app and a search component.

```<code>const App = () => {
    const [search, setSearch] = useState("initial query");
    // ... other code

    return (
         <Search search={search} setSearch={setSearch} />
         ...other components
    );
};
</code>```
```<code>const Search = ({ search, setSearch }) => {
    const [localSearch, setLocalSearch] = useState(search);
    const debouncedSetSearch = useMemo(() => debounce(setSearch, 200), [setSearch]);
    const handleTextChange = useCallback((e) => {
        setLocalSearch(e.target.value);
        debouncedSetSearch(e.target.value);
    }, [setLocalSearch]);

    return (
         <input value={localSearch} onChange={handleTextChange} />
    );
}
</code>```

It's all good until this point. But I want to know what's the best way to change the search text on an external event. So far, the best approach I've found is using events.

```<code>const App = () => {
    const [search, setSearch] = useState("initial query");
    // ... other code

    useEffect(() => {
       onSomeExternalEvent((newSearch) => {
           setSearch(newSearch);
           EventBus.emit("updateSearch", newSearch);
       });
    }, []);

    return (
         <Search search={search} setSearch={setSearch} />
         ...other components
    );
};
</code>```
```<code>const Search = ({ search, setSearch }) => {
    const [localSearch, setLocalSearch] = useState(search);
    const debouncedSetSearch = useMemo(() => debounce(setSearch, 200), [setSearch]);
    const handleTextChange = useCallback((e) => {
        setLocalSearch(e.target.value);
        debouncedSetSearch(e.target.value);
    }, [setLocalSearch]);

    useEffect(() => {
        EventBus.subscribe("updateSearch", (newSearch) => {
            setLocalSearch(newSearch);
        });
    }, []);

    return (
         <input value={localSearch} onChange={handleTextChange} />
    );
}
</code>```

Is there a better (correct) way of doing this?

Body:
Here's the scenario. I have a app and a search component.

const App = () => {
    const [search, setSearch] = useState("initial query");
    // ... other code

    return (
         <Search search={search} setSearch={setSearch} />
         ...other components
    );
};

const Search = ({ search, setSearch }) => {
    const [localSearch, setLocalSearch] = useState(search);
    const debouncedSetSearch = useMemo(() => debounce(setSearch, 200), [setSearch]);
    const handleTextChange = useCallback((e) => {
        setLocalSearch(e.target.value);
        debouncedSetSearch(e.target.value);
    }, [setLocalSearch]);

    return (
         <input value={localSearch} onChange={handleTextChange} />
    );
}

It's all good until this point. But I want to know what's the best way to change the search text on an external event. So far, the best approach I've found is using events.

const App = () => {
    const [search, setSearch] = useState("initial query");
    // ... other code

    useEffect(() => {
       onSomeExternalEvent((newSearch) => {
           setSearch(newSearch);
           EventBus.emit("updateSearch", newSearch);
       });
    }, []);

    return (
         <Search search={search} setSearch={setSearch} />
         ...other components
    );
};

const Search = ({ search, setSearch }) => {
    const [localSearch, setLocalSearch] = useState(search);
    const debouncedSetSearch = useMemo(() => debounce(setSearch, 200), [setSearch]);
    const handleTextChange = useCallback((e) => {
        setLocalSearch(e.target.value);
        debouncedSetSearch(e.target.value);
    }, [setLocalSearch]);

    useEffect(() => {
        EventBus.subscribe("updateSearch", (newSearch) => {
            setLocalSearch(newSearch);
        });
    }, []);

    return (
         <input value={localSearch} onChange={handleTextChange} />
    );
}

Is there a better (correct) way of doing this?


问:
Tabulator - Tree Structure - Branch Totals
I have a tabulator table with below data / configuration;

Data;

```<code>var data_tab =
[ {
    "code": "A",
    "desc_tr": "Top Level",
    "mylink": [
        {
            "code": "A.1",
            "desc_tr": "Sub Level 1",
            "mylink": [
                {
                    "code": "A.1.1",
                    "desc_tr": "Sub Level 2",
                    "mylink": [
                        {
                            "code": "A.1.1.1",
                            "desc_tr": "Sub Level 3",
                            "mylink": [
                                {
                                    "code": "A.1.1.1.001",
                                    "desc_tr": "Item 1 at Last Level",
                                    "income": "5",
                                },
                                {
                                    "code": "A.1.1.1.002",
                                    "desc_tr": "Item 2 at Last Level",
                                    "income": "2",
                                }
                            ]

                        }
                    ]
                }
            ]
        },
    ]
} ]
</code>```

Config / parameters for table;

```<code>let tmp_Tabulator = new Tabulator( "#tabulator_table",
    {
        data                    : data_tab,
        columns                 : stg_Tabulator[ src_coldata ],
        reactiveData            : false,
        dataTree                : true,
        dataTreeBranchElement   : false,
        dataTreeChildIndent     : 0,
        dataTreeChildField      : "mylink",
        height                  : 683,
    }
)
</code>```

This is the config / parameters for columns;

```<code>tbl_Sample              : [
    {
        title           : "G",
        field           : "",
        width           : 51,
        formatter       : null,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "CODE",
        field           : "code",
        width           : 100,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "DESCRIPTION",
        field           : "desc_tr",
        width           : 400,
        formatter       : null,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "INCOME",
        field           : "income",
        width           : 160,
        formatter       : "money",
        hozAlign        : "right",
        formatterParams : fmt_num_2,
        topCalc         : "sum",
    },
],
</code>```

This is how table looks like when rendered ;

What should I do to populate income fields at upper levels ?

Thanks in advance...

PS : This is just a sample data and I do not want to do it at source data side (by changing query / json structure ect.) as it is very resource demanding.

Body:
I have a tabulator table with below data / configuration;

Data;

var data_tab =
[ {
    "code": "A",
    "desc_tr": "Top Level",
    "mylink": [
        {
            "code": "A.1",
            "desc_tr": "Sub Level 1",
            "mylink": [
                {
                    "code": "A.1.1",
                    "desc_tr": "Sub Level 2",
                    "mylink": [
                        {
                            "code": "A.1.1.1",
                            "desc_tr": "Sub Level 3",
                            "mylink": [
                                {
                                    "code": "A.1.1.1.001",
                                    "desc_tr": "Item 1 at Last Level",
                                    "income": "5",
                                },
                                {
                                    "code": "A.1.1.1.002",
                                    "desc_tr": "Item 2 at Last Level",
                                    "income": "2",
                                }
                            ]

                        }
                    ]
                }
            ]
        },
    ]
} ]

Config / parameters for table;

let tmp_Tabulator = new Tabulator( "#tabulator_table",
    {
        data                    : data_tab,
        columns                 : stg_Tabulator[ src_coldata ],
        reactiveData            : false,
        dataTree                : true,
        dataTreeBranchElement   : false,
        dataTreeChildIndent     : 0,
        dataTreeChildField      : "mylink",
        height                  : 683,
    }
)

This is the config / parameters for columns;

tbl_Sample              : [
    {
        title           : "G",
        field           : "",
        width           : 51,
        formatter       : null,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "CODE",
        field           : "code",
        width           : 100,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "DESCRIPTION",
        field           : "desc_tr",
        width           : 400,
        formatter       : null,
        hozAlign        : "left",
        formatterParams : null
    },
    {
        title           : "INCOME",
        field           : "income",
        width           : 160,
        formatter       : "money",
        hozAlign        : "right",
        formatterParams : fmt_num_2,
        topCalc         : "sum",
    },
],

This is how table looks like when rendered ;

What should I do to populate income fields at upper levels ?

Thanks in advance...

PS : This is just a sample data and I do not want to do it at source data side (by changing query / json structure ect.) as it is very resource demanding.


问:
python seleniumdriver ile xpath hatası
<em>```
login_button = browser.driver.find_element(By.XPATH,'//</em>[@id="loginForm"]/div/div[3]/button')
^^^^^^^^^^^^^^*
AttributeError: 'WebDriver' object has no attribute 'driver'</p>
```<code>I don't understand what is the problem?
selenium 4.7.2

xptah seçimi yapamıyorum.
</code>```

Title: python seleniumdriver ile xpath hatası

Body:
```
login_button = browser.driver.find_element(By.XPATH,'//[@id="loginForm"]/div/div[3]/button')
^^^^^^^^^^^^^^*
AttributeError: 'WebDriver' object has no attribute 'driver'

I don't understand what is the problem?
selenium 4.7.2

xptah seçimi yapamıyorum.


问:
Need help improving backtest class and find optimal combinations
I'm trying to create a backtest class. The code i have for the class atm is this:

```<code>class Backtest:
def __init__(self, df, signals, initial_capital, max_position_size, stop_loss, conditions):
    self.df = df
    self.signals = signals[signals.index.isin(self.df.index)]
    self.initial_capital = initial_capital
    self.positions = pd.DataFrame(index=signals.index).fillna(0.0)
    self.max_position_size = max_position_size
    self.stop_loss = stop_loss
    self.conditions = conditions
    self.stop_loss_levels = None
    self.portfolio_value = None
    self.portfolio_returns = None
    self.portfolio_risk = None
    self.results=None

#this section applies conditions for buying, selling, closes
def generate_trades(self):
    self.positions['buy'] = np.where(self.conditions['buy'], 1000 / self.df['close'], 0)
    self.positions['sell'] = np.where(self.conditions['sell'], -1000 / self.df['close'], 0)
    self.positions = self.positions.where(self.conditions['close'], 0)

"""
conditions = {
    'buy': (self.signals['signal_rsi_oversold'] == 1) & (self.signals['signal_stochastic_oversold'] == 1),
    'sell': (self.signals['signal_rsi_overbought'] == 1) & (self.signals['signal_stochastic_overbought'] == 1),
    'close': self.df['close'] > self.stop_loss_levels
}"""

def calculate_exposure_time(self):
    self.positions['open_time'] = np.where(self.positions['buy'] > 0, self.df['date'], np.nan)
    self.positions['close_time'] = np.where(self.positions['sell'] > 0, self.df['date'], np.nan)
    self.positions['exposure_time'] = self.positions['close_time'] - self.positions['open_time']

def backtest(self):
    self.generate_trades()
    #self.positions['buy'] = np.where(self.signals[buys].sum(axis=1) > 0, 1000 / self.df['close'], 0)
    #self.positions['sell'] = np.where(self.signals[sells].sum(axis=1) > 0, -1000 / self.df['close'], 0)
    portfolio = self.positions.multiply(self.df['close'], axis=0)
    pos_diff = self.positions.diff()
    portfolio['holdings'] = (self.positions.multiply(self.df['close'], axis=0)).sum(axis=1)
    portfolio['cash'] = self.initial_capital - (pos_diff.multiply(self.df['close'], axis=0)).sum(axis=1).cumsum()
    portfolio['total'] = portfolio['cash'] + portfolio['holdings']
    portfolio['returns'] = portfolio['total'].pct_change()
    self.results = portfolio

    # Calculate the average exposure time
    average_exposure_time = self.positions['exposure_time'].mean()

    # Calculate the Sharpe ratio
    sharpe_ratio = np.sqrt(252) * (self.results['returns'].mean() / self.results['returns'].std())

    # Calculate the maximum drawdown
    max_dd = (self.results['total'].cummax() - self.results['total']).max()

    # Calculate the maximum drawdown duration
    max_dd_duration = (self.results['total'].cummax() - self.results['total']).argmax()

    # Calculate the profit factor
    profit_factor = (self.results[self.results['returns'] > 0]['returns'].sum() / abs(self.results[self.results['returns'] < 0]['returns'].sum()))

    # Calculate the average loss and average profit
    trades = self.results[self.results['returns'] != 0]['returns']
    average_loss = trades[trades < 0].mean()
    average_profit = trades[trades > 0].mean()

    # Calculate the Calmar ratio
    calmar_ratio = self.results['returns'].mean() / max_dd

    # Calculate the number of trades taken
    num_trades = trades.count()

    # Calculate the number of winning trades and losing trades
    num_winning_trades = 0
    num_losing_trades = 0
    for i, row in self.results.iterrows():
        if row['returns'] > 0:
            num_winning_trades += 1
        elif row['returns'] < 0:
            num_losing_trades += 1

    # Calculate the win/loss ratio
    win_loss_ratio = num_winning_trades / num_losing_trades

    self.statistics = {
        'calmar_ratio': calmar_ratio,
        'sharpe_ratio': sharpe_ratio,
        'max_drawdown': max_dd,
        'max_drawdown_duration': max_dd_duration,
        'profit_factor': profit_factor,
        'average_loss': average_loss,
        'average_profit': average_profit,
        'num_trades': num_trades,
        'num_winning_trades':num_winning_trades,
        'num_losing_trades':num_losing_trades,
        'win_loss_ratio':win_loss_ratio,
        'exposure_time': average_exposure_time
    }
</code>```

I also have this code that I'm trying to use to analyse results. I'm not sure how to integrate:

```<code>def backtest_by_trade(self, buys, sells):
# Initialize a dictionary to store the results for each trade
self.results_by_trade = {}
# Iterate over the combinations of buy and sell values
for buy in buys:
    for sell in sells:
        # Create a copy of the signals dataframe
        signals = self.signals.copy()
        # Update the signals dataframe with the buy and sell values
        signals['buy'] = np.where(signals['signal_rsi_oversold'] == 1, buy, 0)
        signals['sell'] = np.where(signals['signal_rsi_overbought'] == 1, sell, 0)
        # Create a new Backtest object using the updated signals dataframe
        bt = Backtest(self.df, signals, initial_capital=10000)
        # Run the backtest
        bt.backtest()
        # Store the results in the results_by_trade dictionary
        self.results_by_trade[(buy, sell)] = bt.results

# Calculate the profit or loss for each trade
self.results_by_trade['profit_loss'] = self.results_by_trade['total_profit'] - self.results_by_trade['total_loss']
# Calculate the return on investment for each trade
self.results_by_trade['return_on_investment'] = self.results_by_trade['total_profit'] / self.results_by_trade['total_loss']
# Calculate the profit factor for each trade
self.results_by_trade['profit_factor'] = self.results_by_trade['total_profit'] / abs(self.results_by_trade['total_loss'])
# Calculate the percentage of profitable trades for each combination
self.results_by_trade['percent_profitable'] = self.results_by_trade['num_winning_trades'] / self.results_by_trade['num_trades']
# Calculate the average profit per trade for each combination
self.results_by_trade['avg_profit_per_trade'] = self.results_by_trade['total_profit'] / self.results_by_trade['num_winning_trades']
# Calculate the average loss per trade for each combination
self.results_by_trade['avg_loss_per_trade'] = self.results_by_trade['total_loss'] / self.results_by_trade['num_losing_trades']
# Calculate the maximum consecutive winning trades for each combination
self.results_by_trade['max_consecutive_winning_trades'] = self.results_by_trade['consecutive_winning_trades'].max()
# Calculate the maximum consecutive losing trades for each combination
self.results_by_trade['max_consecutive_losing_trades'] = self.results_by_trade['consecutive_losing_trades'].max()
# Calculate the average consecutive winning trades for each combination
self.results_by_trade['avg_consecutive_winning_trades']
</code>```

In the end, i want to use different combinations of the condictions dictionary and analyse what might be the best combination of signals. How can i do this ?

Body:
I'm trying to create a backtest class. The code i have for the class atm is this:

class Backtest:
def __init__(self, df, signals, initial_capital, max_position_size, stop_loss, conditions):
    self.df = df
    self.signals = signals[signals.index.isin(self.df.index)]
    self.initial_capital = initial_capital
    self.positions = pd.DataFrame(index=signals.index).fillna(0.0)
    self.max_position_size = max_position_size
    self.stop_loss = stop_loss
    self.conditions = conditions
    self.stop_loss_levels = None
    self.portfolio_value = None
    self.portfolio_returns = None
    self.portfolio_risk = None
    self.results=None

#this section applies conditions for buying, selling, closes
def generate_trades(self):
    self.positions['buy'] = np.where(self.conditions['buy'], 1000 / self.df['close'], 0)
    self.positions['sell'] = np.where(self.conditions['sell'], -1000 / self.df['close'], 0)
    self.positions = self.positions.where(self.conditions['close'], 0)

"""
conditions = {
    'buy': (self.signals['signal_rsi_oversold'] == 1) & (self.signals['signal_stochastic_oversold'] == 1),
    'sell': (self.signals['signal_rsi_overbought'] == 1) & (self.signals['signal_stochastic_overbought'] == 1),
    'close': self.df['close'] > self.stop_loss_levels
}"""

def calculate_exposure_time(self):
    self.positions['open_time'] = np.where(self.positions['buy'] > 0, self.df['date'], np.nan)
    self.positions['close_time'] = np.where(self.positions['sell'] > 0, self.df['date'], np.nan)
    self.positions['exposure_time'] = self.positions['close_time'] - self.positions['open_time']

def backtest(self):
    self.generate_trades()
    #self.positions['buy'] = np.where(self.signals[buys].sum(axis=1) > 0, 1000 / self.df['close'], 0)
    #self.positions['sell'] = np.where(self.signals[sells].sum(axis=1) > 0, -1000 / self.df['close'], 0)
    portfolio = self.positions.multiply(self.df['close'], axis=0)
    pos_diff = self.positions.diff()
    portfolio['holdings'] = (self.positions.multiply(self.df['close'], axis=0)).sum(axis=1)
    portfolio['cash'] = self.initial_capital - (pos_diff.multiply(self.df['close'], axis=0)).sum(axis=1).cumsum()
    portfolio['total'] = portfolio['cash'] + portfolio['holdings']
    portfolio['returns'] = portfolio['total'].pct_change()
    self.results = portfolio

    # Calculate the average exposure time
    average_exposure_time = self.positions['exposure_time'].mean()

    # Calculate the Sharpe ratio
    sharpe_ratio = np.sqrt(252) * (self.results['returns'].mean() / self.results['returns'].std())

    # Calculate the maximum drawdown
    max_dd = (self.results['total'].cummax() - self.results['total']).max()

    # Calculate the maximum drawdown duration
    max_dd_duration = (self.results['total'].cummax() - self.results['total']).argmax()

    # Calculate the profit factor
    profit_factor = (self.results[self.results['returns'] > 0]['returns'].sum() / abs(self.results[self.results['returns'] < 0]['returns'].sum()))

    # Calculate the average loss and average profit
    trades = self.results[self.results['returns'] != 0]['returns']
    average_loss = trades[trades < 0].mean()
    average_profit = trades[trades > 0].mean()

    # Calculate the Calmar ratio
    calmar_ratio = self.results['returns'].mean() / max_dd

    # Calculate the number of trades taken
    num_trades = trades.count()

    # Calculate the number of winning trades and losing trades
    num_winning_trades = 0
    num_losing_trades = 0
    for i, row in self.results.iterrows():
        if row['returns'] > 0:
            num_winning_trades += 1
        elif row['returns'] < 0:
            num_losing_trades += 1

    # Calculate the win/loss ratio
    win_loss_ratio = num_winning_trades / num_losing_trades

    self.statistics = {
        'calmar_ratio': calmar_ratio,
        'sharpe_ratio': sharpe_ratio,
        'max_drawdown': max_dd,
        'max_drawdown_duration': max_dd_duration,
        'profit_factor': profit_factor,
        'average_loss': average_loss,
        'average_profit': average_profit,
        'num_trades': num_trades,
        'num_winning_trades':num_winning_trades,
        'num_losing_trades':num_losing_trades,
        'win_loss_ratio':win_loss_ratio,
        'exposure_time': average_exposure_time
    }

I also have this code that I'm trying to use to analyse results. I'm not sure how to integrate:

def backtest_by_trade(self, buys, sells):
# Initialize a dictionary to store the results for each trade
self.results_by_trade = {}
# Iterate over the combinations of buy and sell values
for buy in buys:
    for sell in sells:
        # Create a copy of the signals dataframe
        signals = self.signals.copy()
        # Update the signals dataframe with the buy and sell values
        signals['buy'] = np.where(signals['signal_rsi_oversold'] == 1, buy, 0)
        signals['sell'] = np.where(signals['signal_rsi_overbought'] == 1, sell, 0)
        # Create a new Backtest object using the updated signals dataframe
        bt = Backtest(self.df, signals, initial_capital=10000)
        # Run the backtest
        bt.backtest()
        # Store the results in the results_by_trade dictionary
        self.results_by_trade[(buy, sell)] = bt.results

# Calculate the profit or loss for each trade
self.results_by_trade['profit_loss'] = self.results_by_trade['total_profit'] - self.results_by_trade['total_loss']
# Calculate the return on investment for each trade
self.results_by_trade['return_on_investment'] = self.results_by_trade['total_profit'] / self.results_by_trade['total_loss']
# Calculate the profit factor for each trade
self.results_by_trade['profit_factor'] = self.results_by_trade['total_profit'] / abs(self.results_by_trade['total_loss'])
# Calculate the percentage of profitable trades for each combination
self.results_by_trade['percent_profitable'] = self.results_by_trade['num_winning_trades'] / self.results_by_trade['num_trades']
# Calculate the average profit per trade for each combination
self.results_by_trade['avg_profit_per_trade'] = self.results_by_trade['total_profit'] / self.results_by_trade['num_winning_trades']
# Calculate the average loss per trade for each combination
self.results_by_trade['avg_loss_per_trade'] = self.results_by_trade['total_loss'] / self.results_by_trade['num_losing_trades']
# Calculate the maximum consecutive winning trades for each combination
self.results_by_trade['max_consecutive_winning_trades'] = self.results_by_trade['consecutive_winning_trades'].max()
# Calculate the maximum consecutive losing trades for each combination
self.results_by_trade['max_consecutive_losing_trades'] = self.results_by_trade['consecutive_losing_trades'].max()
# Calculate the average consecutive winning trades for each combination
self.results_by_trade['avg_consecutive_winning_trades']

In the end, i want to use different combinations of the condictions dictionary and analyse what might be the best combination of signals. How can i do this ?


问:
Readable file with the right owner
A script which has to read a file with different owners

I have a php script which has to read a txt file. The script and the file are in different path on linux and have different owners.

The php script has apache:apache as owners, while the txt file has mis_admins:portalemis.

Unfortunately the txt file is generated automatically from another script (that I can't change it) and it's refreshing every 5 minutes. The rights on this file are only: -rw-------

The portion of the script which uses the file is the following function:

```<code>function readfilelinux($file,$azione)
{
    $buffer= '';
    $inizio='';
    $i = 1;
        $contarighe='0';
        $agent='';
        $arrFile= array();

    if( file_exists( $file ) && is_readable( $file ) )
    {
        $fp = fopen( $file, 'r' );
        while (!feof ($fp) )
        {
                $tempstr = stream_get_line( $fp, 1024,"\n" );
                        $arrFile[$contarighe] = $tempstr;
                        $contarighe=$contarighe+1;
        }
        fclose($fp);
                return $arrFile;
    }
    else
    {
       return "FNT";
    }
}
</code>```

But it returns always FNT because of the different owners.

I tried to change the txt file's owners to apache:apache and it works, but as said before it never updated anymore because the other script uses mis_admin:portalemis.

Is there a way to let the file readable, maybe including owner apache into group portalemis... or what else?

Title: Readable file with the right owner

Body:
A script which has to read a file with different owners

I have a php script which has to read a txt file. The script and the file are in different path on linux and have different owners.

The php script has apache:apache as owners, while the txt file has mis_admins:portalemis.

Unfortunately the txt file is generated automatically from another script (that I can't change it) and it's refreshing every 5 minutes. The rights on this file are only: -rw-------

The portion of the script which uses the file is the following function:

function readfilelinux($file,$azione)
{
    $buffer= '';
    $inizio='';
    $i = 1;
        $contarighe='0';
        $agent='';
        $arrFile= array();

    if( file_exists( $file ) && is_readable( $file ) )
    {
        $fp = fopen( $file, 'r' );
        while (!feof ($fp) )
        {
                $tempstr = stream_get_line( $fp, 1024,"\n" );
                        $arrFile[$contarighe] = $tempstr;
                        $contarighe=$contarighe+1;
        }
        fclose($fp);
                return $arrFile;
    }
    else
    {
       return "FNT";
    }
}

But it returns always FNT because of the different owners.

I tried to change the txt file's owners to apache:apache and it works, but as said before it never updated anymore because the other script uses mis_admin:portalemis.

Is there a way to let the file readable, maybe including owner apache into group portalemis... or what else?


问:
How can I insert a progress bar in this code with python zipfile?
im trying to give a progress bar to this code with zipfile module:

```<code>object = zipfile.ZipFile(name, 'w', zipfile.ZIP_LZMA)
object.write(f'{self.dir}\\{new_archive}')
os.remove(f"{self.dir}\\{new_archive}")
</code>```

How can I do this?
ps: this function runs in other threads

I tried with TQDM but without success.

edit: How can I measure zipfile module wait time while zipping?

Body:
im trying to give a progress bar to this code with zipfile module:

object = zipfile.ZipFile(name, 'w', zipfile.ZIP_LZMA)
object.write(f'{self.dir}\\{new_archive}')
os.remove(f"{self.dir}\\{new_archive}")

How can I do this?
ps: this function runs in other threads

I tried with TQDM but without success.

edit: How can I measure zipfile module wait time while zipping?


问:
Specific URL parameter leads to "You don't have permission to access this resource"
Very confusing one this...

On the test subdomain only (so NOT on live), any URL which has parameters including %20desc returns the error:

Forbidden
You don't have permission to access this resource.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
```

Doesn't seem to be anything to do with the actual content of the page... I can literally put up a one line text file containing only "Hello" up in a page and it happens:

vs

and it works fine on my live www subdomain:

The test subdomain is on the same linux server... it's literally just in a parallel folder with an identical copy of the site.

Absolutely baffled... anybody?

*Additional thing I've noticed if it helps... it doesn't need the whole "%20desc" to break it... it's down to the presence of just "0desc".  Other similar values such as "%20asc" do not cause the problem... just "0desc".

Body:
Very confusing one this...

On the test subdomain only (so NOT on live), any URL which has parameters including %20desc returns the error:

Forbidden
You don't have permission to access this resource.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Doesn't seem to be anything to do with the actual content of the page... I can literally put up a one line text file containing only "Hello" up in a page and it happens:

vs

and it works fine on my live www subdomain:

The test subdomain is on the same linux server... it's literally just in a parallel folder with an identical copy of the site.

Absolutely baffled... anybody?

*Additional thing I've noticed if it helps... it doesn't need the whole "%20desc" to break it... it's down to the presence of just "0desc".  Other similar values such as "%20asc" do not cause the problem... just "0desc".


问:
Expo: No native splash screen registered for provided activity. Please configure your application's main Activity to call 'SplashScreen.show'
Unhandled promise rejection: Error: No native splash screen registered for given view controller. Call 'SplashScreen.show' for given view controller first. (https://github.com/expo/expo/tree/main/packages/expo-splash-screen#-configure-android).

I get the following warning only on my android emulator when launching the app.

My Expo SDK is 47 and my React Native version is 0.70.5.

App.tsx

```<code>import React, { useCallback } from 'react';
import {ThemeProvider} from 'styled-components'

import { View } from 'react-native';

import { Routes } from './src/routes';
import { AppProvider } from './src/hooks';

import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';

import {
  Roboto_300Light,
  Roboto_400Regular,
  Roboto_500Medium,
  Roboto_700Bold,
 } from '@expo-google-fonts/roboto';

SplashScreen.preventAutoHideAsync();

export default function App() {

  const [fontsLoaded] = Font.useFonts({
    Roboto_300Light, Roboto_400Regular, Roboto_500Medium, Roboto_700Bold
  })

  const onLayout = useCallback(async () => {
    if(fontsLoaded){
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded])

  if(!fontsLoaded){
    return null;
  }

  return (
    <View style={{flex:1}} onLayout={onLayout}>
      <ThemeProvider theme={theme}>
        <AppProvider>
          <Routes />
        </AppProvider>
      </ThemeProvider>
    </View>
  )
}
</code>```

This warning is currently showing in the Android build.
iOS is working fine.

Body:
Unhandled promise rejection: Error: No native splash screen registered for given view controller. Call 'SplashScreen.show' for given view controller first. (https://github.com/expo/expo/tree/main/packages/expo-splash-screen#-configure-android).

I get the following warning only on my android emulator when launching the app.

My Expo SDK is 47 and my React Native version is 0.70.5.

App.tsx

import React, { useCallback } from 'react';
import {ThemeProvider} from 'styled-components'

import { View } from 'react-native';

import { Routes } from './src/routes';
import { AppProvider } from './src/hooks';

import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';

import {
  Roboto_300Light,
  Roboto_400Regular,
  Roboto_500Medium,
  Roboto_700Bold,
 } from '@expo-google-fonts/roboto';

SplashScreen.preventAutoHideAsync();

export default function App() {

  const [fontsLoaded] = Font.useFonts({
    Roboto_300Light, Roboto_400Regular, Roboto_500Medium, Roboto_700Bold
  })

  const onLayout = useCallback(async () => {
    if(fontsLoaded){
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded])

  if(!fontsLoaded){
    return null;
  }

  return (
    <View style={{flex:1}} onLayout={onLayout}>
      <ThemeProvider theme={theme}>
        <AppProvider>
          <Routes />
        </AppProvider>
      </ThemeProvider>
    </View>
  )
}

This warning is currently showing in the Android build.
iOS is working fine.


问:
I can not recreate thread competing effect
I read, in many many articles, that multiple threads will "compete" for the same resource and try to recreate it with the following code:

```<code>    static void Main(string[] args)
    {
        List<int> list = new List<int>();

        Thread t1 = new Thread(thread1);
        t1.IsBackground = true;
        t1.Start();

        Thread t2 = new Thread(thread2);
        t2.IsBackground = true;
        t2.Start();

        Thread.Sleep(3000);
        foreach(int i in list)
        {
            Console.WriteLine(i);
        }
        Console.ReadLine();

        void thread1()
        {
            for (int i = 0; i < 10000; i++)
            {
                list.Add(i);
            }
        }

        void thread2()
        {
            for (int i = 10000; i < 20000; i++)
            {
                list.Add(i);
            }
        }
    }
</code>```

But the result is still very "nice and neat" in order (from 0 to 19999), what did I do wrong?

Body:
I read, in many many articles, that multiple threads will "compete" for the same resource and try to recreate it with the following code:

    static void Main(string[] args)
    {
        List<int> list = new List<int>();

        Thread t1 = new Thread(thread1);
        t1.IsBackground = true;
        t1.Start();

        Thread t2 = new Thread(thread2);
        t2.IsBackground = true;
        t2.Start();

        Thread.Sleep(3000);
        foreach(int i in list)
        {
            Console.WriteLine(i);
        }
        Console.ReadLine();

        void thread1()
        {
            for (int i = 0; i < 10000; i++)
            {
                list.Add(i);
            }
        }

        void thread2()
        {
            for (int i = 10000; i < 20000; i++)
            {
                list.Add(i);
            }
        }
    }

But the result is still very "nice and neat" in order (from 0 to 19999), what did I do wrong?


问:
Model extends Authenticatable and does not retrieve data from users table
in my Laravel 9 project, the model does not retrieve users' data from the table, probably because it extends authenticatable instead of Model. and when I changed that, the authentication did not work.
Here is my model:

```<code><?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
?>
</code>```

I tried the controller and view code on another model and it worked.
what would the problem be?

I was trying to display records of users table but it keeps giving me the error Undefined variable $users.
I'm using Route::resource

Body:
in my Laravel 9 project, the model does not retrieve users' data from the table, probably because it extends authenticatable instead of Model. and when I changed that, the authentication did not work.
Here is my model:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
?>

I tried the controller and view code on another model and it worked.
what would the problem be?

I was trying to display records of users table but it keeps giving me the error Undefined variable $users.
I'm using Route::resource


问:
Symfony 6 - Class declared in services.yaml not found
I have a problem with registering a class as a service in services.yaml.

I have created a class MenuBuilder.php in Symfony 6 that looks somewhat like this.

src/Menu/MenuBuilder.php

namespace App\Menu;

class MenuBuilder
{

    public function createMainMenu(array $options)
    {
       // method logic
    }

}
```
<p>Now, when I want to register it as a service: <em>(and use it in twig with KnpMenuBundle)</em></p>
<h2>config/services.yaml</h2>
```parameters:

services:

  _defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

  App\:
    resource: '../src/'
    exclude:
      - '../src/DependencyInjection/'
      - '../src/Entity/'
      - '../src/Kernel.php'

  app.menu_builder:
    class: App\Menu\MenuBuilder
    arguments: [ "@knp_menu.factory" ]
    tags:
      - { name: knp_menu.menu_builder, method: createMainMenu, alias: main }

```
<p>I get an error <code>Class "App\Menu\MenuBuilder" not found.</code></p>
<p>I tried making some other classes (ex. <code>Test/TestClass</code>) and namespaces and it doesn't work with freshly created classes.</p>
<p>On the other hand it i fiddled around with the naming and it recognized my entities and factories.</p>
<ol>
<li>I tried clearing the cache</li>
<li>I am in development mode</li>
<li>I am getting this message when calling {{ knp_menu_render('main') }} in twig.</li>
</ol>
<p>My composer autoload:</p>
```    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
```
<p><code>symfony console debug:container app.menubuilder</code> gives me this:</p>
```Information for Service "app.menu_builder"
==========================================

 ---------------- -------------------------------------------------------------
  Option           Value
 ---------------- -------------------------------------------------------------
  Service ID       app.menu_builder
  Class            App\Menu\MenuBuilder
  Tags             knp_menu.menu_builder (method: createMainMenu, alias: main)
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         no
  Autowired        yes
  Autoconfigured   yes
  Usages           knp_menu.menu_provider.lazy
 ---------------- -------------------------------------------------------------

 ! [NOTE] The "app.menu_builder" service or alias has been removed or inlined when the container was compiled.
```

How do i get Symfony to recognize my classses?

Body:
I have a problem with registering a class as a service in services.yaml.

I have created a class MenuBuilder.php in Symfony 6 that looks somewhat like this.

src/Menu/MenuBuilder.php

namespace App\Menu;

class MenuBuilder
{

    public function createMainMenu(array $options)
    {
       // method logic
    }

}

Now, when I want to register it as a service: (and use it in twig with KnpMenuBundle)

config/services.yaml

parameters:

services:

  _defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

  App\:
    resource: '../src/'
    exclude:
      - '../src/DependencyInjection/'
      - '../src/Entity/'
      - '../src/Kernel.php'

  app.menu_builder:
    class: App\Menu\MenuBuilder
    arguments: [ "@knp_menu.factory" ]
    tags:
      - { name: knp_menu.menu_builder, method: createMainMenu, alias: main }

I get an error Class "App\Menu\MenuBuilder" not found.

I tried making some other classes (ex. Test/TestClass) and namespaces and it doesn't work with freshly created classes.

On the other hand it i fiddled around with the naming and it recognized my entities and factories.

I tried clearing the cache

I am in development mode

I am getting this message when calling {{ knp_menu_render('main') }} in twig.

My composer autoload:

    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },

symfony console debug:container app.menubuilder gives me this:

Information for Service "app.menu_builder"
==========================================

 ---------------- -------------------------------------------------------------
  Option           Value
 ---------------- -------------------------------------------------------------
  Service ID       app.menu_builder
  Class            App\Menu\MenuBuilder
  Tags             knp_menu.menu_builder (method: createMainMenu, alias: main)
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         no
  Autowired        yes
  Autoconfigured   yes
  Usages           knp_menu.menu_provider.lazy
 ---------------- -------------------------------------------------------------

 ! [NOTE] The "app.menu_builder" service or alias has been removed or inlined when the container was compiled.

How do i get Symfony to recognize my classses?