问:
Laravel database connection use localhost instead of external ip
When I want to migrate my database I got returned an exception regarding:

```<code> Syntax error or access violation: 1044 Access denied for user 'foo'@'%' to database ...
</code>```

And that's weird because I just provided the IP in the .env document and I blocked all ways to communicate with the local IP or %.

First it was using my local IP, so I added the database url as well inside the .env document, but that still didn't fixed this exception. After adding the database url and database host it is using now % as ip location.

How can I prevent Laravel of using %, 127.0.0.1 or localhost by running a migration.

The problem what I see is. When I migrate the first time it is using the normal .env credentials on the correct database ip, but once I provided the new credentials with:

```<code>DB::connection('bar');
</code>```

It use the correct credentials but don't want to use the correct database IP, instead it use localhost or %

Body:
When I want to migrate my database I got returned an exception regarding:

 Syntax error or access violation: 1044 Access denied for user 'foo'@'%' to database ...

And that's weird because I just provided the IP in the .env document and I blocked all ways to communicate with the local IP or %.

First it was using my local IP, so I added the database url as well inside the .env document, but that still didn't fixed this exception. After adding the database url and database host it is using now % as ip location.

How can I prevent Laravel of using %, 127.0.0.1 or localhost by running a migration.

The problem what I see is. When I migrate the first time it is using the normal .env credentials on the correct database ip, but once I provided the new credentials with:

DB::connection('bar');

It use the correct credentials but don't want to use the correct database IP, instead it use localhost or %


来源: stackexchange

问:
checkboxGroupInput in Shiny doesn't work when input data is data table not data frame
I have a case where I need to view a data table in Shiny with dynamic user-selected columns to view. This demo in Shiny Gallery was very insightful as a start. But when I applied it to my specific code where I use a data table rather than a data frame the main panel throws an error of "'data' must be 2-dimensional (e.g. data frame or matrix)". The only reason I got figure out for this error is that the input$show_vars does not work when the input data is a data table.

I present here two samples of codes to show the problem. The first one works well when the diamonds data is a data frame. The other one is the same code but the diamonds table is converted in data table in server section.

Appreciate any assistance to fix the code such that it works well when the input data is data table class.

Scenario1:

```<code>library(shiny)
library(ggplot2)  # for the diamonds dataset

ui <- fluidPage(
  title = "Examples of DataTables",
  sidebarLayout(
    sidebarPanel(
        checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                           names(diamonds), selected = names(diamonds))
      ),
    mainPanel(
      tabsetPanel(
        tabPanel("diamonds", DT::dataTableOutput("mytable1")),
        )
      )
    )
)
server <- function(input, output) {

  # choose columns to display
  diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
  output$mytable1 <-  renderDataTable({
    diamonds2[, input$show_vars]
  })
}

shinyApp(ui, server)
`
</code>```

Scenario2:

```<code>library(shiny)
library(ggplot2)  # for the diamonds dataset

ui <- fluidPage(
  title = "Examples of DataTables",
  sidebarLayout(
    sidebarPanel(
        checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                           names(diamonds), selected = names(diamonds))
      ),
    mainPanel(
      tabsetPanel(
        tabPanel("diamonds", DT::dataTableOutput("mytable1")),
        )
      )
    )
)
server <- function(input, output) {

  # choose columns to display
  diamonds2 = as.data.table(diamonds[sample(nrow(diamonds), 1000), ])
  output$mytable1 <-  renderDataTable({
    diamonds2[, input$show_vars]
  })
}

shinyApp(ui, server)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a case where I need to view a data table in Shiny with dynamic user-selected columns to view. This demo in Shiny Gallery was very insightful as a start. But when I applied it to my specific code where I use a data table rather than a data frame the main panel throws an error of "'data' must be 2-dimensional (e.g. data frame or matrix)". The only reason I got figure out for this error is that the input$show_vars does not work when the input data is a data table.

I present here two samples of codes to show the problem. The first one works well when the diamonds data is a data frame. The other one is the same code but the diamonds table is converted in data table in server section.

Appreciate any assistance to fix the code such that it works well when the input data is data table class.

Scenario1:

library(shiny)
library(ggplot2)  # for the diamonds dataset

ui <- fluidPage(
  title = "Examples of DataTables",
  sidebarLayout(
    sidebarPanel(
        checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                           names(diamonds), selected = names(diamonds))
      ),
    mainPanel(
      tabsetPanel(
        tabPanel("diamonds", DT::dataTableOutput("mytable1")),
        )
      )
    )
)
server <- function(input, output) {

  # choose columns to display
  diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
  output$mytable1 <-  renderDataTable({
    diamonds2[, input$show_vars]
  })
}

shinyApp(ui, server)
`

Scenario2:

library(shiny)
library(ggplot2)  # for the diamonds dataset

ui <- fluidPage(
  title = "Examples of DataTables",
  sidebarLayout(
    sidebarPanel(
        checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                           names(diamonds), selected = names(diamonds))
      ),
    mainPanel(
      tabsetPanel(
        tabPanel("diamonds", DT::dataTableOutput("mytable1")),
        )
      )
    )
)
server <- function(input, output) {

  # choose columns to display
  diamonds2 = as.data.table(diamonds[sample(nrow(diamonds), 1000), ])
  output$mytable1 <-  renderDataTable({
    diamonds2[, input$show_vars]
  })
}

shinyApp(ui, server)


问:
Tensor must have a shape comprised of positive integers but got shape [,96]
```<code>const predictGenre = async (filename) => {
  console.log("*********** Predict Genre ***********");
    // eslint-disable-next-line no-undef
    const audioFilePath = musicPath + filename;
    //Decode Audio (Wav File)
    const audioBuffer = fs.readFileSync(audioFilePath);
    const preprocessedAudio = preprocess(audioBuffer);
    // Initialisation "musicnn"
    let features = {
      melSpectrum: [],
      batchSize: 0,
      melBandsSize: 96,
      patchSize: 187,
    };
    let frameSize = 512;
    let hopSize = 256;
    //Extract Features
    const extractor = new EssentiaModel.EssentiaTFInputExtractor(
      EssentiaWASM,
      "musicnn"
    );
    let wasm = EssentiaWASM;
    let essentia = extractor.essentia;
    features.melSpectrum = []; // ensure it's empty from previous runs
    let frames = essentia.FrameGenerator(preprocessedAudio, frameSize, hopSize);
    let audioLength = frames.size();
    for (var i = 0; i < audioLength; i++) {
      let frame = wasm.vectorToArray(frames.get(i));
      features.melSpectrum.push(extractor.compute(frame).melSpectrum);
    }
    //frames.delete();
    features.batchSize = features.melSpectrum.length;
    //Load Model
    const modelPath =
      //eslint-disable-next-line no-undef
      "file://" + path.join(__dirname, "/models/genderModel.json");
    let musicnn = new EssentiaModel.TensorflowMusiCNN(tf, modelPath);
    await musicnn.initialize();
    let predictions = await musicnn.predict(features);
    console.log("-> predictions", predictions);
};
</code>```
<p>I am trying to predict the genre of an audio file with essentia js models.
when I pass the features to the prediction model after extracting them correctly I get this tensor flow error ..
Tensorflow Js error </p>

Body:
const predictGenre = async (filename) => {
  console.log("*********** Predict Genre ***********");
    // eslint-disable-next-line no-undef
    const audioFilePath = musicPath + filename;
    //Decode Audio (Wav File)
    const audioBuffer = fs.readFileSync(audioFilePath);
    const preprocessedAudio = preprocess(audioBuffer);
    // Initialisation "musicnn"
    let features = {
      melSpectrum: [],
      batchSize: 0,
      melBandsSize: 96,
      patchSize: 187,
    };
    let frameSize = 512;
    let hopSize = 256;
    //Extract Features
    const extractor = new EssentiaModel.EssentiaTFInputExtractor(
      EssentiaWASM,
      "musicnn"
    );
    let wasm = EssentiaWASM;
    let essentia = extractor.essentia;
    features.melSpectrum = []; // ensure it's empty from previous runs
    let frames = essentia.FrameGenerator(preprocessedAudio, frameSize, hopSize);
    let audioLength = frames.size();
    for (var i = 0; i < audioLength; i++) {
      let frame = wasm.vectorToArray(frames.get(i));
      features.melSpectrum.push(extractor.compute(frame).melSpectrum);
    }
    //frames.delete();
    features.batchSize = features.melSpectrum.length;
    //Load Model
    const modelPath =
      //eslint-disable-next-line no-undef
      "file://" + path.join(__dirname, "/models/genderModel.json");
    let musicnn = new EssentiaModel.TensorflowMusiCNN(tf, modelPath);
    await musicnn.initialize();
    let predictions = await musicnn.predict(features);
    console.log("-> predictions", predictions);
};

I am trying to predict the genre of an audio file with essentia js models.
when I pass the features to the prediction model after extracting them correctly I get this tensor flow error ..
Tensorflow Js error


问:
Unable to convert bytes Uint8Array to string in javascript
I am unable to decrypt this Uint8Array

```<code>Uint8Array(32) [
    174, 157, 255, 238,  54, 143,  97, 132,
     70, 243,   7, 249,  98, 188,  68, 170,
     53,  82,  78,   9,  96, 226, 182, 160,
    131,  79,   3, 147, 153,  34, 205, 162
  ]
