问:
Bulk FindOrCreate in Sequelize?
Is it possible for me to use findOrCreate for multiple rows instead of just one? Whenever I tried finding multiple rows it only returned one

```<code>let a = model.findOrCreate({
        where: {
            ID: ["216","2809"]
        },
    })
</code>```

in this case, a[0] is the row for "212" and a[1] is a boolean instead of the row for "2809"

Title: Bulk FindOrCreate in Sequelize?

Body:
Is it possible for me to use findOrCreate for multiple rows instead of just one? Whenever I tried finding multiple rows it only returned one

let a = model.findOrCreate({
        where: {
            ID: ["216","2809"]
        },
    })

in this case, a[0] is the row for "212" and a[1] is a boolean instead of the row for "2809"


来源: stackexchange

问:
Android Appium unable to resolve Snackbar?
Android community!

On THIS post a similar question was asked, no working solution found. It is dead for over 4 years now. I am wondering if anything changed in this topic, maybe we could share our experience once again.

I would like to ask a question if anyone found out the way to obtain Android Snackbar presence and validate it was shown with Appium engine?

 I can't post any comments to current answers because of lack of reputation points (new account), I cannot post a new answer because repeating the same question won't be considered as valid answer. So the only way to ask is to create new topic here.

Appium version: "io.appium:java-client:7.6.0"

Automation: UIAutomator2

I was trying to use several methods to fetch the Snackbar elements or to find it by text displayed but all of them failed.

Tracking down Snackbar presence using XPATH - FAILED

```<code>fun verifySnackbarShown(textDisplayed: String, timeOutSeconds: Long = 10, sleepTimeMillis: Long = 100) {
    val wait = WebDriverWait(driver, timeOutSeconds, sleepTimeMillis).ignoring(NoSuchElementException::class.java)
    val element = wait.until(ExpectedConditions.presenceOfElementLocated(
        By.xpath("//*[@text='$textDisplayed']"))
    )
    Assert.assertNotNull(element)
}
</code>```

Searching by ID's of Snackbar's layout elements - FAILED

```<code>wait.until(ExpectedConditions.presenceOfElementLocated(
    By.id("com.google.android.material:id/snackbar_action"))
)

wait.until(ExpectedConditions.presenceOfElementLocated(
    By.id("com.google.android.material:id/snackbar_text"))
)
</code>```

Does anyone know how we can get this view correctly verified?

ContentLicense: CC BY-SA 4.0

Body:
Android community!

On THIS post a similar question was asked, no working solution found. It is dead for over 4 years now. I am wondering if anything changed in this topic, maybe we could share our experience once again.

I would like to ask a question if anyone found out the way to obtain Android Snackbar presence and validate it was shown with Appium engine?

 I can't post any comments to current answers because of lack of reputation points (new account), I cannot post a new answer because repeating the same question won't be considered as valid answer. So the only way to ask is to create new topic here.

Appium version: "io.appium:java-client:7.6.0"

Automation: UIAutomator2

I was trying to use several methods to fetch the Snackbar elements or to find it by text displayed but all of them failed.

Tracking down Snackbar presence using XPATH - FAILED

fun verifySnackbarShown(textDisplayed: String, timeOutSeconds: Long = 10, sleepTimeMillis: Long = 100) {
    val wait = WebDriverWait(driver, timeOutSeconds, sleepTimeMillis).ignoring(NoSuchElementException::class.java)
    val element = wait.until(ExpectedConditions.presenceOfElementLocated(
        By.xpath("//*[@text='$textDisplayed']"))
    )
    Assert.assertNotNull(element)
}

Searching by ID's of Snackbar's layout elements - FAILED

wait.until(ExpectedConditions.presenceOfElementLocated(
    By.id("com.google.android.material:id/snackbar_action"))
)

wait.until(ExpectedConditions.presenceOfElementLocated(
    By.id("com.google.android.material:id/snackbar_text"))
)

Does anyone know how we can get this view correctly verified?


问:
classes instantiated by cmd line arg import conflicts
I have a dictionary data structure holding two classes where the key is a string representing the argument I am passing to my app.py and the value is the actual class, in the following format

```<code>from my package import ClassA
from my_other_package import ClassB
from my_other_package import ClassZ
DICT = {
    "class_a": ClassA
    "class_b": ClassB
    ...
    "class_z": ClassZ
</code>```

In my app.py I have a logic in place which performs a callback and returns within app.py, the class instantiated after the argument is taken and parsed from command line.
So when i execute the following command i get my object created.

python3 app.py class_a

Now the problem is the following: since my data structure holds both classes definitions (and will certainty grow to support different use cases), when the DICT{} is imported in the app.py and initialized, both ClassA and ClassB dependencies are checked on runtime.

Let's say for example that ClassA includes an import error due to a pip dependency not defined also ClassB will be affected and will not be initialized, returning an import error due to a missing pip library installed, but for the other class which is not involved in the current setup.

Eventually, I would like still to be able to instantiate classes using the following logic dynamically, but I would also like to be able to split it in a way that ClassA and ClassB would not affect each other from whatever runtime error would occur.

I thought if the namespace topic could come into the game and a different approach would help to solve the issue, as well as creating an ad-hoc import strategy using __ init __.py or also completely reworking the structure but I can't figure out an optimal way
Any idea how I could do that?

Body:
I have a dictionary data structure holding two classes where the key is a string representing the argument I am passing to my app.py and the value is the actual class, in the following format

from my package import ClassA
from my_other_package import ClassB
from my_other_package import ClassZ
DICT = {
    "class_a": ClassA
    "class_b": ClassB
    ...
    "class_z": ClassZ

In my app.py I have a logic in place which performs a callback and returns within app.py, the class instantiated after the argument is taken and parsed from command line.
So when i execute the following command i get my object created.

python3 app.py class_a

Now the problem is the following: since my data structure holds both classes definitions (and will certainty grow to support different use cases), when the DICT{} is imported in the app.py and initialized, both ClassA and ClassB dependencies are checked on runtime.

Let's say for example that ClassA includes an import error due to a pip dependency not defined also ClassB will be affected and will not be initialized, returning an import error due to a missing pip library installed, but for the other class which is not involved in the current setup.

Eventually, I would like still to be able to instantiate classes using the following logic dynamically, but I would also like to be able to split it in a way that ClassA and ClassB would not affect each other from whatever runtime error would occur.

I thought if the namespace topic could come into the game and a different approach would help to solve the issue, as well as creating an ad-hoc import strategy using __ init __.py or also completely reworking the structure but I can't figure out an optimal way
Any idea how I could do that?


问:
Setting up a subdomain to use both www and non-www
I have www.mydomain.com and mydomain.com both working. Now, the subdomain sub.mydomain.com also works well; but not www.sub.mydomain.com.

I've tried adding A records for for www.app; but not working.

I've also tried creating a CNAME record "www.app" for mydomain.com; but also not working.

Browser throws a NET::ERR_CERT_COMMON_NAME_INVALID for both.

Any suggestions?


问:
Can I assert that certain Http requests were made BEFORE or AFTER other Http requests in an Xunit unit test?
I have a simple Xunit project setup to test my code. During the method under test, I make two, separate, consecutive Http requests to an endpoint on the network. My test should check that the first Http request is always made BEFORE the second Http request. Is this possible? Here is what the test looks like. I just need to check if the request with request.AbsolutelUri.EndsWith("Some-Request-1") is made before the subsequent request, ("Some-Request-2).

[Fact]
public async Task HttpRequestMessage1_IsMade_Before_HttpRequest2()
{
    //Arrange
    var builder = new TestClassBuilder();

    var handlerMock = new Mock<HttpMessageHandler>();
    var mockData = fixture.Create<List<string>>();

    var httpClient = new HttpClient(handlerMock.Object);
    var cache = await IMemoryCacheInstance();
    var mapper = new Mock<IMapper>();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-1")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.OK,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-2")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    var testClass = builder.WithHttpClient(httpClient)
                           .WithMemoryCache(cache)
                           .WithMapper(mapper.Object)
                           .Build();

    //Act
    var result = await testClass.DoSomething(It.IsAny<string>());

    //Assert
    result.Should().NotBeNull();
}
```

I have not tried anything yet. I have not found a solution. The Assert statement is simply placeholder.

Body:
I have a simple Xunit project setup to test my code. During the method under test, I make two, separate, consecutive Http requests to an endpoint on the network. My test should check that the first Http request is always made BEFORE the second Http request. Is this possible? Here is what the test looks like. I just need to check if the request with request.AbsolutelUri.EndsWith("Some-Request-1") is made before the subsequent request, ("Some-Request-2).

[Fact]
public async Task HttpRequestMessage1_IsMade_Before_HttpRequest2()
{
    //Arrange
    var builder = new TestClassBuilder();

    var handlerMock = new Mock<HttpMessageHandler>();
    var mockData = fixture.Create<List<string>>();

    var httpClient = new HttpClient(handlerMock.Object);
    var cache = await IMemoryCacheInstance();
    var mapper = new Mock<IMapper>();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-1")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.OK,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-2")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    var testClass = builder.WithHttpClient(httpClient)
                           .WithMemoryCache(cache)
                           .WithMapper(mapper.Object)
                           .Build();

    //Act
    var result = await testClass.DoSomething(It.IsAny<string>());

    //Assert
    result.Should().NotBeNull();
}

I have not tried anything yet. I have not found a solution. The Assert statement is simply placeholder.


问:
GGPlot Dual Axis Line Chart in r
I am attempting to generate a dual axis plot. I have successfully generated a secondary axis on the correct scale, but I cannot get both geom_lines to plot.

The code below plots the primary plot on the left axis, but the secondary plot (emp) is not displayed (or is still scaled to the primary axis so it doesn't show).

```<code>ggplot(data, aes(x=month, y=Amount, colour ='Expenses')) +
      geom_line() +  geom_smooth(method='lm',show.legend =TRUE, se = FALSE, aes(y=Amount,  colour='Trend'))+
      geom_line(aes(y=per_emp, colour='per_emp'))+
     geom_smooth(method='lm',show.legend =TRUE, se = FALSE,aes(y=per_emp, colour='trend'))+
      scale_y_continuous(
        # Features of the first axis
        name = "First Axis",
        # Add a second axis and specify its features
        sec.axis = sec_axis(~./max(data$per_emp), name="Second Axis"), )+
      scale_colour_manual(
        name = ("Legend"),
        values = c("Expenses" = "black", 'Trend' = 'blue', 'trend' = 'green', 'per_emp'='red'))
</code>```

I have seen recommendations for creating a formula to set the secondary axis, so I have tried that as well, and received similar results.

```<code>ylim.prim <- c(0,6000000)   # in this example, precipitation
ylim.sec <- c(0, 7000)    # in this example, temperature

b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])

ggplot(data, aes(x=month, y=Amount, colour ='ex')) +
      geom_line() +  geom_smooth(method='lm',show.legend =TRUE, se = FALSE, aes(y=Amount,  colour='Trend'))+
      geom_line(aes(y=per_emp, colour='emp'))+
     geom_smooth(method='lm',show.legend =TRUE, se = FALSE,aes(y=per_emp, colour='trend'))+
      scale_y_continuous(
        # Features of the first axis
        name = "First Axis",
        # Add a second axis and specify its features
        sec.axis = sec_axis(~ (. - a)/b, name="Second Axis"), )+
      scale_colour_manual(
        name = ("Legend"),
        values = c("ex" = "black", 'Trend' = 'blue', 'trend' = 'green', 'emp'='red'))
</code>```

Any recommendations to get the per_emp field to plot on the secondary access, as well as the trend line for that plot?

Title: GGPlot Dual Axis Line Chart in r

Body:
I am attempting to generate a dual axis plot. I have successfully generated a secondary axis on the correct scale, but I cannot get both geom_lines to plot.

The code below plots the primary plot on the left axis, but the secondary plot (emp) is not displayed (or is still scaled to the primary axis so it doesn't show).

ggplot(data, aes(x=month, y=Amount, colour ='Expenses')) +
      geom_line() +  geom_smooth(method='lm',show.legend =TRUE, se = FALSE, aes(y=Amount,  colour='Trend'))+
      geom_line(aes(y=per_emp, colour='per_emp'))+
     geom_smooth(method='lm',show.legend =TRUE, se = FALSE,aes(y=per_emp, colour='trend'))+
      scale_y_continuous(
        # Features of the first axis
        name = "First Axis",
        # Add a second axis and specify its features
        sec.axis = sec_axis(~./max(data$per_emp), name="Second Axis"), )+
      scale_colour_manual(
        name = ("Legend"),
        values = c("Expenses" = "black", 'Trend' = 'blue', 'trend' = 'green', 'per_emp'='red'))

I have seen recommendations for creating a formula to set the secondary axis, so I have tried that as well, and received similar results.

ylim.prim <- c(0,6000000)   # in this example, precipitation
ylim.sec <- c(0, 7000)    # in this example, temperature

b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])

ggplot(data, aes(x=month, y=Amount, colour ='ex')) +
      geom_line() +  geom_smooth(method='lm',show.legend =TRUE, se = FALSE, aes(y=Amount,  colour='Trend'))+
      geom_line(aes(y=per_emp, colour='emp'))+
     geom_smooth(method='lm',show.legend =TRUE, se = FALSE,aes(y=per_emp, colour='trend'))+
      scale_y_continuous(
        # Features of the first axis
        name = "First Axis",
        # Add a second axis and specify its features
        sec.axis = sec_axis(~ (. - a)/b, name="Second Axis"), )+
      scale_colour_manual(
        name = ("Legend"),
        values = c("ex" = "black", 'Trend' = 'blue', 'trend' = 'green', 'emp'='red'))

Any recommendations to get the per_emp field to plot on the secondary access, as well as the trend line for that plot?


问:
Can I make an ngFor repeath specifict times of an array? Ionic
I have an ion-list that shows n objects of an array.
I'm using *ngFor to show them.
The problem is that the array will have n quantity of objects.It could be 10 objects or 2000. I would like to show the first 30 objects, then, use an infinite scroll and show the next 30.
How could I do it? This is my code:</p>
```<code>    <div *ngFor="let key of objectKeys(message)">
      <ion-card class="{{val.Status}}" *ngFor="let val of message[key]">
        <ion-card-header class="headerClass">
          <ion-row>
            <ion-col size="11"><ion-label class="titulo">{{val.Permiso}}</ion-label></ion-col>
            <ion-col *ngIf="val?.Status == 'Autorizado'" size="1" ><ion-icon color="success" style="zoom:1.5;" name="checkmark-circle-outline"></ion-icon></ion-col>
            <ion-col *ngIf="val?.Status == 'Rechazado'" size="1"><ion-icon color="danger" style="zoom:1.5;" name="close-circle-outline"></ion-icon></ion-col>
            <ion-col *ngIf="val?.Status == 'Pendiente'" size="1"><ion-icon color="warning" style="zoom:1.5;" name="help-circle-outline"></ion-icon></ion-col>
          </ion-row>
        </ion-card-header>
        <ion-card-content>
          <ion-row>
            <ion-col size="12" ><b>Fecha de inicio: </b> {{val.FechaInicio | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col *ngIf="val?.FechaFin != null" size="12" ><b>Fecha de termino: </b> {{val.FechaFin | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col size="6"><b>Hora de inicio:</b> {{val.HoraInicio}}</ion-col>
            <ion-col  size="6"><b>Hora termino:</b> {{val.HoraFin}}</ion-col>
          </ion-row>
          <ion-row *ngIf="val?.FechaReanudacion != null">
            <ion-col size="12" ><b>Fecha reanudacion: </b> {{val.FechaReanudacion | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col *ngIf="val?.Status == 'Rechazado'"  size="12" ><b>Motivo:</b> {{val.Comentarios}}</ion-col>
          </ion-row>
        </ion-card-content>
      </ion-card>
    </div>
  </div>

This is how a fill my array:

MisPermisos(datos){
    this.proveedor.MostrarPermisos(datos).subscribe(
      async (dataReturnFromService2)=>{
        this.dataFromService2 = (dataReturnFromService2);
        let obj2 = JSON.parse(this.dataFromService2);
        if((dataReturnFromService2) == '{"Table":[]}'){
          this.noHayPermisos();
        }
        else{
          this.messages = [obj2] ;
          this.keys = Object.keys([obj2]);
          this.prueba = (obj2.Table[0].Status);
        }
      }
    )
  }
</code>```

Body:
I have an ion-list that shows n objects of an array.
I'm using *ngFor to show them.
The problem is that the array will have n quantity of objects.It could be 10 objects or 2000. I would like to show the first 30 objects, then, use an infinite scroll and show the next 30.
How could I do it? This is my code:

      <ion-card class="{{val.Status}}" *ngFor="let val of message[key]">
        <ion-card-header class="headerClass">
          <ion-row>
            <ion-col size="11"><ion-label class="titulo">{{val.Permiso}}</ion-label></ion-col>
            <ion-col *ngIf="val?.Status == 'Autorizado'" size="1" ><ion-icon color="success" style="zoom:1.5;" name="checkmark-circle-outline"></ion-icon></ion-col>
            <ion-col *ngIf="val?.Status == 'Rechazado'" size="1"><ion-icon color="danger" style="zoom:1.5;" name="close-circle-outline"></ion-icon></ion-col>
            <ion-col *ngIf="val?.Status == 'Pendiente'" size="1"><ion-icon color="warning" style="zoom:1.5;" name="help-circle-outline"></ion-icon></ion-col>
          </ion-row>
        </ion-card-header>
        <ion-card-content>
          <ion-row>
            <ion-col size="12" >Fecha de inicio:  {{val.FechaInicio | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col *ngIf="val?.FechaFin != null" size="12" >Fecha de termino:  {{val.FechaFin | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col size="6">Hora de inicio: {{val.HoraInicio}}</ion-col>
            <ion-col  size="6">Hora termino: {{val.HoraFin}}</ion-col>
          </ion-row>
          <ion-row *ngIf="val?.FechaReanudacion != null">
            <ion-col size="12" >Fecha reanudacion:  {{val.FechaReanudacion | date: 'd/M/yyyy'}}</ion-col>
          </ion-row>
          <ion-row>
            <ion-col *ngIf="val?.Status == 'Rechazado'"  size="12" >Motivo: {{val.Comentarios}}</ion-col>
          </ion-row>
        </ion-card-content>
      </ion-card>

This is how a fill my array:

MisPermisos(datos){
    this.proveedor.MostrarPermisos(datos).subscribe(
      async (dataReturnFromService2)=>{
        this.dataFromService2 = (dataReturnFromService2);
        let obj2 = JSON.parse(this.dataFromService2);
        if((dataReturnFromService2) == '{"Table":[]}'){
          this.noHayPermisos();
        }
        else{
          this.messages = [obj2] ;
          this.keys = Object.keys([obj2]);
          this.prueba = (obj2.Table[0].Status);
        }
      }
    )
  }


问:
Set environment variable for fastAPI on Cloud RUN
I'm trying to set environment variables using docker (for fastAPI) but clod run doesn't want to see them. I tried many solutions, what would be a good way? I mention that I use the docker image in cloud run</p>


问:
xgboost classifier model performance
I've trained an xgboost classifier (on train_df) and tuned (on valid_df) and tested (on test_df). Some non-trivial observations follow. After running HyperOpt trials, I obtain the following performance with the Precision scores.

Model 1: train: 0.16, valid: 0.12, test:0.12

Model 2: train: 0.23, valid: 0.18, test:0.17

Before rushing to conclude that these two models are overfitting, can somebody tell what's happening here and what can be done to resolve it? If this is indeed overfitting is it something to worry about? I am getting consistent results in valid_df and test_df?  In addition, on an out-of-sample(i.e., unseen data) evaluation, I get a performance consistent with test_df performance. Since we care only about the test_df performance metric since it's an indication of the real performance of the model, do we need to worry about how much overfitting (if this is overfitting) the model is having on train_df? At the end of the day, test_df performance is all what matters.

Title: xgboost classifier model performance


问:
format no valid records found in tracefile using genHTML on coverage.dat generated by bazel in lcov
Team,
I am able to successfully generated the coverage.dat file but I cannot generate htlm to view the report. anything that am missing? am new to this.

./bazel coverage --combined_report=lcov //src/teams/test/...

output

```<code>Command> ./bazel coverage --combined_report=lcov //src/teams/test/...
INFO: Invocation ID: 48b15c3a-43bb-435c-97d5-e608703cc53a
INFO: Using default value for --instrumentation_filter: "^//src/teams/test/keys[/:],^//src/teams/test/server[/:],^//src/teams/test/store/postgres[/:],^//src/teams/test/tools/keyrotate[/:],^//src/teams/test/vault[/:]".
INFO: Override the above default with --instrumentation_filter
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
DEBUG: Rule 'distroless' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1564086429 -0400"
DEBUG: Repository distroless instantiated at:
  /Users/userme/code/company/git-team/product/WORKSPACE:32:20: in <toplevel>
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/external/product/wkspc/phase0.bzl:62:23: in static_repositories
Repository rule git_repository defined at:
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/external/bazel_tools/tools/build_defs/repo/git.bzl:199:33: in <toplevel>
INFO: Analyzed 33 targets (68 packages loaded, 21664 targets configured).
INFO: Found 28 targets and 5 test targets...
INFO: LCOV coverage report is located at /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/_coverage/_coverage_report.dat
 and execpath is bazel-out/_coverage/_coverage_report.dat
INFO: From Coverage report generation:
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main getTracefiles
INFO: Found 5 tracefiles.
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/vault/vault_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/server/server_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/store/postgres/postgres_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/keys/keys_test/coverage.dat
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/tools/keyrotate/keyrotate_test/coverage.dat
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getGcovInfoFiles
INFO: No gcov info file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getGcovJsonInfoFiles
INFO: No gcov json file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getProfdataFileOrNull
INFO: No .profdata file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main runWithArgs
WARNING: There was no coverage found.
INFO: Elapsed time: 65.521s, Critical Path: 52.28s
INFO: 247 processes: 25 disk cache hit, 75 internal, 146 darwin-sandbox, 1 worker.
INFO: Build completed successfully, 247 total actions
//src/teams/test/keys:keys_test                                    PASSED in 3.1s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/keys/keys_test/coverage.dat
//src/teams/test/server:server_test                                PASSED in 1.1s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/server/server_test/coverage.dat
//src/teams/test/store/postgres:postgres_test                      PASSED in 3.8s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/store/postgres/postgres_test/coverage.dat
//src/teams/test/tools/keyrotate:keyrotate_test                    PASSED in 1.3s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/tools/keyrotate/keyrotate_test/coverage.dat
//src/teams/test/vault:vault_test                                  PASSED in 2.3s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/vault/vault_test/coverage.dat

Executed 5 out of 5 tests: 5 tests pass.
INFO: Build completed successfully, 247 total actions
</code>```

genHTML output

```<code> `genhtml /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/_coverage/_coverage_report.dat`

Reading data file _coverage_report.dat
genhtml: ERROR: no valid records found in tracefile _coverage_report.dat
</code>```

i also tried this but same output.
https://bazel.build/configure/coverage
genhtml --output genhtml "$(bazel info output_path)/_coverage/_coverage_report.dat"

Body:
Team,
I am able to successfully generated the coverage.dat file but I cannot generate htlm to view the report. anything that am missing? am new to this.

./bazel coverage --combined_report=lcov //src/teams/test/...

output

Command> ./bazel coverage --combined_report=lcov //src/teams/test/...
INFO: Invocation ID: 48b15c3a-43bb-435c-97d5-e608703cc53a
INFO: Using default value for --instrumentation_filter: "^//src/teams/test/keys[/:],^//src/teams/test/server[/:],^//src/teams/test/store/postgres[/:],^//src/teams/test/tools/keyrotate[/:],^//src/teams/test/vault[/:]".
INFO: Override the above default with --instrumentation_filter
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
DEBUG: Rule 'distroless' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1564086429 -0400"
DEBUG: Repository distroless instantiated at:
  /Users/userme/code/company/git-team/product/WORKSPACE:32:20: in <toplevel>
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/external/product/wkspc/phase0.bzl:62:23: in static_repositories
Repository rule git_repository defined at:
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/external/bazel_tools/tools/build_defs/repo/git.bzl:199:33: in <toplevel>
INFO: Analyzed 33 targets (68 packages loaded, 21664 targets configured).
INFO: Found 28 targets and 5 test targets...
INFO: LCOV coverage report is located at /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/_coverage/_coverage_report.dat
 and execpath is bazel-out/_coverage/_coverage_report.dat
INFO: From Coverage report generation:
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main getTracefiles
INFO: Found 5 tracefiles.
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/vault/vault_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/server/server_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/store/postgres/postgres_test/coverage.dat
Dec 09, 2022 11:36:27 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/keys/keys_test/coverage.dat
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main parseFilesSequentially
INFO: Parsing file bazel-out/darwin-fastbuild/testlogs/src/teams/test/tools/keyrotate/keyrotate_test/coverage.dat
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getGcovInfoFiles
INFO: No gcov info file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getGcovJsonInfoFiles
INFO: No gcov json file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main getProfdataFileOrNull
INFO: No .profdata file found.
Dec 09, 2022 11:36:28 AM com.google.devtools.coverageoutputgenerator.Main runWithArgs
WARNING: There was no coverage found.
INFO: Elapsed time: 65.521s, Critical Path: 52.28s
INFO: 247 processes: 25 disk cache hit, 75 internal, 146 darwin-sandbox, 1 worker.
INFO: Build completed successfully, 247 total actions
//src/teams/test/keys:keys_test                                    PASSED in 3.1s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/keys/keys_test/coverage.dat
//src/teams/test/server:server_test                                PASSED in 1.1s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/server/server_test/coverage.dat
//src/teams/test/store/postgres:postgres_test                      PASSED in 3.8s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/store/postgres/postgres_test/coverage.dat
//src/teams/test/tools/keyrotate:keyrotate_test                    PASSED in 1.3s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/tools/keyrotate/keyrotate_test/coverage.dat
//src/teams/test/vault:vault_test                                  PASSED in 2.3s
  /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/darwin-fastbuild/testlogs/src/teams/test/vault/vault_test/coverage.dat

Executed 5 out of 5 tests: 5 tests pass.
INFO: Build completed successfully, 247 total actions

genHTML output

 `genhtml /private/var/tmp/_bazel_userme/e6e1d0cbd051dd43ed59dca5541f019d/execroot/product/bazel-out/_coverage/_coverage_report.dat`

Reading data file _coverage_report.dat
genhtml: ERROR: no valid records found in tracefile _coverage_report.dat

i also tried this but same output.
https://bazel.build/configure/coverage
genhtml --output genhtml "$(bazel info output_path)/_coverage/_coverage_report.dat"


问:
not sending the 500.html file res.sendFile(path.join(__dirname, '../public/500.html'))

This works on a macbook but I am presently using my windows computer. What am I doing wrong? Why is this not pointing to the 500.html file?

i have tried many fixes I have seen on here and none of them work.
How can i keep my code relatively the same and fix the issue?


问:
pushing element to array of arrays in js
I've got array, where every element is an empty array. When trying to execute "array[i].push(el)" instead el is pushed to every single sub array not just array[i].

```<code>let columns = new Array(data[0].length).fill([]);

data[0].split('').forEach((el, i) => {
            if (i < 5) {
                        console.log('el: ', el, 'i: ', i);
                        columns[i].push(el);
            }
});

console.log(columns);

</code>```

in this example only 5 elements of columns should not be empty, instead elements are added to every sub array as if columns[i] was somehow looping through every array inside "columns". Not sure why

Body:
I've got array, where every element is an empty array. When trying to execute "array[i].push(el)" instead el is pushed to every single sub array not just array[i].

let columns = new Array(data[0].length).fill([]);

data[0].split('').forEach((el, i) => {
            if (i < 5) {
                        console.log('el: ', el, 'i: ', i);
                        columns[i].push(el);
            }
});

console.log(columns);

in this example only 5 elements of columns should not be empty, instead elements are added to every sub array as if columns[i] was somehow looping through every array inside "columns". Not sure why


问:
When I install my app, why notification "Allow playing sound" option if always disabled by default?
When I have just installed my app, the options "Allow notification badges", "allow playing sound" and "allow using led light" are always off by default. Why? how to make those option enabled by default? I'm on android 11. I'm not sure if those options are present in all android device or just present in my android device (xiaomi) if someone can confirm me.


问:
Registering db context dynamically in Autofac
I am using Autofac to register all my classes and DbContext. I am having two connection strings and dynamically I need to choose which one to use.

```<code>public partial class DataConext: DBContext
{
  public DataContext():base("name=ConnA") { }

  public DataConext(string name):base(name) { }
  ...
}
</code>```

In Main method, I am creating Autofac DI.

here is my Main method implementation

```<code>static void Main(string[] args)
{
  var container= BuildContainer();
  using(var scope=container.BuildLifetimescope())
  {
    log=container.Resolve<ILog>();
    string dbName=args[0];
    container.Resolve<AppConfiguration>.ChangeConnection(dbName);
  }
}
Public static IContainer BuildContainer()
{
  var  builder=new ContainerBuilder();
  builder.RegisterType<Program>.AsSelf();
  builder.RegisterType<DataContext>().Instanceperlifetimescope();
  builder.RegisterType<AppConfiguration>().As<IAppConfiguration>();
  builder.RegisterType<DataContext>().AsImplementedInterfaces().InstanceperlifetimeScope();
  return builder.Build();
}
</code>```

In AppConfiguration, I am trying to pass the dbName as parameter and modify the datacontext.

```<code>public class AppConfiguration:IAppConfiguration
{
  public void ChangeConnection(string DbName)
  {
      var connectionString=ConfigurationManager.ConnectionStrings["+DbName+"].ConnectionString;
      var context=new DataContext(DbName);

      var container=Program.BuildContainer();
      var builder=new ContainerBuilder();
      builder.RegisterType<DataContext>().AsImplementedInterfaces().InstanceperLifetimeScope();
  }
}
</code>```

I am trying to update the Datacontext but the instance is not getting updated and still its pointing the default context. Please let me know how to update the datacontext every time the parameter dbName changes.

Body:
I am using Autofac to register all my classes and DbContext. I am having two connection strings and dynamically I need to choose which one to use.

public partial class DataConext: DBContext
{
  public DataContext():base("name=ConnA") { }

  public DataConext(string name):base(name) { }
  ...
}

In Main method, I am creating Autofac DI.

here is my Main method implementation

static void Main(string[] args)
{
  var container= BuildContainer();
  using(var scope=container.BuildLifetimescope())
  {
    log=container.Resolve<ILog>();
    string dbName=args[0];
    container.Resolve<AppConfiguration>.ChangeConnection(dbName);
  }
}
Public static IContainer BuildContainer()
{
  var  builder=new ContainerBuilder();
  builder.RegisterType<Program>.AsSelf();
  builder.RegisterType<DataContext>().Instanceperlifetimescope();
  builder.RegisterType<AppConfiguration>().As<IAppConfiguration>();
  builder.RegisterType<DataContext>().AsImplementedInterfaces().InstanceperlifetimeScope();
  return builder.Build();
}

In AppConfiguration, I am trying to pass the dbName as parameter and modify the datacontext.

public class AppConfiguration:IAppConfiguration
{
  public void ChangeConnection(string DbName)
  {
      var connectionString=ConfigurationManager.ConnectionStrings["+DbName+"].ConnectionString;
      var context=new DataContext(DbName);

      var container=Program.BuildContainer();
      var builder=new ContainerBuilder();
      builder.RegisterType<DataContext>().AsImplementedInterfaces().InstanceperLifetimeScope();
  }
}

I am trying to update the Datacontext but the instance is not getting updated and still its pointing the default context. Please let me know how to update the datacontext every time the parameter dbName changes.


问:
Is it possible to create some kind of virtual private cloud between my AWS apis/lambda and a non-AWS server provider?
Right now I'm using AWS lamba and AWS EC2 and I'm relying on VPC to share data between a lambda function and a server when lambda needs something from the server.

With the right settings in Secure Groups the server accepts only requests from that special lambda and I don't have to do secure the connection between the two because it's like the server and the lambda function are the only two things in their network.

But I'm trying to move my server to another provider, and this means i have to find a way to secure the server

My question: is there something like a VPC I can create between lambda and a server hosted somewhere else AWS? what kind of tecnologies do i need?

I started looking for VPNs and certificates


问:
How to create 2D array type column in pyspark using split() function?
I am currently working with df containing an array column with values, such that each element in the array is a line containing field value.

eg:

file_name
line_array

file 1
[l1,l2,l3]

file 2
[l1,l2,l3]

and "l1" value will be like: "1 100 0 0 New". The value "[1,100,0,0, New]" needs to be extracted from the line string, which is separated by a single space.

After transformation:

file_name
line_array

file 1
[[1,100,0,0,New],[values of l2],[values of l3]]

file 2
[[v1],[v2],[v3]]

how can we derive it?

I tried using the map function but I don't know how to iterate the array value or use the split function in this case
and genuinely have no idea about iterations in pyspark.

Any solutions as well as reading suggestions for better understanding are much appreciated.

P.S: the array might contain null values as well


问:
How to send zip file with bash script?
I'm able to send simple files, and I'm able to zip a file inn bash... I'm not sure how to put the two together

for context temporaryDirectory is a folder with all the files I want to send

```<code>zip attachmentt.zip "${temporaryDirectory}"/*
ATTACHMENT="attachmentt.zip.zip"

# Create message
echo '{"Data":"From:'${MAIL_ACCOUNT}'\nTO:'${recipient}'\nSubject:'${MAIL_SUBJECT}'\nMIME-Version: 1.0\nContent-type: Multipart/Mixed;boundary=\"NextPart\"\n\n--NextPart\nContent-Type: text/plain\n\n'${body}'\n\n--NextPart\nContent-Type: attachment/zip;Content-Description:'${ATTACHMENT}';Content-Disposition:attachment;filename='${ATTACHMENT}'\";Content-Transfer-Encoding:base64"}' > message.json

aws ses send-raw-email --raw-message file://message.json

</code>```

This sends the email with an attachment, but it is a blank file...

Title: How to send zip file with bash script?

Body:
I'm able to send simple files, and I'm able to zip a file inn bash... I'm not sure how to put the two together

for context temporaryDirectory is a folder with all the files I want to send

zip attachmentt.zip "${temporaryDirectory}"/*
ATTACHMENT="attachmentt.zip.zip"

# Create message
echo '{"Data":"From:'${MAIL_ACCOUNT}'\nTO:'${recipient}'\nSubject:'${MAIL_SUBJECT}'\nMIME-Version: 1.0\nContent-type: Multipart/Mixed;boundary=\"NextPart\"\n\n--NextPart\nContent-Type: text/plain\n\n'${body}'\n\n--NextPart\nContent-Type: attachment/zip;Content-Description:'${ATTACHMENT}';Content-Disposition:attachment;filename='${ATTACHMENT}'\";Content-Transfer-Encoding:base64"}' > message.json

aws ses send-raw-email --raw-message file://message.json

This sends the email with an attachment, but it is a blank file...


问:
Class based middleware triggers two handlers at once
I'm using pretty simple class-based middleware for anti-flood. If I simplify code, there are two handlers:

```<code>@bot.message_handler(commands=['start'])
    bot.send_message(message.from_user.id, "Hello!")

@bot.message_handler(content_types=['text'])
    bot.send_message(message.from_user.id, "Haven't understand you!"

</code>```

When I run it and message "/start" to my bot I receive both of this messages. And I can see that middleware have been triggered only once.

If I turn off middleware, it works fine, I receive only "Hello!" message.

Body:
I'm using pretty simple class-based middleware for anti-flood. If I simplify code, there are two handlers:

@bot.message_handler(commands=['start'])
    bot.send_message(message.from_user.id, "Hello!")

@bot.message_handler(content_types=['text'])
    bot.send_message(message.from_user.id, "Haven't understand you!"

When I run it and message "/start" to my bot I receive both of this messages. And I can see that middleware have been triggered only once.

If I turn off middleware, it works fine, I receive only "Hello!" message.


问:
Typings for a hierarchical recursive data structure
I'm trying to write typings for nested NoSQL collections. A collection can be a root collection or a sub-collection. A collection contains documents with IDs, the paths to sub-collections contain the IDs of the parent collection's documents.

The path to a collection could be accounts or for sub-collections accounts/acc-1/users. The path to a document in a sub-collection looks like this, for example accounts/acc-1/users/usr-1

The goal is to have a strongly typed class called Collection which has methods for generating collection and document paths, where the argument of those methods require the IDs passed as a map.

Is it possible to infer the types (except the type of the ID Id<>) from constructor arguments, without manually passing it as a generic to every sub-collection? I've been playing around with it for a few days now and can't get it to work.

declare const t: unique symbol;
export type Id<T> = string & { readonly [t]: T };

type DocumentIds<C extends Collection> = C extends Collection<infer IdType, infer PC, infer IdKey>
    ? { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>)
    : never;

class Collection<IdType extends string = string, PC extends Collection | void = void, IdKey extends string = string> {
   constructor(
      private readonly collectionName: string,
      private readonly idName: IdKey,
      private readonly parent?: Collection
   ) {}

   getCollectionPath(ids: PC extends void ? void : DocumentIds<PC>) {}

   getDocumentPath(ids: { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>)) {}

   parse(path: string): { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>) {
      return null as any;
   }
}

type AccountId = Id<'Account'>;
type UserId = Id<'User'>;

const AccountCollection = new Collection<AccountId>('accounts', 'accountId');

const UserCollection = new Collection<UserId>('users', 'userId', AccountCollection);

// Does not require an argument since it's a root collection
// returns 'accounts'
AccountCollection.getCollectionPath();

// Requires an argument for the document id
// returns 'accounts/acc-1'
AccountCollection.getDocumentPath({
   accountId: 'acc-1' as AccountId,
});

// Requires an argument for the parent collection
// returns 'accounts/acc-1/users'
UserCollection.getCollectionPath({
   accountId: 'acc-1' as AccountId,
});

// Requires an argument for the parent collection and the document itself
// returns 'accounts/acc-1/users/usr-1'
UserCollection.getDocumentPath({
   accountId: 'acc-1' as AccountId,
   userId: 'usr-1' as UserId,
});

// Return type should be {accountId: AccountId, userId: UserId}
// Return value {accountId: 'acc-1', userId: 'usr-1'}
const ids = UserCollection.parse('accounts/acc-1/users/usr-1');

```

What I'm looking for are only the typings and not the implementation.

Body:
I'm trying to write typings for nested NoSQL collections. A collection can be a root collection or a sub-collection. A collection contains documents with IDs, the paths to sub-collections contain the IDs of the parent collection's documents.

The path to a collection could be accounts or for sub-collections accounts/acc-1/users. The path to a document in a sub-collection looks like this, for example accounts/acc-1/users/usr-1

The goal is to have a strongly typed class called Collection which has methods for generating collection and document paths, where the argument of those methods require the IDs passed as a map.

Is it possible to infer the types (except the type of the ID Id<>) from constructor arguments, without manually passing it as a generic to every sub-collection? I've been playing around with it for a few days now and can't get it to work.

declare const t: unique symbol;
export type Id<T> = string & { readonly [t]: T };

type DocumentIds<C extends Collection> = C extends Collection<infer IdType, infer PC, infer IdKey>
    ? { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>)
    : never;

class Collection<IdType extends string = string, PC extends Collection | void = void, IdKey extends string = string> {
   constructor(
      private readonly collectionName: string,
      private readonly idName: IdKey,
      private readonly parent?: Collection
   ) {}

   getCollectionPath(ids: PC extends void ? void : DocumentIds<PC>) {}

   getDocumentPath(ids: { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>)) {}

   parse(path: string): { [k in IdKey]: IdType } & (PC extends void ? {} : DocumentIds<PC>) {
      return null as any;
   }
}

type AccountId = Id<'Account'>;
type UserId = Id<'User'>;

const AccountCollection = new Collection<AccountId>('accounts', 'accountId');

const UserCollection = new Collection<UserId>('users', 'userId', AccountCollection);

// Does not require an argument since it's a root collection
// returns 'accounts'
AccountCollection.getCollectionPath();

// Requires an argument for the document id
// returns 'accounts/acc-1'
AccountCollection.getDocumentPath({
   accountId: 'acc-1' as AccountId,
});

// Requires an argument for the parent collection
// returns 'accounts/acc-1/users'
UserCollection.getCollectionPath({
   accountId: 'acc-1' as AccountId,
});

// Requires an argument for the parent collection and the document itself
// returns 'accounts/acc-1/users/usr-1'
UserCollection.getDocumentPath({
   accountId: 'acc-1' as AccountId,
   userId: 'usr-1' as UserId,
});

// Return type should be {accountId: AccountId, userId: UserId}
// Return value {accountId: 'acc-1', userId: 'usr-1'}
const ids = UserCollection.parse('accounts/acc-1/users/usr-1');

What I'm looking for are only the typings and not the implementation.


问:
How to draw 3D plot of interval valued function using "IntervalArithmetic" package in Julia?
I have a function P = f(a, b, c) = squareroot( a^2 + b^2 + ac + bc), where a, b, and c are in intervals. I want to draw a 3D or cubical type plot where a, b, and c will be on the x, y, and z axes. My aim is to visualize how the interval value of P changes with inputs a, b, and c.

Let a = (20..30), b= (3..4), and c = (100..200).

Please note that a, b, and c are not points in some range but are intervals.

Please let me know if any other information is required.

Thank you in advance.


问:
Google Test: Is it OK to abuse the comma operator to return values from ASSERT_ statements?
After some frustration using ASSERT_ statements in non-void functions, I discovered a workaround that works, but seems dubious.

I want to know if this is good practice or not.

Here's an example:

```<code>bool MyTest() {
    // ... code here
    ASSERT_TRUE(condition) << "Message", false;
    // ... more code
    return true;
}
</code>```

This works because ASSERT_  ends up calling GTEST_FATAL_FAILURE_, which returns the result of calling a void function:

```<code>#define GTEST_FATAL_FAILURE_(message) \
  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)

</code>```

Since I didn't see anything like this specified in the Google Test documentation, I'm wondering if I can depend on this implementation remaining as it is, or whether it may possibly change and break things later.

I'd appreciate any insight.  Thanks.

Body:
After some frustration using ASSERT_ statements in non-void functions, I discovered a workaround that works, but seems dubious.

I want to know if this is good practice or not.

Here's an example:

bool MyTest() {
    // ... code here
    ASSERT_TRUE(condition) << "Message", false;
    // ... more code
    return true;
}

This works because ASSERT_  ends up calling GTEST_FATAL_FAILURE_, which returns the result of calling a void function:

#define GTEST_FATAL_FAILURE_(message) \
  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)

Since I didn't see anything like this specified in the Google Test documentation, I'm wondering if I can depend on this implementation remaining as it is, or whether it may possibly change and break things later.

I'd appreciate any insight.  Thanks.


问:
MPDF not rendering in live server
I have created a WordPress plugin. Where PDF will be created using Ajax and downloaded. And mPDF is used to generate PDF.

```<code>function milltown_brochure_download() {
    $document_id = $_POST['documentId'];
    ob_start();
    $url = site_url('/brochure?document='.$document_id);
    try {
        $html = file_get_contents($url);
        $mpdf = new \Mpdf\Mpdf([
            'showImageErrors ' => true,
            'curlAllowUnsafeSslRequests  ' => true,
            'tempDir' => wp_upload_dir('pdf')
        ]);
        $mpdf->SetDisplayMode('fullwidth');
        $mpdf->WriteHTML($html);
        return $mpdf->Output('boat.pdf', \Mpdf\Output\Destination::DOWNLOAD);
    } catch (\Mpdf\MpdfException $e) {
        echo $e->getMessage();
    }
    die();
}
</code>```

In the local server, the download works perfectly, but after uploading to the server, it is not working anymore.

If I use image then I got Could not find image file ().
If I remove the image then I got the pdf codes.

After removing the images. I see from the browser's network tab that only the PDF code is there. But not generating pdf and downloading at all.

I did 777 permission of mpdf's temp folder but it didn't work.

Title: MPDF not rendering in live server

Body:
I have created a WordPress plugin. Where PDF will be created using Ajax and downloaded. And mPDF is used to generate PDF.

function milltown_brochure_download() {
    $document_id = $_POST['documentId'];
    ob_start();
    $url = site_url('/brochure?document='.$document_id);
    try {
        $html = file_get_contents($url);
        $mpdf = new \Mpdf\Mpdf([
            'showImageErrors ' => true,
            'curlAllowUnsafeSslRequests  ' => true,
            'tempDir' => wp_upload_dir('pdf')
        ]);
        $mpdf->SetDisplayMode('fullwidth');
        $mpdf->WriteHTML($html);
        return $mpdf->Output('boat.pdf', \Mpdf\Output\Destination::DOWNLOAD);
    } catch (\Mpdf\MpdfException $e) {
        echo $e->getMessage();
    }
    die();
}

In the local server, the download works perfectly, but after uploading to the server, it is not working anymore.

If I use image then I got Could not find image file ().
If I remove the image then I got the pdf codes.

After removing the images. I see from the browser's network tab that only the PDF code is there. But not generating pdf and downloading at all.

I did 777 permission of mpdf's temp folder but it didn't work.


问:
Python. TypeError: 'Status' object is not subscriptable
I am trying to use the code I share below to fetch the user data and tweets.

```<code>    while len(new_tweets) > 0:

        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)
        # print(alltweets[-1]['id'])
        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

    user_data = alltweets[0]["user"]
    # print('UD',user_data)
    screen_name = user_data["screen_name"]
    # print('SN',screen_name)
    # print("screen name",screen_name)
    search = api.search(screen_name, count=200)
    # print("search",search)
    mentions = search["statuses"]
    # print('mentions',mentions)
    # print('all tweets',alltweets)
    return alltweets, mentions

    pass
</code>```

Everything seems to be set up well, but when I run the code, I get this error:

```<code><ipython-input-5-52f5b94963c9> in get_all_tweets(screen_name)
    190         oldest = alltweets[-1].id - 1
    191
--> 192     user_data = alltweets[0]["user"]
    193     # print('UD',user_data)
    194     screen_name = user_data["screen_name"]

TypeError: 'Status' object is not subscriptable
</code>```

Why is 'Status' non-subscriptable? And is there a way I can fix this issue?

Someone please help me!

Body:
I am trying to use the code I share below to fetch the user data and tweets.

    while len(new_tweets) > 0:

        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)
        # print(alltweets[-1]['id'])
        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

    user_data = alltweets[0]["user"]
    # print('UD',user_data)
    screen_name = user_data["screen_name"]
    # print('SN',screen_name)
    # print("screen name",screen_name)
    search = api.search(screen_name, count=200)
    # print("search",search)
    mentions = search["statuses"]
    # print('mentions',mentions)
    # print('all tweets',alltweets)
    return alltweets, mentions

    pass

Everything seems to be set up well, but when I run the code, I get this error:

<ipython-input-5-52f5b94963c9> in get_all_tweets(screen_name)
    190         oldest = alltweets[-1].id - 1
    191
--> 192     user_data = alltweets[0]["user"]
    193     # print('UD',user_data)
    194     screen_name = user_data["screen_name"]

TypeError: 'Status' object is not subscriptable

Why is 'Status' non-subscriptable? And is there a way I can fix this issue?

Someone please help me!


问:
How to import a local library that resolves its dependencies from a different gradle project (using buildSrc)?
So recently we have been creating KMM modules for our native iOS and Android apps. Our previous way of doing things using Swift Packages ended up being too complicated and error prone for local testing of the kmm code on iOS.

In an effort to make our iOS dev teams life easier, we have created a Kmm "meta project". The goal was to have the iOS devs change one line of code in the ios app Podfile, to switch from pointing to a single Kmm bridge project that itself points to multiple maven Kmm libraries, to a Local kmm bridge project that points to all the local Kmm subprojects that include libraries and sample apps for each library (for local testing and development).

Also, the main goal of this meta project that wraps multiple subprojects was to use a root buildSrc directory to have one place to define dependencies and their versions, to ensure consistent versioning throughout all our Kmm libraries. All the dependencies are defined in a file called Dependencies.kt

Long story short, this method functions quite well for the iOS developers. The problem arrives when we try to import one of the local kmm libraries into our Android app, for local testing during development.

Because our android app is contained in a Gradle project that defines it's own buildSrc and Dependencies.kt file, importing one of the kmm libraries as a local library does not work, I am guessing because the dependencies are defined in another gradle project.

So my question is:

Is it possible to "import" an external BuildSrc kotlin file in another project to help gradle resolve the kmm library dependency?

If not #1, can I define libraries and shared dependencies somewhere else, and be able to have the meta project as well as another project resolve the dependencies for the kmm libraries?

Here is a diagram of our current architecture, that illustrates how we have things set up and where the problem arises:

Open to any suggestions or solutions. I am thinking there has to be a way to get dependency definitions that can be shared cross-project, like some sort of external file or dependency catalog, that can be imported everywhere and can allow the kmm libraries to resolve their own dependencies without the need of a gradle project.


问:
C# JsonSerializer.Serialize missing files
I am trying to serialize a List of MapPools but every time I seem to get an error about missing files. As you can see I added the dependencie System.Text.Json.

This is the code I have for it but it quits JsonSerializer.Serialize. Any ideas on how to fix the missing files?
Thanks

```<code>private const string MapPoolsFile = @"../../../resources/MapPools.json";
public void JSONSerializerMapPools()
        {
            if (File.Exists(MapPoolsFile))
            {
                List<Map> Maps = new List<Map> { new Map(Side.Attack, Side.Deffend, "Inferno"), new Map(Side.Attack, Side.Deffend, "Nuke"), new Map(Side.Attack, Side.Deffend, "Mirage") };
                List<MapPool> MapPools = new List<MapPool> { new MapPool("CSGO BIG3", Maps) };
                string json = JsonSerializer.Serialize(MapPools);
                Console.WriteLine(json);
                File.WriteAllText(MapPoolsFile, json);
            }
            else
            {
                Console.WriteLine("File not found");
            }

        }
</code>```
```<code>Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
   at System.Text.Json.JsonSerializerOptions.GetDefaultSimpleConverters()
   at System.Text.Json.JsonSerializerOptions.RootBuiltInConverters()
   at System.Text.Json.JsonSerializerOptions.InitializeForReflectionSerializer()
   at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions options, Type runtimeType)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at Datalaag.DataProvider.JSONSerializerMapPools()
</code>```

Body:
I am trying to serialize a List of MapPools but every time I seem to get an error about missing files. As you can see I added the dependencie System.Text.Json.

This is the code I have for it but it quits JsonSerializer.Serialize. Any ideas on how to fix the missing files?
Thanks

private const string MapPoolsFile = @"../../../resources/MapPools.json";
public void JSONSerializerMapPools()
        {
            if (File.Exists(MapPoolsFile))
            {
                List<Map> Maps = new List<Map> { new Map(Side.Attack, Side.Deffend, "Inferno"), new Map(Side.Attack, Side.Deffend, "Nuke"), new Map(Side.Attack, Side.Deffend, "Mirage") };
                List<MapPool> MapPools = new List<MapPool> { new MapPool("CSGO BIG3", Maps) };
                string json = JsonSerializer.Serialize(MapPools);
                Console.WriteLine(json);
                File.WriteAllText(MapPoolsFile, json);
            }
            else
            {
                Console.WriteLine("File not found");
            }

        }

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
   at System.Text.Json.JsonSerializerOptions.GetDefaultSimpleConverters()
   at System.Text.Json.JsonSerializerOptions.RootBuiltInConverters()
   at System.Text.Json.JsonSerializerOptions.InitializeForReflectionSerializer()
   at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions options, Type runtimeType)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at Datalaag.DataProvider.JSONSerializerMapPools()


问:
How to print a unsigned char array having hex values values as input string using hexdump
I have a unsigned char array [32]="1A2B3C4D5E"; this array has string having hex values so now how can I print it? Please help

%s is giving wrong unrecognised characters
%X is giving error

I want to print using hexdump


问:
ExternalTaskSensor Does't Pick Up Right TimeDelta
I have more than one dependent DAGs I need to sense in order to start the final dag. The problem is that DAGs have different schedules.
In order to sense the dags, I have created a code mentioned below.
The code works, but when I try to pick up timedelta (variable dag_minutes_delta) from dependency_dags list, only the last value got picked up.
However, if I hardcode timedelta, everything works as expected.
No clue, how to fix this issue. Does someone faced the same issue?

```<code>with DAG(
            dag_id=dag_id_config,
            start_date=pendulum.datetime(2022, 6, 13, tz="UTC"),
            schedule_interval=config["schedule"],
            catchup=False,
            max_active_runs=config["max_active_runs"],
            default_args=default_args,
            render_template_as_native_obj=True
    ) as dag:

        dummy = BashOperator(
            task_id="start_invocation",
            bash_command="echo start",
        )

        dependency_dags = [
                {"dag_name": "dag A",
                 "schedule_type": "daily",
                 "minutes_delta": 10
                },
                {"dag_name": "dag B",
                "schedule_type": "hourly",
                "minutes_delta": 300
                }
            ]

        dependency_check = []
        for dag_item in dependency_dags:
            dag_name = dag_item["dag_name"]
            dag_schedule_type = dag_item["schedule_type"]
            dag_minutes_delta = dag_item["minutes_delta"]
            if dag_schedule_type == "daily":
                execution_date_recheck = lambda dt: dt.replace(hour=0, minute=0, second=0).add(days=-1) \
                .add(minutes=dag_minutes_delta)
            if dag_schedule_type == "hourly":
                execution_date_recheck = lambda dt: dt.add(minutes=dag_minutes_delta)

            dependency_dag = ExternalTaskSensor(
                task_id=f"dependency_on_{dag_name}",
                external_dag_id=dag_name,
                external_task_id=None,
                timeout=5,
                allowed_states=["success"],
                failed_states=["failed"],
                check_existence=True,
                execution_date_fn=execution_date_recheck,
                mode="reschedule")
            dependency_check.append(dependency_dag)

    dependency_check >> dummy
</code>```

I swapped items in dependency_dags list, but the result is the same - execution_date_fn picks up the latest value.
I checked all possible articles and documentation, but could not find anything

Body:
I have more than one dependent DAGs I need to sense in order to start the final dag. The problem is that DAGs have different schedules.
In order to sense the dags, I have created a code mentioned below.
The code works, but when I try to pick up timedelta (variable dag_minutes_delta) from dependency_dags list, only the last value got picked up.
However, if I hardcode timedelta, everything works as expected.
No clue, how to fix this issue. Does someone faced the same issue?

with DAG(
            dag_id=dag_id_config,
            start_date=pendulum.datetime(2022, 6, 13, tz="UTC"),
            schedule_interval=config["schedule"],
            catchup=False,
            max_active_runs=config["max_active_runs"],
            default_args=default_args,
            render_template_as_native_obj=True
    ) as dag:

        dummy = BashOperator(
            task_id="start_invocation",
            bash_command="echo start",
        )

        dependency_dags = [
                {"dag_name": "dag A",
                 "schedule_type": "daily",
                 "minutes_delta": 10
                },
                {"dag_name": "dag B",
                "schedule_type": "hourly",
                "minutes_delta": 300
                }
            ]

        dependency_check = []
        for dag_item in dependency_dags:
            dag_name = dag_item["dag_name"]
            dag_schedule_type = dag_item["schedule_type"]
            dag_minutes_delta = dag_item["minutes_delta"]
            if dag_schedule_type == "daily":
                execution_date_recheck = lambda dt: dt.replace(hour=0, minute=0, second=0).add(days=-1) \
                .add(minutes=dag_minutes_delta)
            if dag_schedule_type == "hourly":
                execution_date_recheck = lambda dt: dt.add(minutes=dag_minutes_delta)

            dependency_dag = ExternalTaskSensor(
                task_id=f"dependency_on_{dag_name}",
                external_dag_id=dag_name,
                external_task_id=None,
                timeout=5,
                allowed_states=["success"],
                failed_states=["failed"],
                check_existence=True,
                execution_date_fn=execution_date_recheck,
                mode="reschedule")
            dependency_check.append(dependency_dag)

    dependency_check >> dummy

I swapped items in dependency_dags list, but the result is the same - execution_date_fn picks up the latest value.
I checked all possible articles and documentation, but could not find anything


问:
Prevent Teamcity artifacts being deleted in dependency builds
I am using Teamcity on prem. We have a policy for deleting builds older than a certain time period, and the base rule is set to "Do not prevent dependency artifacts cleanup". I am not allowed to change the base rule.

I have a project called "API" which publishes a NuGet package, and this is consumed by another build called "Service". Due to the clean-up rules I am finding that the "API" NuGet package is being deleted even though I have a pinned build of "Service" that consumes that version of the NuGet package.

I can define a "Keep Rule" and tick "Keep artifacts in all dependency builds". But I am unclear if I should be setting the "Keep Rule" on the "API" build or the "Service" build.

I want to ensure that the "API" NuGet package is not deleted while there exists a build of "Service" that depends on it. Should the "Keep Rule" go on the "API" or the "Service" build?


问:
Google translate embed , can I have it always visible
I have installed the Google translate on my web page, but the translate panel only appears at the top of the screen when someone hits a language.  Is there any way for the panel to appear on loading?

Just to be clear, the pages is working fine, and can be translated, I simply want the translate bar to be always visible at the top of the screen.

I looked on the Google translate website, and could not find anything.


问:
Window style in SFML using sf::Window::getSystemHandle() error
I am using SFML, and I want to change my window style to a specific style not supported bt SFML using the following code:

```<code>//--- Window objects;
RenderWindow game_window(VideoMode(O_WIN_WD, O_WIN_HT, 64), "window");

HWND hwd = game_window.getSystemHandle();
LONG s = GetWindowLongPtr(hwd, GWL_STYLE);
</code>```

I get an error:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp_GetWindowLongPtrW referenced in function main  App C:\Users\user\App\main.obj  1

I am using MS Visual Studio.

Thanks

Body:
I am using SFML, and I want to change my window style to a specific style not supported bt SFML using the following code:

//--- Window objects;
RenderWindow game_window(VideoMode(O_WIN_WD, O_WIN_HT, 64), "window");

HWND hwd = game_window.getSystemHandle();
LONG s = GetWindowLongPtr(hwd, GWL_STYLE);

I get an error:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp_GetWindowLongPtrW referenced in function main  App C:\Users\user\App\main.obj  1

I am using MS Visual Studio.

Thanks


问:
useDispatch causes 'Object(...) is not a function' error
I'm doing a simple app to retrieve some messages for a dashboard, react & redux.

I have this code block:

```<code>import React from 'react';
import { useDispatch } from 'react-redux';

function Dashboard() {

  const dispatch = useDispatch();

  return (
    <div>
      My dashboard!
    </div>
  )
}

</code>```

That always returns the error "Uncaught TypeError: Object(...) is not a function" in the useReduxContext. When I comment out useDispatch, it works fine. My imports are also up to date. Other similar questions here usually showed it to be an import error, so I'm confused as to what I'm doing wrong.

Console logging useDispatch yielded this:

```<code>  useDispatch() {
    const store = useStore(); // @ts-ignore

    return store.dispatch;
  }
</code>```

Body:
I'm doing a simple app to retrieve some messages for a dashboard, react & redux.

I have this code block:

import React from 'react';
import { useDispatch } from 'react-redux';

function Dashboard() {

  const dispatch = useDispatch();

  return (

      My dashboard!

  )
}

That always returns the error "Uncaught TypeError: Object(...) is not a function" in the useReduxContext. When I comment out useDispatch, it works fine. My imports are also up to date. Other similar questions here usually showed it to be an import error, so I'm confused as to what I'm doing wrong.

Console logging useDispatch yielded this:

  useDispatch() {
    const store = useStore(); // @ts-ignore

    return store.dispatch;
  }


问:
Document more than one repos with MkDocs
I got a special situation where I have a few Django packages that work closely together, and I want to document them together at one place.

medux-common: common used models, views, etc.

medux: main application

medux-online: web interface for certain functions

medux-docs: the documentation package

Both medux-online and medux use the common module, and I don't want to have 3 documentation homepages, but just one where all is documented at one place.

Is there a possibility in MkDocs to "load" external packages? I use the mkdocstrings plugin to load the docstrings from my code. Its docs says, that the path must be set so that the module to document must be importable.

In my medux-docs package, I import all the other packages using pip install -e ../medux etc., which works fine. But MkDocs does not find them:

```<code>$ mkdocs serve
[...]
ERROR    -  mkdocstrings: medux.core.middleware could not be found
ERROR    -  Could not collect 'medux.core.middleware'
</code>```

How do I do that? I don't want to merge all repositories into one, as medux and medux-online should be 2 pypi packages too. I just want MkDocs to find the imported medux, medux-online, and medux-common.
Do I completely think the wrong way?

Body:
I got a special situation where I have a few Django packages that work closely together, and I want to document them together at one place.

medux-common: common used models, views, etc.

medux: main application

medux-online: web interface for certain functions

medux-docs: the documentation package

Both medux-online and medux use the common module, and I don't want to have 3 documentation homepages, but just one where all is documented at one place.

Is there a possibility in MkDocs to "load" external packages? I use the mkdocstrings plugin to load the docstrings from my code. Its docs says, that the path must be set so that the module to document must be importable.

In my medux-docs package, I import all the other packages using pip install -e ../medux etc., which works fine. But MkDocs does not find them:

$ mkdocs serve
[...]
ERROR    -  mkdocstrings: medux.core.middleware could not be found
ERROR    -  Could not collect 'medux.core.middleware'

How do I do that? I don't want to merge all repositories into one, as medux and medux-online should be 2 pypi packages too. I just want MkDocs to find the imported medux, medux-online, and medux-common.
Do I completely think the wrong way?


问:
LakeFormation permissions when deploying w/ Terraform?
I'm working on deploying to LakeFormation via Terraform. Specifically, granting data location access to a lambda role. I'm getting an error when the role/user I'm deploying with in Terraform isn't an admin on LakeFormation (I haven't tried playing around w/ granular policies on the caller yet). Has anyone come across the same issue and what was the resolution? The caller is a service user which is used by other groups across the org, so I would ideally like to avoid elevating any more of its permissions.

```<code>resource "aws_lakeformation_permissions" "datalake-permissions" {
  principal   = aws_iam_role.lambda-role.arn
  permissions = ["DATA_LOCATION_ACCESS"]

  data_location {
    arn = data.aws_s3_bucket.datalake-bucket.arn
  }
}
</code>```

This is the error :

error creating Lake Formation Permissions (input: { Permissions: ["DATA_LOCATION_ACCESS"], Principal: { DataLakePrincipalIdentifier: "arn:aws:iam::{account_id}:role/lambda_role" }, Resource: { DataLocation: { ResourceArn: "arn:aws:s3:::{my-bucket}" } } }): AccessDeniedException: Resource does not exist or requester is not authorized to access requested permissions.

Also made sure the bucket exists and isn't an issue.

I've tried adding the lambda role as an admin to the space, had no effect. Only appears to be when I give the caller access that things work as expected.

Body:
I'm working on deploying to LakeFormation via Terraform. Specifically, granting data location access to a lambda role. I'm getting an error when the role/user I'm deploying with in Terraform isn't an admin on LakeFormation (I haven't tried playing around w/ granular policies on the caller yet). Has anyone come across the same issue and what was the resolution? The caller is a service user which is used by other groups across the org, so I would ideally like to avoid elevating any more of its permissions.

resource "aws_lakeformation_permissions" "datalake-permissions" {
  principal   = aws_iam_role.lambda-role.arn
  permissions = ["DATA_LOCATION_ACCESS"]

  data_location {
    arn = data.aws_s3_bucket.datalake-bucket.arn
  }
}

This is the error :

error creating Lake Formation Permissions (input: { Permissions: ["DATA_LOCATION_ACCESS"], Principal: { DataLakePrincipalIdentifier: "arn:aws:iam::{account_id}:role/lambda_role" }, Resource: { DataLocation: { ResourceArn: "arn:aws:s3:::{my-bucket}" } } }): AccessDeniedException: Resource does not exist or requester is not authorized to access requested permissions.

Also made sure the bucket exists and isn't an issue.

I've tried adding the lambda role as an admin to the space, had no effect. Only appears to be when I give the caller access that things work as expected.


问:
Docker and selenium grid set-up. Debug node not linking to container
So I am trying to get Selenium Grid a docker-compose.yml file and this is my current set-up.

```<code>version: "3.8"
services:
  selenium-hub:
    image: selenium/hub:latest
    container_name: selenium-hub
    ports:
      - "4442:4444"
    environment:
      GRID_MAX_SESSION: 16
      GRID_BROWSER_TIMEOUT: 3000
      GRID_TIMEOUT: 3000
    networks:
      - grid

  firefox:
    image: selenium/node-firefox
    container_name: firefox
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
      - SE_NODE_MAX_INSTANCE=2
      - SE_NODE_MAX_SESSIONS=12
      - SE_NODE_SESSION_TIMEOUT=10
    networks:
      - grid

  firefox-debug:
    image: selenium/node-firefox-debug
    restart: always
    container_name: firefox-debug
    depends_on:
      - selenium-hub
    ports:
      - "32772:5900"
    volumes:
      - /dev/shm:/dev/shm
    environment:
      - HUB_HOST = selenium-hub
    networks:
      - grid

networks:
  grid:
</code>```

I got my grid to set up with my firefox node but the debug node keeps saying "Not linked with a running Hub container" which I am having trouble resolving. This is how my inspect grid look like.

```<code>[
    {
        "Name": "dil_grid",
        "Id": "bedb7a355fbfaabaaea0a9aab7c690ba0da0614acce81dbd1c74ad98364f8b55",
        "Created": "2022-12-09T21:39:15.7226184Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.26.0.0/16",
                    "Gateway": "172.26.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "05d699c2186b94a6f90cf0e391dc1df3f953cad61b6daa3252bfcd0aa5ed569b": {
                "Name": "firefox-debug",
                "EndpointID": "5e433746b5737a33e0d7963a24c77144a3e5845bf760c5f158dddef81985fd27",
                "MacAddress": "02:42:ac:1a:00:03",
                "IPv4Address": "172.26.0.3/16",
                "IPv6Address": ""
            },
                "Name": "selenium-hub",
                "EndpointID": "3fe8ccad24f258d032244d4f0ed0d1f035e9c35877f6fb6a36873f022cc004b8",
                "MacAddress": "02:42:ac:1a:00:02",
                "IPv4Address": "172.26.0.2/16",
                "IPv6Address": ""
            },
            "86ae4e625cb3fef048c1a7ba9abf1f93b6c494b0026848de2825fe4c71ba819a": {
                "Name": "firefox",
                "EndpointID": "e7f53ad99ad3be60eef833c318bf6f1ef43f86658860756601edc92f4ea5339d",
                "MacAddress": "02:42:ac:1a:00:04",
                "IPv4Address": "172.26.0.4/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "grid",
            "com.docker.compose.project": "dil",
            "com.docker.compose.version": "2.10.2"
        }
    }
]
</code>```

I've tried using expose and links instead of ports and depends_on and I haven't been successful in adding the debug node to the hub. Any ideas would be helpful. Thanks

Body:
So I am trying to get Selenium Grid a docker-compose.yml file and this is my current set-up.

version: "3.8"
services:
  selenium-hub:
    image: selenium/hub:latest
    container_name: selenium-hub
    ports:
      - "4442:4444"
    environment:
      GRID_MAX_SESSION: 16
      GRID_BROWSER_TIMEOUT: 3000
      GRID_TIMEOUT: 3000
    networks:
      - grid

  firefox:
    image: selenium/node-firefox
    container_name: firefox
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
      - SE_NODE_MAX_INSTANCE=2
      - SE_NODE_MAX_SESSIONS=12
      - SE_NODE_SESSION_TIMEOUT=10
    networks:
      - grid

  firefox-debug:
    image: selenium/node-firefox-debug
    restart: always
    container_name: firefox-debug
    depends_on:
      - selenium-hub
    ports:
      - "32772:5900"
    volumes:
      - /dev/shm:/dev/shm
    environment:
      - HUB_HOST = selenium-hub
    networks:
      - grid

networks:
  grid:

I got my grid to set up with my firefox node but the debug node keeps saying "Not linked with a running Hub container" which I am having trouble resolving. This is how my inspect grid look like.

[
    {
        "Name": "dil_grid",
        "Id": "bedb7a355fbfaabaaea0a9aab7c690ba0da0614acce81dbd1c74ad98364f8b55",
        "Created": "2022-12-09T21:39:15.7226184Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.26.0.0/16",
                    "Gateway": "172.26.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "05d699c2186b94a6f90cf0e391dc1df3f953cad61b6daa3252bfcd0aa5ed569b": {
                "Name": "firefox-debug",
                "EndpointID": "5e433746b5737a33e0d7963a24c77144a3e5845bf760c5f158dddef81985fd27",
                "MacAddress": "02:42:ac:1a:00:03",
                "IPv4Address": "172.26.0.3/16",
                "IPv6Address": ""
            },
                "Name": "selenium-hub",
                "EndpointID": "3fe8ccad24f258d032244d4f0ed0d1f035e9c35877f6fb6a36873f022cc004b8",
                "MacAddress": "02:42:ac:1a:00:02",
                "IPv4Address": "172.26.0.2/16",
                "IPv6Address": ""
            },
            "86ae4e625cb3fef048c1a7ba9abf1f93b6c494b0026848de2825fe4c71ba819a": {
                "Name": "firefox",
                "EndpointID": "e7f53ad99ad3be60eef833c318bf6f1ef43f86658860756601edc92f4ea5339d",
                "MacAddress": "02:42:ac:1a:00:04",
                "IPv4Address": "172.26.0.4/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "grid",
            "com.docker.compose.project": "dil",
            "com.docker.compose.version": "2.10.2"
        }
    }
]

I've tried using expose and links instead of ports and depends_on and I haven't been successful in adding the debug node to the hub. Any ideas would be helpful. Thanks


问:
How to drag and drop an item into a ajax fetched div using java script?
I have fetched a table using ajax and I want to drag and drop another div to it and update my db  but when I use dragover , dragenter etc... functions with javascript it doesnt work. But when I fetch that table using just php without ajax it works.
Is there a way to make it work with ajax tooo.

Below is my ajax request

```<code>          $.ajax({
            url: 'timetable',
            type: 'POST',
            cache: false,
            data: {
              valuehere: valuehere,
              dayhere: dayhere,
            },
            success: function(data) {
              // alert(data);
              // show the data
              let showhere = document.querySelector('.showhere');
              showhere.innerHTML = data;
            }
          });
</code>```

Below is my javascript drag and drop code

```<code>
const draggables = document.querySelectorAll('.draggable');
const containers = document.querySelectorAll('.containersdrag34234');

// loop through the containers and add the event listeners
for (const container of containers) {
    container.addEventListener('dragover', dragOver);
    container.addEventListener('dragenter', dragEnter);
    container.addEventListener('dragleave', dragLeave);
    container.addEventListener('drop', dragDrop);
}

// fill the containers with the draggable elements and send ajax and edit the db
draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('hold');
        setTimeout(() => (draggable.classList.add('invisible')), 0);
    });
    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('hold', 'invisible');
    });
});

// functions for the containers
function dragOver() {
    console.log('over');
}

function dragEnter() {
    console.log('enter');
}

function dragLeave() {
    console.log('leave');
}

function dragDrop() {
    console.log('drop');
}

</code>```

Body:
I have fetched a table using ajax and I want to drag and drop another div to it and update my db  but when I use dragover , dragenter etc... functions with javascript it doesnt work. But when I fetch that table using just php without ajax it works.
Is there a way to make it work with ajax tooo.

Below is my ajax request

          $.ajax({
            url: 'timetable',
            type: 'POST',
            cache: false,
            data: {
              valuehere: valuehere,
              dayhere: dayhere,
            },
            success: function(data) {
              // alert(data);
              // show the data
              let showhere = document.querySelector('.showhere');
              showhere.innerHTML = data;
            }
          });

Below is my javascript drag and drop code

const draggables = document.querySelectorAll('.draggable');
const containers = document.querySelectorAll('.containersdrag34234');

// loop through the containers and add the event listeners
for (const container of containers) {
    container.addEventListener('dragover', dragOver);
    container.addEventListener('dragenter', dragEnter);
    container.addEventListener('dragleave', dragLeave);
    container.addEventListener('drop', dragDrop);
}

// fill the containers with the draggable elements and send ajax and edit the db
draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('hold');
        setTimeout(() => (draggable.classList.add('invisible')), 0);
    });
    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('hold', 'invisible');
    });
});

// functions for the containers
function dragOver() {
    console.log('over');
}

function dragEnter() {
    console.log('enter');
}

function dragLeave() {
    console.log('leave');
}

function dragDrop() {
    console.log('drop');
}


问:
Oauth flow for Meta Workplace
I am attempitng to complete an oauth flow for a workplace app. Following this guide https://developers.facebook.com/docs/workplace/third-party-apps/development , I tried to use this https://work.workplace.com/work/admin/apps?
app_id={your-app-id}
&state={optional-state-parameter}  but it did not work. I just get a generic error that there is a technical issue. I have setup a valid redirect url in my app settings. I will appreciate any help.</p>

Title: Oauth flow for Meta Workplace


问:
bootstrap 5 navigations and dropdowns are very laggy on ios devices
Django web app on Pythonenywhere, farhood.pythonanywhere.com, navigations and dropdowns are very laggy on ios devices but work fine on android and windows. any Ideas on what might cause this?
navigation is done using bootstrap 5 responsive navigation
I've searched online and did not find any relevant info</p>


问:
Cannot get lines() function to change individual color of lines added
I am attempting to change the colors of lines in a chi-squared distribution that is being added on to a normal distribution curve. The lines only come up as one specific color, not all three that I want.

This is the current code I am using. The normal distribution curve works as it should. But all chi-squared values come up in the same color. I want each individual curve to be a specific color. I think it might have something to do with my for loop as I'm not exactly sure how to use them. The code was given to me as fill in the blank.

```<code>x <- seq(-4, 45, length=500)         # x values
dist.x <- dnorm(x, mean = 20, sd = 5)    # Returns CDF of normal distribution with mean 20 and sd 5.

degf <- c(4,10, 20)             # Set up the three degree of freedoms
colors <- c("green","red", "blue", "black")  # Set up the four colors
labels <- c("df=4", "df=10","df=20",  "normal")       # Label the plots

plot(dist.x, col = colors[4], type="l", lty=2, lwd=2, xlab="x value",
  ylab="Density", main="Comparison of Normal and Chi-Square Distributions")         # Plot normal density curve

for (i in x){
  lines(x, dchisq(x,degf[1:3]), lty=1, lwd=2, col= colors[1:3]) # Plot chi-square distribution curves
                                   # dchisq() returns CDF of chi-square distribution
                                   # col= set up colors for the chi-square distributions
}

legend("topright", inset=0.01, title="Distributions",       # Set up the title of legend
  labels, lwd=2, lty=c(1, 1, 1, 2), col=colors)  # Set up line types appearing in the legend
</code>```

Body:
I am attempting to change the colors of lines in a chi-squared distribution that is being added on to a normal distribution curve. The lines only come up as one specific color, not all three that I want.

This is the current code I am using. The normal distribution curve works as it should. But all chi-squared values come up in the same color. I want each individual curve to be a specific color. I think it might have something to do with my for loop as I'm not exactly sure how to use them. The code was given to me as fill in the blank.

x <- seq(-4, 45, length=500)         # x values
dist.x <- dnorm(x, mean = 20, sd = 5)    # Returns CDF of normal distribution with mean 20 and sd 5.

degf <- c(4,10, 20)             # Set up the three degree of freedoms
colors <- c("green","red", "blue", "black")  # Set up the four colors
labels <- c("df=4", "df=10","df=20",  "normal")       # Label the plots

plot(dist.x, col = colors[4], type="l", lty=2, lwd=2, xlab="x value",
  ylab="Density", main="Comparison of Normal and Chi-Square Distributions")         # Plot normal density curve

for (i in x){
  lines(x, dchisq(x,degf[1:3]), lty=1, lwd=2, col= colors[1:3]) # Plot chi-square distribution curves
                                   # dchisq() returns CDF of chi-square distribution
                                   # col= set up colors for the chi-square distributions
}

legend("topright", inset=0.01, title="Distributions",       # Set up the title of legend
  labels, lwd=2, lty=c(1, 1, 1, 2), col=colors)  # Set up line types appearing in the legend


问:
Where is the n_periods value in sktime ARIMA coming from?
I am trying to use the sktime python library for forecasting some time series data.
My x_train is of shape (277, 10) with the DateTime as index. My x_test is of shape (70, 10)
My code for using ARIMA is:

```<code>fh = ForecastingHorizon(y_test.index, is_relative=False)
arima = ARIMA()
arima.fit(y=y_train, X=x_train)
y_pred = arima.predict(fh=fh, X=x_test)
</code>```

But the predict step is giving me error:

X array dims (n_rows) != n_periods. Received n_rows=70 and n_periods=80

I am totally unable to understand where the 80 is coming from. I couldn't find any explanation in the sktime documentation. The index of fh and x_test are matching.

I am also getting similar error in case of VARMAX, in case of which it is expecting (89,10) X. where are these numbers coming from? Why can't I predict for any period of time? What am I doing wrong here?

Body:
I am trying to use the sktime python library for forecasting some time series data.
My x_train is of shape (277, 10) with the DateTime as index. My x_test is of shape (70, 10)
My code for using ARIMA is:

fh = ForecastingHorizon(y_test.index, is_relative=False)
arima = ARIMA()
arima.fit(y=y_train, X=x_train)
y_pred = arima.predict(fh=fh, X=x_test)

But the predict step is giving me error:

X array dims (n_rows) != n_periods. Received n_rows=70 and n_periods=80

I am totally unable to understand where the 80 is coming from. I couldn't find any explanation in the sktime documentation. The index of fh and x_test are matching.

I am also getting similar error in case of VARMAX, in case of which it is expecting (89,10) X. where are these numbers coming from? Why can't I predict for any period of time? What am I doing wrong here?


问:
How do I port ImageDataGenerator's channel_shift_range() from tensorflow to Pytorch?
I want to perform channel shift operation on pytorch, but can't seem to figure if there's a predefined function. Also new to pytorch so don't know how to create the function. I did find one for tensorflow, but need to implement pytorch.

Here's the link for tensorflow

Objective: To do online data augmentation

The error screenshot:

I tried to use the function used in tensorflow source (as its just python) and call it in my pytorch code:

```<code>class channel_shift(torch.nn.Module):

  def __init__(self, intensity, channel_axis):
    super().__init__()
    self.intensity = intensity
    self.channel_axis = channel_axis

  def forward(self, x, intensity, channel_axis):

    """Performs a channel shift.
    Args:
        x: Input tensor. Must be 3D.
        intensity: Transformation intensity.
        channel_axis: Index of axis for channels in the input tensor.
    Returns:
        Numpy image tensor.
  """
    self.intensity = intensity
    self.channel_axis = channel_axis
    x = np.rollaxis(x, channel_axis, 0)
    min_x, max_x = np.min(x), np.max(x)
    channel_images = [
        np.clip(x_channel + intensity, min_x, max_x) for x_channel in x
    ]
    x = np.stack(channel_images, axis=0)
    x = np.rollaxis(x, 0, channel_axis + 1)
    return x

  def __repr__(self) -> str:
     return f"{self.__class__.__name__}(p={self.intensity})"

class transformed_dataset(Dataset):
  def __init__(self, data, transform):
      self.data = data[0]
      self.transform = transform

  def __len__(self):
      return len(self.data)

  def __getitem__(self, idx):
      item = self.data[idx]
      item = self.transform(item)
      return item

transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.RandomAffine(degrees=90, translate=(0.2, 0.2), scale=(0.2, 1), shear=0.2),
    transforms.RandomVerticalFlip(),
    channel_shift(intensity=20, channel_axis=0), # # to do
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor()
    ])

dataset_top_indian_fruits_augmentations = transformed_dataset(top_indian_fruits, transform)
for item in dataset_top_indian_fruits_augmentations[0]:
    print(item)

</code>```

Body:
I want to perform channel shift operation on pytorch, but can't seem to figure if there's a predefined function. Also new to pytorch so don't know how to create the function. I did find one for tensorflow, but need to implement pytorch.

Here's the link for tensorflow

Objective: To do online data augmentation

The error screenshot:

I tried to use the function used in tensorflow source (as its just python) and call it in my pytorch code:

class channel_shift(torch.nn.Module):

  def __init__(self, intensity, channel_axis):
    super().__init__()
    self.intensity = intensity
    self.channel_axis = channel_axis

  def forward(self, x, intensity, channel_axis):

    """Performs a channel shift.
    Args:
        x: Input tensor. Must be 3D.
        intensity: Transformation intensity.
        channel_axis: Index of axis for channels in the input tensor.
    Returns:
        Numpy image tensor.
  """
    self.intensity = intensity
    self.channel_axis = channel_axis
    x = np.rollaxis(x, channel_axis, 0)
    min_x, max_x = np.min(x), np.max(x)
    channel_images = [
        np.clip(x_channel + intensity, min_x, max_x) for x_channel in x
    ]
    x = np.stack(channel_images, axis=0)
    x = np.rollaxis(x, 0, channel_axis + 1)
    return x

  def __repr__(self) -> str:
     return f"{self.__class__.__name__}(p={self.intensity})"

class transformed_dataset(Dataset):
  def __init__(self, data, transform):
      self.data = data[0]
      self.transform = transform

  def __len__(self):
      return len(self.data)

  def __getitem__(self, idx):
      item = self.data[idx]
      item = self.transform(item)
      return item

transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.RandomAffine(degrees=90, translate=(0.2, 0.2), scale=(0.2, 1), shear=0.2),
    transforms.RandomVerticalFlip(),
    channel_shift(intensity=20, channel_axis=0), # # to do
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor()
    ])

dataset_top_indian_fruits_augmentations = transformed_dataset(top_indian_fruits, transform)
for item in dataset_top_indian_fruits_augmentations[0]:
    print(item)