</code>```

using this code

```<code>const string = new TextDecoder().decode(hash);
console.log(string);
</code>```

I get this: ����Kc2Jk�&an↕�9���&��h-Lﺠ�Ԋ

I've also tried with many online converters but it says there's some problem with the byte array. This byte array is a response from an API.

Where Am I wrong? How can I convert it properly?

Body:
I am unable to decrypt this Uint8Array

Uint8Array(32) [
    174, 157, 255, 238,  54, 143,  97, 132,
     70, 243,   7, 249,  98, 188,  68, 170,
     53,  82,  78,   9,  96, 226, 182, 160,
    131,  79,   3, 147, 153,  34, 205, 162
  ]

using this code

const string = new TextDecoder().decode(hash);
console.log(string);

I get this: ����Kc2Jk�&an↕�9���&��h-Lﺠ�Ԋ

I've also tried with many online converters but it says there's some problem with the byte array. This byte array is a response from an API.

Where Am I wrong? How can I convert it properly?


问:
Failed to change MySQL port in XAMPP
I noticed that XAMPP and Docker don't mix so I tried to change the MySQL port to 3307 instead of Default 3306 but all tries failed.

My Steps:

Change the MySQL port from XAMPP Config [Services and Port Settings]

Modify in [\xampp\properties.ini]

Modify in [\xampp\mysql\bin\my.ini]

Modify in [\xampp\php\php.ini]

Add Port $cfg['Servers'][$i]['port'] = 3307; in [\xampp\phpMyAdmin\config.inc.php]

I tried to add the new port with host $cfg['Servers'][$i]['host'] = '127.0.0.1:3307'; But not working either.

Restrat PC and Start xampp as admin, and MySQL service still running on 3306.

What should I do?

Thanks

Title: Failed to change MySQL port in XAMPP


问:
How to ensure i can print inside for loop of pinescript for TD Sequential
I am trying to build a TD sequential Pinescript code as below.

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=4

study("TD Sequential", overlay=true)

// Set the number of bars for each stage of the TD Sequential
// The default is 13 bars for the Setup and 9 bars for the Countdown
setupLength = input(13, minval=1)
countdownLength = input(9, minval=1)

// Initialize variables for tracking the setup and countdown
setup = 0
countdown = 0

// Define a plot for the Setup levels
plot(setupLevels = series(na), color=red, linewidth=2)

// Define a plot for the Countdown levels
plot(countdownLevels = series(na), color=green, linewidth=2)

// Loop through all bars on the chart
for i = 0 to bar_index
    // Check if the current bar is a Setup bar
    if (high[i] >= high[i+1] and high[i] >= high[i+2] and low[i] <= low[i+1]) or (low[i] <= low[i+1] and low[i] <= low[i+2] and high[i] >= high[i+1])
        // Increment the setup count
        setup := setup + 1
    else
        // Reset the setup count if the current bar is not a Setup bar
        setup := 0

    // Check if the current bar is a Countdown bar
    if (high[i] >= high[i+1] and low[i] <= low[i+1]) or (low[i] <= low[i+1] and high[i] >= high[i+1])
        // Increment the countdown count
        countdown := countdown + 1
    else
        // Reset the countdown count if the current bar is not a Countdown bar
        countdown := 0

    // Plot the Setup and Countdown levels on the chart
    setupLevels[i] := setup >= setupLength ? high[i] : na
    countdownLevels[i] := countdown >= countdownLength ? low[i] : na
</code>```

However, I am getting an error message on the last two lines.

```<code>Compilation error. Line 41: Syntax error at input ':='.
</code>```

I am feeling clueless about how to fix it. I have defined the plot and trying to reuse inside the for loop.

Body:
I am trying to build a TD sequential Pinescript code as below.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=4

study("TD Sequential", overlay=true)

// Set the number of bars for each stage of the TD Sequential
// The default is 13 bars for the Setup and 9 bars for the Countdown
setupLength = input(13, minval=1)
countdownLength = input(9, minval=1)

// Initialize variables for tracking the setup and countdown
setup = 0
countdown = 0

// Define a plot for the Setup levels
plot(setupLevels = series(na), color=red, linewidth=2)

// Define a plot for the Countdown levels
plot(countdownLevels = series(na), color=green, linewidth=2)

// Loop through all bars on the chart
for i = 0 to bar_index
    // Check if the current bar is a Setup bar
    if (high[i] >= high[i+1] and high[i] >= high[i+2] and low[i] <= low[i+1]) or (low[i] <= low[i+1] and low[i] <= low[i+2] and high[i] >= high[i+1])
        // Increment the setup count
        setup := setup + 1
    else
        // Reset the setup count if the current bar is not a Setup bar
        setup := 0

    // Check if the current bar is a Countdown bar
    if (high[i] >= high[i+1] and low[i] <= low[i+1]) or (low[i] <= low[i+1] and high[i] >= high[i+1])
        // Increment the countdown count
        countdown := countdown + 1
    else
        // Reset the countdown count if the current bar is not a Countdown bar
        countdown := 0

    // Plot the Setup and Countdown levels on the chart
    setupLevels[i] := setup >= setupLength ? high[i] : na
    countdownLevels[i] := countdown >= countdownLength ? low[i] : na

However, I am getting an error message on the last two lines.

Compilation error. Line 41: Syntax error at input ':='.

I am feeling clueless about how to fix it. I have defined the plot and trying to reuse inside the for loop.


问:
Filtering Sylius Grid : Default Value
I have a really simple question and can't actually find an answer in the sylius documentation.

I have a grid that shows a client's order and thus far everything works.
I also have a date filter for this grid that works.

I am trying to set a default value to this date filter as the pages load. I tried several solutions and was hoping something like this should work :

```<code>filters:
    date:
         label: sylius.ui.date
         type: simple_date
         options:
             field: createdAt
             form_options:
                 criteria_date_from: first day of this month
</code>```

The idea here is pretty simple, to have a default value to the date filter, so only the orders matching the current month are displayed.

I could of course update the query to match, but then I wouldn't be able to remove the filter to access more data.

Title: Filtering Sylius Grid : Default Value

Body:
I have a really simple question and can't actually find an answer in the sylius documentation.

I have a grid that shows a client's order and thus far everything works.
I also have a date filter for this grid that works.

I am trying to set a default value to this date filter as the pages load. I tried several solutions and was hoping something like this should work :

filters:
    date:
         label: sylius.ui.date
         type: simple_date
         options:
             field: createdAt
             form_options:
                 criteria_date_from: first day of this month

The idea here is pretty simple, to have a default value to the date filter, so only the orders matching the current month are displayed.

I could of course update the query to match, but then I wouldn't be able to remove the filter to access more data.


问:
Unable to configure GCP API Gateway where endpoint is outside of GCP
I am trying to configure API Gateway on GCP console where the APIs are exposed at external web URL endpoint. I wish to fetch them and store the results in json in GCP cloud storage bucket. So the flow to retrive info is - External URI endpoint -> API Gateway (gcp) -> gcp storage bucket

Below is the URL that has exposed the APIs. I have the key and the element information. I am able to retrive the values via Power BI as well as curl command but I am unable to configure the API successfully on the GCP API Gateway service to fetch the same.

URL - https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements

```<code>Below curl command works -
curl -H X-User-Access-Token:xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements

Below is the openAPI specs file that is being provided on the console
# openapi2-functions.yaml
swagger: '2.0'
info:
  title: API_ID description
  description: Sample API on API Gateway  backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
host: 'https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements'
paths:
  /control-elements:
    get:
      summary: Greet a user
      operationId: control-elements
      security:
        - api_key: []
      responses:
       '200':
          description: A successful response
          schema:
            type: string
securityDefinitions:
  api_key:
    type: "apiKey"
    name: "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    in: "query"
</code>```

Error message -
Cannot convert to service config. 'location: "unknown location" kind: ERROR message: "Unable to parse the content. while parsing a block mapping\n in 'reader', line 2, column 1:\n swagger: '2.0'\n ^\nexpected , but found ''\n in 'reader', line 11, column 98:\n ... xxxxx/xxxxx/control-element's\n ^\n\n at [Source: (StringReader); line: 11, column: 98]" ' com.google.apps.framework.request.BadRequestException: Cannot convert to service config. 'location: "unknown location" kind: ERROR message: "Unable to parse the content. while parsing a block mapping\n in 'reader', line 2, column 1:\n swagger: '2.0'\n ^\nexpected , but found ''\n in 'reader', line 11, column 98:\n ... xxxxx/xxxxx/control-element's\n ^\n\n at [Source: (StringReader); line: 11, column: 98]" '

Attached is the screenshot of the values entered in the API Gateway service. Please advise on what is being missed over here

Data feed for API gateway service is as shown in screenshot

I tried altering the config in various ways. My service account has APIGateway-Admin access too. Curl as well as through Power BI, I am able to fetch API information from the mentioned URL too

Body:
I am trying to configure API Gateway on GCP console where the APIs are exposed at external web URL endpoint. I wish to fetch them and store the results in json in GCP cloud storage bucket. So the flow to retrive info is - External URI endpoint -> API Gateway (gcp) -> gcp storage bucket

Below is the URL that has exposed the APIs. I have the key and the element information. I am able to retrive the values via Power BI as well as curl command but I am unable to configure the API successfully on the GCP API Gateway service to fetch the same.

URL - https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements

Below curl command works -
curl -H X-User-Access-Token:xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements

Below is the openAPI specs file that is being provided on the console
# openapi2-functions.yaml
swagger: '2.0'
info:
  title: API_ID description
  description: Sample API on API Gateway  backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
host: 'https://xxxx.xxxxxxxx.com/cost/api/organizations/control-elements'
paths:
  /control-elements:
    get:
      summary: Greet a user
      operationId: control-elements
      security:
        - api_key: []
      responses:
       '200':
          description: A successful response
          schema:
            type: string
securityDefinitions:
  api_key:
    type: "apiKey"
    name: "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    in: "query"

Error message -
Cannot convert to service config. 'location: "unknown location" kind: ERROR message: "Unable to parse the content. while parsing a block mapping\n in 'reader', line 2, column 1:\n swagger: '2.0'\n ^\nexpected , but found ''\n in 'reader', line 11, column 98:\n ... xxxxx/xxxxx/control-element's\n ^\n\n at [Source: (StringReader); line: 11, column: 98]" ' com.google.apps.framework.request.BadRequestException: Cannot convert to service config. 'location: "unknown location" kind: ERROR message: "Unable to parse the content. while parsing a block mapping\n in 'reader', line 2, column 1:\n swagger: '2.0'\n ^\nexpected , but found ''\n in 'reader', line 11, column 98:\n ... xxxxx/xxxxx/control-element's\n ^\n\n at [Source: (StringReader); line: 11, column: 98]" '

Attached is the screenshot of the values entered in the API Gateway service. Please advise on what is being missed over here

Data feed for API gateway service is as shown in screenshot

I tried altering the config in various ways. My service account has APIGateway-Admin access too. Curl as well as through Power BI, I am able to fetch API information from the mentioned URL too


问:
Auto update import paths to alias in VS Code
I've been working on a project and implemented aliases midway. Is there a way in VS Code to automatically update all the import paths to the new aliases so that I don't have to do it manually.

From this:

```<code>import button from '../../components/common/button'
</code>```

To:

```<code>import button from '@components/common/button'
</code>```

Automatically over all of the files.

Body:
I've been working on a project and implemented aliases midway. Is there a way in VS Code to automatically update all the import paths to the new aliases so that I don't have to do it manually.

From this:

import button from '../../components/common/button'

To:

import button from '@components/common/button'

Automatically over all of the files.


问:
How to read a formated chain until a certain point in C?
I am currently struggling with file manipulations in C and still have a lot of reflexes to acquire.
My code is here :

```<code>int main(int argc, char *argv[])
{
    FILE* f = fopen("/Users/[...].txt","r+");
    int input1=0; int input2=0; int input3=0;

    fscanf(f,"sommets : %d\n",&input1);
    printf("%d\n",input1);
    fscanf(f,"transitions : %d\n",&input1);
    printf("%d\n",input1);
    printf("%ld\n",ftell(f));
    fscanf(f,"ARCS PRE\n");
    printf("%ld\n",ftell(f));
    long int point = ftell(f);
    char word[10]="ARCS POST"; char data[100];
    while((strcmp(word, fgets(data,100,f)))!=0){
        fseek(f,point-ftell(f), (int) ftell(f));  //to reposition the cursor after strcmp
        fscanf(f, "%d->%d,%d\n", &input1, &input2, &input3);
        printf("%d->%d,%d\n",input1, input2, input3);
        point =ftell(f);
    }
    fclose(f);

    return 0;
}
</code>```

The part which is not working is around the while : here is the file I try to read

```<code>sommets : 69
transitions : 9
ARCS PRE
1->2,5
1->3,7
ARCS POST
1->7,1
1->9,4
END
</code>```

The while is supposed to stop the reading once I reach "ARCS POST" in the file but never recognizes such a string, and it seems that the fseek in the loop doesn't want to work. In fact I also tried with SEEK_CUR but its value seems stuck to 1. Does anyone have an alternative for what I am trying to do ? Or does anyone know why nothing goes on this part as intended ?

Body:
I am currently struggling with file manipulations in C and still have a lot of reflexes to acquire.
My code is here :

int main(int argc, char *argv[])
{
    FILE* f = fopen("/Users/[...].txt","r+");
    int input1=0; int input2=0; int input3=0;

    fscanf(f,"sommets : %d\n",&input1);
    printf("%d\n",input1);
    fscanf(f,"transitions : %d\n",&input1);
    printf("%d\n",input1);
    printf("%ld\n",ftell(f));
    fscanf(f,"ARCS PRE\n");
    printf("%ld\n",ftell(f));
    long int point = ftell(f);
    char word[10]="ARCS POST"; char data[100];
    while((strcmp(word, fgets(data,100,f)))!=0){
        fseek(f,point-ftell(f), (int) ftell(f));  //to reposition the cursor after strcmp
        fscanf(f, "%d->%d,%d\n", &input1, &input2, &input3);
        printf("%d->%d,%d\n",input1, input2, input3);
        point =ftell(f);
    }
    fclose(f);

    return 0;
}

The part which is not working is around the while : here is the file I try to read

sommets : 69
transitions : 9
ARCS PRE
1->2,5
1->3,7
ARCS POST
1->7,1
1->9,4
END

The while is supposed to stop the reading once I reach "ARCS POST" in the file but never recognizes such a string, and it seems that the fseek in the loop doesn't want to work. In fact I also tried with SEEK_CUR but its value seems stuck to 1. Does anyone have an alternative for what I am trying to do ? Or does anyone know why nothing goes on this part as intended ?


问:
How to create a search widget in Wordpress with the theme Hello Elementor
I'm using the theme Hello Elementor for Wordpress and I want to include in the main menu a search option for giving the visitors the possibility of searching for an entry. I've seen that other themes include this possibility: they include a widget area in the menu, but I don't want to change my theme.

Would it be possible?

I have tried by creating a widget area by codding on PHP but it creates the search option below the menu, and I want it to be next to it.

This is the PHP code I've used:

functions.php

```<code>function register_widgets() {

 register_sidebar( array(
  'name' => __( 'After Content Widget Area'),
  'id' => 'after-content-widget-area',
  'description' => __( 'Widget area after the content' ),
  'before_widget' => '<div id="%1$s" class="widget-container %2$s">',
  'after_widget' => '</div>',
  'before_title' => '<h3 class="widget-title">',
  'after_title' => '</h3>',

 ) );

}
</code>```

header.php

```<code>if ( is_active_sidebar( 'after-content-widget-area' ) ) { ?>
 <aside class="after-content widget-area full-width" role="complementary">
  <?php dynamic_sidebar( 'after-content-widget-area' ); ?>
 </aside>
<?php }
</code>```

Body:
I'm using the theme Hello Elementor for Wordpress and I want to include in the main menu a search option for giving the visitors the possibility of searching for an entry. I've seen that other themes include this possibility: they include a widget area in the menu, but I don't want to change my theme.

Would it be possible?

I have tried by creating a widget area by codding on PHP but it creates the search option below the menu, and I want it to be next to it.

This is the PHP code I've used:

functions.php

function register_widgets() {

 register_sidebar( array(
  'name' => __( 'After Content Widget Area'),
  'id' => 'after-content-widget-area',
  'description' => __( 'Widget area after the content' ),
  'before_widget' => '
',
  'after_widget' => '
',
  'before_title' => '
',
  'after_title' => '
',

 ) );

}

header.php

if ( is_active_sidebar( 'after-content-widget-area' ) ) { ?>

  <?php dynamic_sidebar( 'after-content-widget-area' ); ?>

<?php }


问:
Could not decode base64 error when upload images
I am building Ecommerce in the MERN stack. Products can have multiple images. I use cloudinary to upload images. When I upload more pictures (slightly larger pictures) I get an error Could not decode base64 error.

This is my createProduct controller:

```<code>export const createProduct = async (req, res) => {
  const { name, description, price, color, size, quantity, category } =
    req.body;

  let images = [];

  if (typeof req.body.images === 'string') {
    images.push(req.body.images);
  } else {
    images = req.body.images;
  }

  const imagesLinks = [];

  for (let i = 0; i < images.length; i++) {
    const result = await cloudinary.v2.uploader.upload(images[i], {
      folder: 'products',
    });

    imagesLinks.push({
      public_id: result.public_id,
      url: result.secure_url,
    });
  }

  req.body.images = imagesLinks;

  const newProduct = new Product({
    name,
    description,
    quantity,
    images: imagesLinks,
    price,
    color: JSON.parse(color),
    size: JSON.parse(size),
    category,
    user: req.user.userId,
  });

  const product = await newProduct.save();

  res.status(StatusCodes.CREATED).json({ product });
};
</code>```

When I upload smaller images, I don't get an error and everything works great. Is there a solution to this problem, something like reducing the image size when uploading, changing it to webp format so that it takes up less space, or something similar?

Body:
I am building Ecommerce in the MERN stack. Products can have multiple images. I use cloudinary to upload images. When I upload more pictures (slightly larger pictures) I get an error Could not decode base64 error.

This is my createProduct controller:

export const createProduct = async (req, res) => {
  const { name, description, price, color, size, quantity, category } =
    req.body;

  let images = [];

  if (typeof req.body.images === 'string') {
    images.push(req.body.images);
  } else {
    images = req.body.images;
  }

  const imagesLinks = [];

  for (let i = 0; i < images.length; i++) {
    const result = await cloudinary.v2.uploader.upload(images[i], {
      folder: 'products',
    });

    imagesLinks.push({
      public_id: result.public_id,
      url: result.secure_url,
    });
  }

  req.body.images = imagesLinks;

  const newProduct = new Product({
    name,
    description,
    quantity,
    images: imagesLinks,
    price,
    color: JSON.parse(color),
    size: JSON.parse(size),
    category,
    user: req.user.userId,
  });

  const product = await newProduct.save();

  res.status(StatusCodes.CREATED).json({ product });
};

When I upload smaller images, I don't get an error and everything works great. Is there a solution to this problem, something like reducing the image size when uploading, changing it to webp format so that it takes up less space, or something similar?


问:
Python Subprocess not killing python script and command prompt
I have a python script (x) that starts another python script (y) using subprocess.Popen and a command prompt. It uses this command:

```<code>proc = Popen(["deactivate.bat", "&&", "cd", r'PathToScript', "&&", "call", r'.\\venv\Scripts\activate.bat', "&&", "SET", r"PYTHONPATH=PathToScript", "&&", "python", "main.py", "-t", "ArgumentValue", "%*"]
proc.poll()
... Do something ...
proc.terminate()
</code>```

I have also tried:

```<code>pid = proc.pid
os.kill(pid, signal.SIGTERM)
</code>```

But the same problem. Everything works as it should when it opens the python script (y), however, when it is supposed to close the script, it closes the console that runs the commands, but the console that shows the output from script y is still open, and script y is still running. The result that I want is the same as in Windows Task Manager (i.e. whenever I click end process on the command prompt, it closes the command prompt and in return it also automatically ends the python script (y), however, in my script (x) it only closes the command prompt.

Body:
I have a python script (x) that starts another python script (y) using subprocess.Popen and a command prompt. It uses this command:

proc = Popen(["deactivate.bat", "&&", "cd", r'PathToScript', "&&", "call", r'.\\venv\Scripts\activate.bat', "&&", "SET", r"PYTHONPATH=PathToScript", "&&", "python", "main.py", "-t", "ArgumentValue", "%*"]
proc.poll()
... Do something ...
proc.terminate()

I have also tried:

pid = proc.pid
os.kill(pid, signal.SIGTERM)

But the same problem. Everything works as it should when it opens the python script (y), however, when it is supposed to close the script, it closes the console that runs the commands, but the console that shows the output from script y is still open, and script y is still running. The result that I want is the same as in Windows Task Manager (i.e. whenever I click end process on the command prompt, it closes the command prompt and in return it also automatically ends the python script (y), however, in my script (x) it only closes the command prompt.


问:
I'm having a key error with using pytesseract on google colab , when the line pytesseract.image_to_string(img) is run
Here is my code. I used cv2 to load the jpeg image because for some weird reason pil couldn't load the image directly.

```<code>import pytesseract
import shutil
import os
import random
import cv2
from PIL import Image

img = cv2.imread('/content/believe in yourself.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img  = Image.fromarray(img)
extractedInformation = pytesseract.image_to_string(img)
print(extractedInformation)
</code>```

here was the error which i was facing.

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-38-e446955037e6> in <module>
----> 1 extractedInformation = pytesseract.image_to_string(img)
      2 print(extractedInformation)

5 frames
/usr/local/lib/python3.8/dist-packages/PIL/Image.py in save(self, fp, format, **params)
   2121         the resulting size will be rounded up.
   2122
-> 2123         :param factor: A greater than 0 integer or tuple of two integers
   2124            for width and height separately.
   2125         :param box: An optional 4-tuple of ints providing

KeyError: 'PNG'
</code>```

Body:
Here is my code. I used cv2 to load the jpeg image because for some weird reason pil couldn't load the image directly.

import pytesseract
import shutil
import os
import random
import cv2
from PIL import Image

img = cv2.imread('/content/believe in yourself.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img  = Image.fromarray(img)
extractedInformation = pytesseract.image_to_string(img)
print(extractedInformation)

here was the error which i was facing.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-38-e446955037e6> in <module>
----> 1 extractedInformation = pytesseract.image_to_string(img)
      2 print(extractedInformation)

5 frames
/usr/local/lib/python3.8/dist-packages/PIL/Image.py in save(self, fp, format, **params)
   2121         the resulting size will be rounded up.
   2122
-> 2123         :param factor: A greater than 0 integer or tuple of two integers
   2124            for width and height separately.
   2125         :param box: An optional 4-tuple of ints providing

KeyError: 'PNG'


问:
Is overriding generic_visit() more effective when transforming multiple types of AST Nodes within one inner class?
Suppose you have an inner class

```<code>class SomeTransformer(ast.NodeTransformer):

        def visit_Global(self, node):
                *transform AST*
                super().generic_visit(node)
                return node

        def visit_Assign(self, node):
                *transform AST*
                super().generic_visit(node)
                return node

        def visit_FunctionDef(self, node):
                *transform AST*
                super().generic_visit(node)
                return node
</code>```

Would it be more effective to override generic_visit() in a way below, because in the first version the whole tree will be traversed completely three times, looking for nodes of specific type only, while in the second version it will be transformed in a single traversal?

```<code>class SomeTransformer(ast.NodeTransformer):

  def generic_visit(self, node):

    for child in ast.iter_child_nodes(node):
        if isinstance(child, ast.Global):
            *transform AST*
        if isinstance(child, ast.Assign):
            *transform AST*
        if isinstance(child, ast.FunctionDef):
            *transform AST*

    return node
</code>```

Body:
Suppose you have an inner class

class SomeTransformer(ast.NodeTransformer):

        def visit_Global(self, node):
                *transform AST*
                super().generic_visit(node)
                return node

        def visit_Assign(self, node):
                *transform AST*
                super().generic_visit(node)
                return node

        def visit_FunctionDef(self, node):
                *transform AST*
                super().generic_visit(node)
                return node

Would it be more effective to override generic_visit() in a way below, because in the first version the whole tree will be traversed completely three times, looking for nodes of specific type only, while in the second version it will be transformed in a single traversal?

class SomeTransformer(ast.NodeTransformer):

  def generic_visit(self, node):

    for child in ast.iter_child_nodes(node):
        if isinstance(child, ast.Global):
            *transform AST*
        if isinstance(child, ast.Assign):
            *transform AST*
        if isinstance(child, ast.FunctionDef):
            *transform AST*

    return node


问:
How to bold mathematic symbol in plt.text($E_{m}$)?
I am having difficulty to bold the symbol in plt.text although i have tried using the method as \boldmath and weight="bold" but still cannot work. (Refer to the screenshot) Hence, I would like to seek you all advice on this.

I have tried using \boldmath and weight="bold" command and expect it works but end up did not work


问:
How to convert a two-dimensional array to CSV format using a function and return a string?
I need to write a function that converts a two-dimensional array to CSV and returns a string. Valid values as array elements are numbers and strings If a function is encountered, throw an error with the text "Unexpected value"

Example:

```<code>func([[1, 2], ['a', 'b']]) // '1,2 a,b'
func([[1, 2], ['a,b', 'c,d']]) // '1,2 "a,b","c,d"'
</code>```

I did this, the test "correctly escapes quotes" fails:

```<code>Expected: """"text""","other ""long"" text""
Received: ""text",other "long" text"
</code>```

My code:

```<code>function func(arr)
{ return arr
.map(array => array.map(e => {
let type = typeof e;
if (type !== "number" && type !== "string")
throw new Error("Unexpected value");
return (type === "string" && e.includes(",")) ? JSON.stringify(e) : e;
}).join(","))
.join("\n");
}
</code>```

Body:
I need to write a function that converts a two-dimensional array to CSV and returns a string. Valid values as array elements are numbers and strings If a function is encountered, throw an error with the text "Unexpected value"

Example:

func([[1, 2], ['a', 'b']]) // '1,2 a,b'
func([[1, 2], ['a,b', 'c,d']]) // '1,2 "a,b","c,d"'

I did this, the test "correctly escapes quotes" fails:

Expected: """"text""","other ""long"" text""
Received: ""text",other "long" text"

My code:

function func(arr)
{ return arr
.map(array => array.map(e => {
let type = typeof e;
if (type !== "number" && type !== "string")
throw new Error("Unexpected value");
return (type === "string" && e.includes(",")) ? JSON.stringify(e) : e;
}).join(","))
.join("\n");
}


问:
How to use Linux "watch" command with python script
I want to run a python script every 2 hours using the "watch" Linux command.

I choose watch because it can be output to the terminal, and it doesn't need any other files to be created (as I understand it, this is what cron requires)

I've tried the following commands, but the terminal just feezes when doing them:
watch -n 7200 'python test.py', watch -n 7200 'python test.py

If anyone could give me a hint on how to achive this, that would be great. Thank you very much.


问:
Unable to run Abp framework Angular project
I created a new solution using the following abp cli command:

abp new MyProject.Cloud -u angular --theme basic

The aspnetcore solution builds just fine and I have setup the database etc but I cant get the angular solution to build? I have run Yarn, then Yarn Start but I get the following error:

```<code>[error] Error: ENOENT: no such file or directory, lstat 'E:\Repositories\abpTest\angular\node_modules\@volo'
    at Object.realpathSync (node:fs:2552:7)
    at resolveGlobalStyles (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\webpack\configs\styles.js:64:33)
    at getStylesConfig (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\webpack\configs\styles.js:97:70)
    at E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\builders\dev-server\index.js:144:43
    at E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:75:16
    at generateWebpackConfig (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:64:40)
    at async generateBrowserWebpackConfigFromContext (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:125:20)
    at async generateI18nBrowserWebpackConfigFromContext (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:73:20)
    at async setup (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\builders\dev-server\index.js:141:47)
</code>```

The @volo folder does not exist in my node_modules folder but it does in the solution i created using the Commercial trial i had. I have used abp cli to logout from my account and also tried clean etc but I just cant get it working? Am i barking up the wrong tree or have I missed something?

Edit *
I have tried running it on my laptop too which has never had Abp Commercial on it so it must be to do with the basic theme?

Body:
I created a new solution using the following abp cli command:

abp new MyProject.Cloud -u angular --theme basic

The aspnetcore solution builds just fine and I have setup the database etc but I cant get the angular solution to build? I have run Yarn, then Yarn Start but I get the following error:

[error] Error: ENOENT: no such file or directory, lstat 'E:\Repositories\abpTest\angular\node_modules\@volo'
    at Object.realpathSync (node:fs:2552:7)
    at resolveGlobalStyles (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\webpack\configs\styles.js:64:33)
    at getStylesConfig (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\webpack\configs\styles.js:97:70)
    at E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\builders\dev-server\index.js:144:43
    at E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:75:16
    at generateWebpackConfig (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:64:40)
    at async generateBrowserWebpackConfigFromContext (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:125:20)
    at async generateI18nBrowserWebpackConfigFromContext (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\utils\webpack-browser-config.js:73:20)
    at async setup (E:\Repositories\abpTest\angular\node_modules\@angular-devkit\build-angular\src\builders\dev-server\index.js:141:47)

The @volo folder does not exist in my node_modules folder but it does in the solution i created using the Commercial trial i had. I have used abp cli to logout from my account and also tried clean etc but I just cant get it working? Am i barking up the wrong tree or have I missed something?

Edit *
I have tried running it on my laptop too which has never had Abp Commercial on it so it must be to do with the basic theme?


问:
Can we use multiple git accounts in vs code for pushing code to github?
I've two github accounts, and I want to use same device for multiple projects. Is there any way I can use two accounts at the same time in  VScode somehow without deleting git config again and again.

I've tried googling over git and see if I can use two accounts . I didn't find much on that. Only solution I could find is to delete the config and log in with different account again, which is very tedious.


问:
Error with BrowserRouter in ReactJS: react.development.js:209 Warning: Invalid hook call. Hooks can only be called
I set up my react app like this so far:

index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {BrowserRouter, Routes, Route} from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
        <Route path="/" exact component={App} />
    </BrowserRouter>
);
</code>```

App.js:

```<code>import './App.css';
import {useState, useEffect} from 'react';

function App() {
  const [drinks, setDrinks] = useState([]);

  const fetchData = async () => {
    const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list');
    const jsondata = await response.json();
    console.log(jsondata.drinks);
    setDrinks(jsondata.drinks);
  }

  useEffect(() => {
    fetchData();
  }, [])

  return (
    <div className="App">
    <ul>
     {drinks.map((item, index) => {
      return <li key={index}><a href="">{item.strCategory}</a></li>
     })}
    </ul>
    </div>
  );
}

export default App;
</code>```

But I'm getting this error in the console:

```<code>react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

I'm not sure why

Body:
I set up my react app like this so far:

index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {BrowserRouter, Routes, Route} from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
        <Route path="/" exact component={App} />
    </BrowserRouter>
);

App.js:

import './App.css';
import {useState, useEffect} from 'react';

function App() {
  const [drinks, setDrinks] = useState([]);

  const fetchData = async () => {
    const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list');
    const jsondata = await response.json();
    console.log(jsondata.drinks);
    setDrinks(jsondata.drinks);
  }

  useEffect(() => {
    fetchData();
  }, [])

  return (

     {drinks.map((item, index) => {
      return
{item.strCategory}

     })}

  );
}

export default App;

But I'm getting this error in the console:

react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I'm not sure why


问:
Buddypress members widget tab switching issue
When I click on the buttons shown by the arrows in the picture in the Buddypress member widget, it sends them to the /members/ page.

https://prnt.sc/wle-fYU8by2S

Normally, when the buttons on that page are clicked, the buttons need to change, not the page.
Please help with this.

for example: it should show the people who are the newest when you click on the newest button, when you click on the active button, it should show the ones that are active.


问:
Woocommerce Phone Field İnput Mask
The code below works fine, but I want no special characters to be entered including the period. In addition, the phone number like "534-055-7888", which it masks, is also shown on the admin panel in the same way. I want it to show as "5340557888" without "-" in admin panel but I couldn't.

`

```<code>add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_phone_us_format' );

function bbloomer_checkout_phone_us_format( $fields ) {
    $fields['billing']['billing_phone']['placeholder'] = '123-456-7890';
    $fields['billing']['billing_phone']['maxlength'] = 12; // 123-456-7890 is 12 chars long
    return $fields;
}

add_action( 'woocommerce_after_checkout_form', 'bbloomer_phone_mask_us' );

function bbloomer_phone_mask_us() {
   wc_enqueue_js( "
      $('#billing_phone')
      .keydown(function(e) {
         var key = e.which || e.charCode || e.keyCode || 0;
         var phone = $(this);
         if (key !== 8 && key !== 9) {
           if (phone.val().length === 3) {
            phone.val(phone.val() + '-'); // add dash after char #3
           }
           if (phone.val().length === 7) {
            phone.val(phone.val() + '-'); // add dash after char #7
           }
         }
         return (key == 8 ||
           key == 9 ||
           key == 46 ||
           (key >= 48 && key <= 57) ||
           (key >= 96 && key <= 105));
        });

   " );
}
</code>```

`

Title: Woocommerce Phone Field İnput Mask

Body:
The code below works fine, but I want no special characters to be entered including the period. In addition, the phone number like "534-055-7888", which it masks, is also shown on the admin panel in the same way. I want it to show as "5340557888" without "-" in admin panel but I couldn't.

`

add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_phone_us_format' );

function bbloomer_checkout_phone_us_format( $fields ) {
    $fields['billing']['billing_phone']['placeholder'] = '123-456-7890';
    $fields['billing']['billing_phone']['maxlength'] = 12; // 123-456-7890 is 12 chars long
    return $fields;
}

add_action( 'woocommerce_after_checkout_form', 'bbloomer_phone_mask_us' );

function bbloomer_phone_mask_us() {
   wc_enqueue_js( "
      $('#billing_phone')
      .keydown(function(e) {
         var key = e.which || e.charCode || e.keyCode || 0;
         var phone = $(this);
         if (key !== 8 && key !== 9) {
           if (phone.val().length === 3) {
            phone.val(phone.val() + '-'); // add dash after char #3
           }
           if (phone.val().length === 7) {
            phone.val(phone.val() + '-'); // add dash after char #7
           }
         }
         return (key == 8 ||
           key == 9 ||
           key == 46 ||
           (key >= 48 && key <= 57) ||
           (key >= 96 && key <= 105));
        });

   " );
}

`


问:
Selectize required tag breaks placeholder
I'm building a laravel project (version 9) and I need to use selectize.js for my select inputs.

I need to show a placeholder like "Select product" so users can click on it, search for items and choose one. And I need this field to be required.

Here's a sample select input :

```<code><select name="product_id" id="select_product" class="form-control my-3">
    <option value="">Select product</option>
    @foreach($products as $product)
            <option value="{{$product->id}}" data-price="{{$product->price}}" data-stock="{{$product->stock}}">{{$product->name}}</option>
    @endforeach
</select>
</code>```

This one works fine, it's not required though. And submiting the form with this field empty throws an error, I need it to be required on the front-end level.

BUT, when I add required to the select input, it doesn't show ANY of the options I'm loading inside select box with foreach loop. Doesn't even show a dropdown when I click on it.

Is there a way to have a placeholder and make the field required at the same time in select.js? If not, do you know any alternative to select.js that works with Laravel?

I also tried giving a placeholder through selectize function with JS, nothing changed, it shows placeholder but no items being shown (when the input has required tag).

```<code><select name="customer_id" class="form-control" id="select_customer" required>
    <option value=""></option>
    @forelse($customers as $customer)
        <option value="{{$customer->id}}">{{$customer->name}}</option>
    @empty
        <option value="" selected disabled>No customer found</option>
    @endforelse
</select>
</code>```
```<code>$('select').selectize({
    placeholder: 'Select something',
});
</code>```

Simplest way to put it : Select input doesn't show any options when I add required tag to it. (I'm loading options with laravel blade foreach loop.)

Body:
I'm building a laravel project (version 9) and I need to use selectize.js for my select inputs.

I need to show a placeholder like "Select product" so users can click on it, search for items and choose one. And I need this field to be required.

Here's a sample select input :

<select name="product_id" id="select_product" class="form-control my-3">
    <option value="">Select product</option>
    @foreach($products as $product)
            <option value="{{$product->id}}" data-price="{{$product->price}}" data-stock="{{$product->stock}}">{{$product->name}}</option>
    @endforeach
</select>

This one works fine, it's not required though. And submiting the form with this field empty throws an error, I need it to be required on the front-end level.

BUT, when I add required to the select input, it doesn't show ANY of the options I'm loading inside select box with foreach loop. Doesn't even show a dropdown when I click on it.

Is there a way to have a placeholder and make the field required at the same time in select.js? If not, do you know any alternative to select.js that works with Laravel?

I also tried giving a placeholder through selectize function with JS, nothing changed, it shows placeholder but no items being shown (when the input has required tag).

<select name="customer_id" class="form-control" id="select_customer" required>
    <option value=""></option>
    @forelse($customers as $customer)
        <option value="{{$customer->id}}">{{$customer->name}}</option>
    @empty
        <option value="" selected disabled>No customer found</option>
    @endforelse
</select>

$('select').selectize({
    placeholder: 'Select something',
});

Simplest way to put it : Select input doesn't show any options when I add required tag to it. (I'm loading options with laravel blade foreach loop.)


问:
How to use the pictureSize to set height and width?
I'm creating a project with expo, to capture photos and save them in the device's gallery. Where these photos must be the same height and width regardless of the device.

So, I want to define a height and width of the image captured by the camera, so that the result looks like this resize example.

For this, I thought about using the pictureSize type to set the height and width of the image captured by the camera.

I tried using react-native-image-crop-picker and react-native-image-resizer package and haven't been able to make any progress.

My project code is available at: CameraApp

Does anyone know how I can do this implementation?


问:
cordovaProj.create is not a function with Emberjs + corber
I'm trying to add corber to my existing EmberJS application. When I run
corber init then I get

stack: TypeError: cordovaProj.create is not a function
at Class.run (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/lib/targets/cordova/tasks/create-project.js:33:26)
at /Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/lib/tasks/create-project.js:97:24
at tryCatcher (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:326:21)
at invokeCallback (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:498:33)
at publish (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:484:9)
at flush (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:2441:7)
at process.processTicksAndRejections (node:internal/process/task_queues:77:11)

My env is:

ember-cli: 4.9.2
node: 18.12.1

How can I add corber and build mobile app with Ember?


问:
Woocommerce add order meta from checkbox
I have tried to make a checkbox whenever a specific product is added too the cart. The checkbox is working but i can't get the data in to the order meta. I want to show if the checkbox is checked in de order meta. Any help would be greatly appreciate!

The code i added to function.php

```<code>
// extra option checkout

add_action( 'woocommerce_checkout_fields', 'woo_add_conditional_checkout_fields' );

function woo_add_conditional_checkout_fields( $fields ) {

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];

            if( $product_id == 38 ) {
                $fields['billing']['billing_field_' . $product_id] = array(
                    'type'          => 'checkbox',
                    'label'     => __('Ik heb interesse in onderhoud op abonnementsbasis en wil hier graag meer informatie over tijdens het persoonlijk oriëntatiegesprek.'),
                    'placeholder'   => _x('Field for Product ' . $product_id, 'placeholder', 'woocommerce'),
                    'required'  => false,
                    'clear'     => true
                );
            }
    }
    // Return checkout fields.
    return $fields;

}

// checkbox meta
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'edit_woocommerce_checkout_page', 10, 1 );

function edit_woocommerce_checkout_page($order){
    global $post_id;
    $order = new WC_Order( $post_id );
    echo '<p><strong>'.__('Interesse in onderhoud op abbonementsbasis').':</strong> ' . get_post_meta($order->get_id(), 'billing_field_38', true ) . '</p>';
}
</code>```

Body:
I have tried to make a checkbox whenever a specific product is added too the cart. The checkbox is working but i can't get the data in to the order meta. I want to show if the checkbox is checked in de order meta. Any help would be greatly appreciate!

The code i added to function.php

// extra option checkout

add_action( 'woocommerce_checkout_fields', 'woo_add_conditional_checkout_fields' );

function woo_add_conditional_checkout_fields( $fields ) {

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];

            if( $product_id == 38 ) {
                $fields['billing']['billing_field_' . $product_id] = array(
                    'type'          => 'checkbox',
                    'label'     => __('Ik heb interesse in onderhoud op abonnementsbasis en wil hier graag meer informatie over tijdens het persoonlijk oriëntatiegesprek.'),
                    'placeholder'   => _x('Field for Product ' . $product_id, 'placeholder', 'woocommerce'),
                    'required'  => false,
                    'clear'     => true
                );
            }
    }
    // Return checkout fields.
    return $fields;

}

// checkbox meta
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'edit_woocommerce_checkout_page', 10, 1 );

function edit_woocommerce_checkout_page($order){
    global $post_id;
    $order = new WC_Order( $post_id );
    echo '
'.__('Interesse in onderhoud op abbonementsbasis').': ' . get_post_meta($order->get_id(), 'billing_field_38', true ) . '
';
}


问:
.NET Framework Cipher Suites Azure and older Windows OS's
After a pen test I have to implement a more strict Azure policy on the Web server.

As a result, client PC's running older versions of Windows, i.e., Vista and Windows 7, can no longer establish a TLS/SSL connection using .NET Framework 4.8. I need to have a secure policy whilst allowing older Windows OS's to connect.

I have checked the supported Cipher Suites for Windows 7 and one of the supported Cipher Suite (I am only focussing on one for the sake of simplicity) is:

TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA_P256

Whereas Azure supports

TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA

It appears that the Cipher names have to be an exact match.

Is the Elliptic Curve P256 just a variant of TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA or is it completely different?

Is there another approach I should adopt or am I trying to do the impossible?

I tried configuring Azure with the non Elliptic Curve variants but they were not available.

I am unable to modify the Windows machines that are attempting to connect to Azure.


问:
html2canvas send back to server react.js
It is going to be a long post, I appreciate your patience.

I'm trying to take a screenshot of <FormList /> component in the <TemplateRealEstate /> using html2canvas library and send to backend to server.

<FormList /> components return
 <FormItem />
. So basically, display some house informations.

I got so confused how to send back to server. I tested and it can display in the same page, but I need to display in another component that is nor child neither parent component. I tried with Context and didn't result. So I'm trying to send back to server to display.

<TemplateRealEstate /> rendering under http://localhost:3000/pages/:pageId. You need to create a page first to create templates. So page controllers normally takes

```<code>const createdPage = new Page({
    name,
    area,
    tema,
    type,
    creator,
    screenshot
  });
</code>```

and when I create page I got these field values;

```<code>area: "Real Estate"
creator: "63a6612aaa0e288b21afe2d2"
name: "LABA"
screenshot: undefined
tema: "Boho"
type: "Basic"
</code>```

After created page, and created template as well, I have a button to take a screenshot of a div in <TemplateRealEstate />

When I trigger button to set screenshot I got Successfully sent screenshot to server: {data: {…}, status: 201, statusText: 'Created', headers: AxiosHeaders, config: {…}, …} but does not add field as screenshot neither updates the value. It returns like this;

```<code>page:
area:"Real Estate"
creator:"63a6612aaa0e288b21afe2d2"
id:"63a6f6ed7e0d858bc283a79c"
name:"LABA"
tema:"Boho"
type:"Basic"
__v:0
_id:"63a6f6ed7e0d858bc283a79c"
</code>```

I've tried with all of Content-Types.

TemplateRealEstate.js

```<code>import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import domtoimage from "dom-to-image";
import html2canvas from "html2canvas";

import FormList from "../components/FormList";

import "./TemplateRealEstate.css";

const TemplateRealEstate = () => {
  const [loadedTemplates, setLoadedTemplates] = useState([]);
  const [screenshot, setScreenshot] = useState(null);
  const [screenshotFile, setScreenshotFile] = useState(null);
  const [screenshotUrl, setScreenshotUrl] = useState(null);

  const pageId = useParams().pageId;

  // Define a helper function to convert a data URI to a Blob object
  const dataURItoBlob = (dataURI) => {
    // Convert the data URI to a binary string
    const binaryString = window.atob(dataURI.split(",")[1]);

    // Get the MIME type from the data URI
    const mimeType = dataURI.split(",")[0].split(":")[1].split(";")[0];

    // Create an ArrayBuffer from the binary string
    const arrayBuffer = new ArrayBuffer(binaryString.length);
    const uint8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < binaryString.length; i++) {
      uint8Array[i] = binaryString.charCodeAt(i);
    }

    // Return the Blob object
    return new Blob([arrayBuffer], { type: mimeType });
  };

  const handleScreenshot = () => {
    // Select the element you want to take a screenshot of
    const element = document.getElementById("my-element");

    // Use the html2canvas function to render the element as a canvas element
    html2canvas(element)
      .then((canvas) => {
        const dataURI = canvas.toDataURL();

        // Convert the data URI to a Blob object
        const blob = dataURItoBlob(dataURI);

        // Set the screenshot file
        setScreenshotFile(blob);

        // Create a new FormData object
        const formData = new FormData();

        // Add the screenshot as a file field to the form
        formData.append("screenshot", blob, "screenshot.png");

        // Set the screenshot as a prop or state variable in the NewPage component

        // Send the screenshot to the backend
        axios
          .patch(`http://localhost:8080/api/pages/${pageId}`, formData, {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
          .then((res) => {
            console.log("Successfully sent screenshot to server:", res);
            setScreenshot(formData);
          })
          .catch((err) => {
            console.error("Failed to send screenshot to server:", err);
          });
      })
      .catch((error) => {
        console.error("Failed to take screenshot:", error);
      });
  };

  useEffect(() => {
    if (screenshotFile) {
      // Create a new FileReader object
      const reader = new FileReader();

      // Set the onload event handler
      reader.onload = (event) => {
        // Set the screenshot data URL
        setScreenshotUrl(event.target.result);
      };

      // Read the image file
      reader.readAsDataURL(screenshotFile);
    }
  }, [screenshotFile]);

  return (
    <div>
      <div id="my-element">
        <FormList items={loadedTemplates} />
      </div>
      <button onClick={redirectToForm}>Add house</button>

      <button type="button" onClick={handleScreenshot}>
        Set screenshot
      </button>
      <button onClick={handleDelete}>Delete Page</button>
    </div>
  );
};

export default TemplateRealEstate;
</code>```

Page controller in server

```<code>// PATCH http://localhost:8080/api/pages/:pid
const updatePageById = async (req, res, next) => {
  //const stores the address of the object and not the object it self
  const pageId = req.params.pid;
  const screenshot = req.file;

  try {
    page = await Page.findById(pageId);
  } catch (err) {
    const error = new HttpError(
      // this error will display if our get request generally has some kind of a problem
      "Something went wrong, could not update a page with that ID.",
      500
    );
    return next(error);
  }

  // applying if statement, won't lose the data if the user only wants to update one field instead of given all req.body
  if (screenshot) page.screenshot = screenshot;

  try {
    await page.save();
  } catch (err) {
    const error = new HttpError(
      "Something went wrong, could not update page",
      500
    );
    return next(error);
  }

  res.status(201).json({ page: page.toObject({ getters: true }) });
};
</code>```

Body:
It is going to be a long post, I appreciate your patience.

I'm trying to take a screenshot of <FormList /> component in the <TemplateRealEstate /> using html2canvas library and send to backend to server.

<FormList /> components return
 <FormItem />
. So basically, display some house informations.

I got so confused how to send back to server. I tested and it can display in the same page, but I need to display in another component that is nor child neither parent component. I tried with Context and didn't result. So I'm trying to send back to server to display.

<TemplateRealEstate /> rendering under http://localhost:3000/pages/:pageId. You need to create a page first to create templates. So page controllers normally takes

const createdPage = new Page({
    name,
    area,
    tema,
    type,
    creator,
    screenshot
  });

and when I create page I got these field values;

area: "Real Estate"
creator: "63a6612aaa0e288b21afe2d2"
name: "LABA"
screenshot: undefined
tema: "Boho"
type: "Basic"

After created page, and created template as well, I have a button to take a screenshot of a div in <TemplateRealEstate />

When I trigger button to set screenshot I got Successfully sent screenshot to server: {data: {…}, status: 201, statusText: 'Created', headers: AxiosHeaders, config: {…}, …} but does not add field as screenshot neither updates the value. It returns like this;

page:
area:"Real Estate"
creator:"63a6612aaa0e288b21afe2d2"
id:"63a6f6ed7e0d858bc283a79c"
name:"LABA"
tema:"Boho"
type:"Basic"
__v:0
_id:"63a6f6ed7e0d858bc283a79c"

I've tried with all of Content-Types.

TemplateRealEstate.js

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import domtoimage from "dom-to-image";
import html2canvas from "html2canvas";

import FormList from "../components/FormList";

import "./TemplateRealEstate.css";

const TemplateRealEstate = () => {
  const [loadedTemplates, setLoadedTemplates] = useState([]);
  const [screenshot, setScreenshot] = useState(null);
  const [screenshotFile, setScreenshotFile] = useState(null);
  const [screenshotUrl, setScreenshotUrl] = useState(null);

  const pageId = useParams().pageId;

  // Define a helper function to convert a data URI to a Blob object
  const dataURItoBlob = (dataURI) => {
    // Convert the data URI to a binary string
    const binaryString = window.atob(dataURI.split(",")[1]);

    // Get the MIME type from the data URI
    const mimeType = dataURI.split(",")[0].split(":")[1].split(";")[0];

    // Create an ArrayBuffer from the binary string
    const arrayBuffer = new ArrayBuffer(binaryString.length);
    const uint8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < binaryString.length; i++) {
      uint8Array[i] = binaryString.charCodeAt(i);
    }

    // Return the Blob object
    return new Blob([arrayBuffer], { type: mimeType });
  };

  const handleScreenshot = () => {
    // Select the element you want to take a screenshot of
    const element = document.getElementById("my-element");

    // Use the html2canvas function to render the element as a canvas element
    html2canvas(element)
      .then((canvas) => {
        const dataURI = canvas.toDataURL();

        // Convert the data URI to a Blob object
        const blob = dataURItoBlob(dataURI);

        // Set the screenshot file
        setScreenshotFile(blob);

        // Create a new FormData object
        const formData = new FormData();

        // Add the screenshot as a file field to the form
        formData.append("screenshot", blob, "screenshot.png");

        // Set the screenshot as a prop or state variable in the NewPage component

        // Send the screenshot to the backend
        axios
          .patch(`http://localhost:8080/api/pages/${pageId}`, formData, {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
          .then((res) => {
            console.log("Successfully sent screenshot to server:", res);
            setScreenshot(formData);
          })
          .catch((err) => {
            console.error("Failed to send screenshot to server:", err);
          });
      })
      .catch((error) => {
        console.error("Failed to take screenshot:", error);
      });
  };

  useEffect(() => {
    if (screenshotFile) {
      // Create a new FileReader object
      const reader = new FileReader();

      // Set the onload event handler
      reader.onload = (event) => {
        // Set the screenshot data URL
        setScreenshotUrl(event.target.result);
      };

      // Read the image file
      reader.readAsDataURL(screenshotFile);
    }
  }, [screenshotFile]);

  return (

        <FormList items={loadedTemplates} />

      <button onClick={redirectToForm}>Add house</button>

      <button type="button" onClick={handleScreenshot}>
        Set screenshot
      </button>
      <button onClick={handleDelete}>Delete Page</button>

  );
};

export default TemplateRealEstate;

Page controller in server

// PATCH http://localhost:8080/api/pages/:pid
const updatePageById = async (req, res, next) => {
  //const stores the address of the object and not the object it self
  const pageId = req.params.pid;
  const screenshot = req.file;

  try {
    page = await Page.findById(pageId);
  } catch (err) {
    const error = new HttpError(
      // this error will display if our get request generally has some kind of a problem
      "Something went wrong, could not update a page with that ID.",
      500
    );
    return next(error);
  }

  // applying if statement, won't lose the data if the user only wants to update one field instead of given all req.body
  if (screenshot) page.screenshot = screenshot;

  try {
    await page.save();
  } catch (err) {
    const error = new HttpError(
      "Something went wrong, could not update page",
      500
    );
    return next(error);
  }

  res.status(201).json({ page: page.toObject({ getters: true }) });
};


问:
AnyLogic executeExpression exception
I am using AnyLogic 8 Professional 8.8.1. In my model I sample a repair time for a component that failed from a distribution that is configurable through an input file. To achieve this I specify the distribution in the input file as a String and then in the model, call the executeExpression after each failure to get the downtime for the component.

I have done this for various classes (agent types) in my model and have combined all the logic in a superclass, which the various components merely extend this class.

So far it worked perfectly (except for the annoying 1.6 JVM message see this question) until I tried to add the functionality to another agent. I simply made this agent also extend the superclass, so it is the exact same code executing.

Executing Expression triangular(82.0,287.0,123.0)
Expression returned: 150.21341253179259
Tue Apr 01 21:23:10 CAT 2025: stockyardFeed1 has broken down
Updating status
Executing Expression triangular(82.0,287.0,123.0)
Annotation processing got disabled, since it requires a 1.6 compliant JVM
----------
1. ERROR in \nmet_terminal_model\Expression_9_xjal.java (at line 75)
    public class Expression_9_xjal extends nmet_terminal_model.Schematic$17{
                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The nested type nmet_terminal_model.Schematic$17 cannot be referenced using its binary name
----------
2. ERROR in \nmet_terminal_model\Expression_9_xjal.java (at line 78)
    return triangular(82.0,287.0,123.0);
           ^^^^^^^^^^
The method triangular(double, double, double) is undefined for the type Expression_9_xjal.Performer
----------
2 problems (2 errors)
Exception during discrete event execution:
Truncated class file```

To make it even more confusing is that I added a traceln writing the distribution to execute and its answer in the specific function and when making the distribution the same as another type of component in the input file you will notice that the first two lines in the console output works fine, but then when trying to run the exact same - it throws the error.

Title: AnyLogic executeExpression exception

Body:
I am using AnyLogic 8 Professional 8.8.1. In my model I sample a repair time for a component that failed from a distribution that is configurable through an input file. To achieve this I specify the distribution in the input file as a String and then in the model, call the executeExpression after each failure to get the downtime for the component.

I have done this for various classes (agent types) in my model and have combined all the logic in a superclass, which the various components merely extend this class.

So far it worked perfectly (except for the annoying 1.6 JVM message see this question) until I tried to add the functionality to another agent. I simply made this agent also extend the superclass, so it is the exact same code executing.

Executing Expression triangular(82.0,287.0,123.0)
Expression returned: 150.21341253179259
Tue Apr 01 21:23:10 CAT 2025: stockyardFeed1 has broken down
Updating status
Executing Expression triangular(82.0,287.0,123.0)
Annotation processing got disabled, since it requires a 1.6 compliant JVM
----------
1. ERROR in \nmet_terminal_model\Expression_9_xjal.java (at line 75)
    public class Expression_9_xjal extends nmet_terminal_model.Schematic$17{
                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The nested type nmet_terminal_model.Schematic$17 cannot be referenced using its binary name
----------
2. ERROR in \nmet_terminal_model\Expression_9_xjal.java (at line 78)
    return triangular(82.0,287.0,123.0);
           ^^^^^^^^^^
The method triangular(double, double, double) is undefined for the type Expression_9_xjal.Performer
----------
2 problems (2 errors)
Exception during discrete event execution:
Truncated class file

To make it even more confusing is that I added a traceln writing the distribution to execute and its answer in the specific function and when making the distribution the same as another type of component in the input file you will notice that the first two lines in the console output works fine, but then when trying to run the exact same - it throws the error.


问:
How to achieve different reactions at the first and second button click when there are many the same buttons? (Filter in js)
there is a filter on the js, which consists of three identical buttons (named "green", "yellow", "red"), which are responsible for setting/removing the blur effect for the set of pictures located below.
When pressing the "green" button, a blur effect should be set for all pictures that have a value "green" of data-card property.
At the second click on the same button, the blur effect should be canceled for this category of pictures.
I solved this problem with a reception with a boolean flag:

```<code>let firstClick = true;

if (firstClick){
//..do at first click

firstClick = !firstClick;
}
else{
//..do at second click

firstClick = !firstClick;
}
</code>```

However, the problem occurs when I click on the "green" button (this is the first click on the "green" button), and after that on another button, for example "red" (this is the first click on the "red" button). But the compiler perceives a click on the "red" button as a second click, although it is a different button.
The question is how to distinguish the behavior in different buttons?

In general, I solved the problem through a complete search and many if statements. Maybe there is an alternative way?

Project demo in codepen

//main.js
function app() {
  const buttons = document.querySelectorAll('.service__btn');
  const cards = document.querySelectorAll('.service__item');
  let firstClick = true;

  function setBlour(listOfCards) {
    listOfCards.forEach(item => {
      if (item.classList.contains(currentCategory)) {
        item.classList.add('blur');
      }
    });
  }

  function resetBlour(listOfCards) {
    listOfCards.forEach(item => {
      if (item.classList.contains(currentCategory)) {
        item.classList.remove('blur');
      }
    });
  }

  function highlightButton(butt) {
    if (!butt.classList.contains('service__btn__clicked')) {
      butt.classList.add('service__btn__clicked');
    }

    firstClick = !firstClick;
  }

  function unhighlight(butt) {
    if (butt.classList.contains('service__btn__clicked')) {
      butt.classList.remove('service__btn__clicked');
    }

    firstClick = !firstClick;
  }

  buttons.forEach(button => {
    button.addEventListener('click', (event) => {
      currentCategory = event.target.dataset.filter; //current category we get from clicked button
      let matchedCards = document.querySelectorAll(`[data-card="${button.dataset.filter}"]`);
      //is it first click?
      if (firstClick) {
        if (!matchedCards[0].classList.contains('blur')) { // each click we have set of matchedCards, it's easy to check one of them (the first for example) if it have blur
          setBlour(matchedCards);
          highlightButton(button);
        } else { //it is a first clcik, but card have blur - so remove blur
          resetBlour(matchedCards);
          unhighlight(button);
        }
      }
      //second click
      else {
        if (!matchedCards[0].classList.contains('blur')) { //if there is no blur - add blur
          setBlour(matchedCards);
          highlightButton(button);
        } else { //second click and blur is present - so we need to remove it
          resetBlour(matchedCards);
          unhighlight(button);
        }
      }
    });
  });
}
app()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
}

a {
  text-decoration: none;
}

li {
  list-style-type: none;
}

.container {
  width: 1220px;
  margin: 0 auto;
}

.service {
  background: #EDF2EC;
  padding-top: 40px;
  padding-bottom: 70px;
}

.service__top {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.service__top-title {
  font-family: 'Inika', serif;
  font-weight: 400;
  font-size: 40px;
  line-height: 52px;
  color: #499A18;
  max-width: 306px;
}

.service__filter-btn {
  margin-left: 142px;
}

.service__btn {
  border: 1px solid #E06733;
  border-radius: 5px;
  padding: 12px 40px;
  font-family: 'Inika', serif;
  font-weight: 400;
  font-size: 20px;
  line-height: 26px;
  color: #E06733;
}

.service__btn__clicked {
  background: #E06733;
  border: 1px solid #E06733;
  border-radius: 5px;
  color: #FFFFFF;
}

.service__btn+.service__btn {
  margin-left: 32px;
}

.service__content {
  column-count: 3;
  gap: 0 116px;
}

.service__item {
  margin-bottom: 55px;
  text-align: center;
  width: 330px;
  height: 350px;
  border-radius: 20px;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

.service__item-title {
  font-family: 'Inter', sans-serif;
  font-weight: 700;
  font-size: 20px;
  line-height: 20px;
  color: #E06733;
  margin-top: 10px;
  margin-bottom: 10px;
}

.service__item-text {
  font-family: 'Inter', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 20px;
  color: #717171;
  margin-bottom: 36px;
}

.service__item-description {
  border-radius: 0px 0px 20px 20px;
  border: 1px solid #e3e1d5;
  display: none;
}

.blur {
  filter: blur(5px);
}

.animation {
  transform: scale(0);
  opacity: 0;
}</code>```

          Caption and Description

          <button class="service__btn service__btn-type_green" data-filter="green"> Green</button>
          <button class="service__btn service__btn-type_yellow" data-filter="yellow">Yellow</button>
          <button class="service__btn service__btn-type_red" data-filter="red">Red</button>

Green color

Description

Red color

Description

Yellow color

Description

Red color

Description

Green color

Description

Red color

Description

```

Body:
there is a filter on the js, which consists of three identical buttons (named "green", "yellow", "red"), which are responsible for setting/removing the blur effect for the set of pictures located below.
When pressing the "green" button, a blur effect should be set for all pictures that have a value "green" of data-card property.
At the second click on the same button, the blur effect should be canceled for this category of pictures.
I solved this problem with a reception with a boolean flag:

let firstClick = true;

if (firstClick){
//..do at first click

firstClick = !firstClick;
}
else{
//..do at second click

firstClick = !firstClick;
}

However, the problem occurs when I click on the "green" button (this is the first click on the "green" button), and after that on another button, for example "red" (this is the first click on the "red" button). But the compiler perceives a click on the "red" button as a second click, although it is a different button.
The question is how to distinguish the behavior in different buttons?

In general, I solved the problem through a complete search and many if statements. Maybe there is an alternative way?

Project demo in codepen

//main.js
function app() {
  const buttons = document.querySelectorAll('.service__btn');
  const cards = document.querySelectorAll('.service__item');
  let firstClick = true;

  function setBlour(listOfCards) {
    listOfCards.forEach(item => {
      if (item.classList.contains(currentCategory)) {
        item.classList.add('blur');
      }
    });
  }

  function resetBlour(listOfCards) {
    listOfCards.forEach(item => {
      if (item.classList.contains(currentCategory)) {
        item.classList.remove('blur');
      }
    });
  }

  function highlightButton(butt) {
    if (!butt.classList.contains('service__btn__clicked')) {
      butt.classList.add('service__btn__clicked');
    }

    firstClick = !firstClick;
  }

  function unhighlight(butt) {
    if (butt.classList.contains('service__btn__clicked')) {
      butt.classList.remove('service__btn__clicked');
    }

    firstClick = !firstClick;
  }

  buttons.forEach(button => {
    button.addEventListener('click', (event) => {
      currentCategory = event.target.dataset.filter; //current category we get from clicked button
      let matchedCards = document.querySelectorAll(`[data-card="${button.dataset.filter}"]`);
      //is it first click?
      if (firstClick) {
        if (!matchedCards[0].classList.contains('blur')) { // each click we have set of matchedCards, it's easy to check one of them (the first for example) if it have blur
          setBlour(matchedCards);
          highlightButton(button);
        } else { //it is a first clcik, but card have blur - so remove blur
          resetBlour(matchedCards);
          unhighlight(button);
        }
      }
      //second click
      else {
        if (!matchedCards[0].classList.contains('blur')) { //if there is no blur - add blur
          setBlour(matchedCards);
          highlightButton(button);
        } else { //second click and blur is present - so we need to remove it
          resetBlour(matchedCards);
          unhighlight(button);
        }
      }
    });
  });
}
app()

html {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
}

a {
  text-decoration: none;
}

li {
  list-style-type: none;
}

.container {
  width: 1220px;
  margin: 0 auto;
}

.service {
  background: #EDF2EC;
  padding-top: 40px;
  padding-bottom: 70px;
}

.service__top {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.service__top-title {
  font-family: 'Inika', serif;
  font-weight: 400;
  font-size: 40px;
  line-height: 52px;
  color: #499A18;
  max-width: 306px;
}

.service__filter-btn {
  margin-left: 142px;
}

.service__btn {
  border: 1px solid #E06733;
  border-radius: 5px;
  padding: 12px 40px;
  font-family: 'Inika', serif;
  font-weight: 400;
  font-size: 20px;
  line-height: 26px;
  color: #E06733;
}

.service__btn__clicked {
  background: #E06733;
  border: 1px solid #E06733;
  border-radius: 5px;
  color: #FFFFFF;
}

.service__btn+.service__btn {
  margin-left: 32px;
}

.service__content {
  column-count: 3;
  gap: 0 116px;
}

.service__item {
  margin-bottom: 55px;
  text-align: center;
  width: 330px;
  height: 350px;
  border-radius: 20px;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

.service__item-title {
  font-family: 'Inter', sans-serif;
  font-weight: 700;
  font-size: 20px;
  line-height: 20px;
  color: #E06733;
  margin-top: 10px;
  margin-bottom: 10px;
}

.service__item-text {
  font-family: 'Inter', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 20px;
  color: #717171;
  margin-bottom: 36px;
}

.service__item-description {
  border-radius: 0px 0px 20px 20px;
  border: 1px solid #e3e1d5;
  display: none;
}

.blur {
  filter: blur(5px);
}

.animation {
  transform: scale(0);
  opacity: 0;
}

          Caption and Description

          <button class="service__btn service__btn-type_green" data-filter="green"> Green</button>
          <button class="service__btn service__btn-type_yellow" data-filter="yellow">Yellow</button>
          <button class="service__btn service__btn-type_red" data-filter="red">Red</button>

Green color

Description

Red color

Description

Yellow color

Description

Red color

Description

Green color

Description

Red color

Description