问:
NestJs TypeOrm loadRelationCountAndMap apply order by operation on it
I am new in NestJs TypeORM and I tried to get the count only from the relation table using loadRelationCountAndMap method and now I need a fetuare to change the order of that count ASC or DESC but when I tried the orderBy method it will return me unknow colunm name.

Here is my query

```<code>await this.userRepository
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.roles', 'roles')
    .loadRelationCountAndMap('user.postCount', 'user.post', 'post', qb =>
    qb.where('post.type =:type', { type: 'post' }),)
    .loadRelationCountAndMap('user.userSpotCount', 'user.spot', 'spot')
    .loadRelationCountAndMap(
    'user.itineraryCount',
    'user.post',
    'post',
    qb => qb.where('post.type =:type', { type: 'itinerary' }),)
    .where('roles.name = :name', { name: request.user_type })
    .orderBy('userSpotCount', 'ASC');
</code>```

and the output is without orderBy method

```<code>[{
        "id": xxxxx,
        "name": "xxxx xxxx",
        "email": "xxxx.xxxx@xxxx.xxx",
        "facebook_id": null,
        "google_id": null,
        "apple_id": null,
        "is_email_verifie": null,
        "is_phone_verifie": null,
        "created_at": "2022-06-06T23:38:04.000Z",
        "updated_at": "2022-06-06T23:38:04.000Z",
        "phone": "1234567890",
        "token": null,
        "profile_pic": "",
        "status": "pending",
        "email_token": null,
        "deleted_at": null,
        "latitude": "26.78965",
        "longitude": "93.78965",
        "is_public": null,
        "basedIn": null,
        "visit_place": null,
        "visit_place_lat": null,
        "visit_place_long": null,
        "notification_flag": "on",
        "location": "abc, xyz, pqr",
        "country_code": null,
        "home_key": 1,
        "postCount": 0,
        "userSpotCount": 5,
        "itineraryCount": 0
      },
      {
        "id": xxxxx,
        "name": "xxxx xxxx",
        "email": "xxxx.xxxx@xxxx.xxx",
        "facebook_id": null,
        "google_id": null,
        "apple_id": null,
        "is_email_verifie": null,
        "is_phone_verifie": null,
        "created_at": "2022-06-06T23:38:04.000Z",
        "updated_at": "2022-06-06T23:38:04.000Z",
        "phone": "1234567890",
        "token": null,
        "profile_pic": "",
        "status": "pending",
        "email_token": null,
        "deleted_at": null,
        "latitude": "26.78965",
        "longitude": "93.78965",
        "is_public": null,
        "basedIn": null,
        "visit_place": null,
        "visit_place_lat": null,
        "visit_place_long": null,
        "notification_flag": "on",
        "location": "abc, xyz, pqr",
        "country_code": null,
        "home_key": 1,
        "postCount": 0,
        "userSpotCount": 1,
        "itineraryCount": 0
      }
]
</code>```

I need this output as per the order by ASC/DESC

Body:
I am new in NestJs TypeORM and I tried to get the count only from the relation table using loadRelationCountAndMap method and now I need a fetuare to change the order of that count ASC or DESC but when I tried the orderBy method it will return me unknow colunm name.

Here is my query

await this.userRepository
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.roles', 'roles')
    .loadRelationCountAndMap('user.postCount', 'user.post', 'post', qb =>
    qb.where('post.type =:type', { type: 'post' }),)
    .loadRelationCountAndMap('user.userSpotCount', 'user.spot', 'spot')
    .loadRelationCountAndMap(
    'user.itineraryCount',
    'user.post',
    'post',
    qb => qb.where('post.type =:type', { type: 'itinerary' }),)
    .where('roles.name = :name', { name: request.user_type })
    .orderBy('userSpotCount', 'ASC');

and the output is without orderBy method

[{
        "id": xxxxx,
        "name": "xxxx xxxx",
        "email": "xxxx.xxxx@xxxx.xxx",
        "facebook_id": null,
        "google_id": null,
        "apple_id": null,
        "is_email_verifie": null,
        "is_phone_verifie": null,
        "created_at": "2022-06-06T23:38:04.000Z",
        "updated_at": "2022-06-06T23:38:04.000Z",
        "phone": "1234567890",
        "token": null,
        "profile_pic": "",
        "status": "pending",
        "email_token": null,
        "deleted_at": null,
        "latitude": "26.78965",
        "longitude": "93.78965",
        "is_public": null,
        "basedIn": null,
        "visit_place": null,
        "visit_place_lat": null,
        "visit_place_long": null,
        "notification_flag": "on",
        "location": "abc, xyz, pqr",
        "country_code": null,
        "home_key": 1,
        "postCount": 0,
        "userSpotCount": 5,
        "itineraryCount": 0
      },
      {
        "id": xxxxx,
        "name": "xxxx xxxx",
        "email": "xxxx.xxxx@xxxx.xxx",
        "facebook_id": null,
        "google_id": null,
        "apple_id": null,
        "is_email_verifie": null,
        "is_phone_verifie": null,
        "created_at": "2022-06-06T23:38:04.000Z",
        "updated_at": "2022-06-06T23:38:04.000Z",
        "phone": "1234567890",
        "token": null,
        "profile_pic": "",
        "status": "pending",
        "email_token": null,
        "deleted_at": null,
        "latitude": "26.78965",
        "longitude": "93.78965",
        "is_public": null,
        "basedIn": null,
        "visit_place": null,
        "visit_place_lat": null,
        "visit_place_long": null,
        "notification_flag": "on",
        "location": "abc, xyz, pqr",
        "country_code": null,
        "home_key": 1,
        "postCount": 0,
        "userSpotCount": 1,
        "itineraryCount": 0
      }
]

I need this output as per the order by ASC/DESC


来源: stackexchange

问:
using sjPlot with different random covariance structure
In a mixed model design, I changed the random covariance structure to diagonal:

```<code>library(sjPlot)
library(nlme)
model<- lme(fixed= DV~ IV1*IV2+ IV3 + IV4 + IV5,
control=list(opt="nlminb"), data=data,
                   random = list(id=pdDiag(~1+IV1*IV2)),
                   na.action=na.omit)
</code>```

When I try to use plot_model from the package
"sjPlot" with this model:

```<code>plot_model(model,type="pred",terms=c("V1","V2"),mdrt.values="meansd")
</code>```

It writes the error:

```<code>Error in gregexpr(pattern = "\\|", re)[[1]] : subscript out of bounds
</code>```

here is a data sample:

```<code>set.seed(42)
n <- 90
data <- data.frame ( id = rep(1:6, each = 15),
                  DV=rnorm(n),
                  IV1=rnorm(n),
                  IV2=rnorm(n),
                  IV3=rnorm(n),
                  IV4=rnorm(n),
                  IV5=rnorm(n)
                  )
</code>```

Would be grateful for an answer

ContentLicense: CC BY-SA 4.0

Body:
In a mixed model design, I changed the random covariance structure to diagonal:

library(sjPlot)
library(nlme)
model<- lme(fixed= DV~ IV1*IV2+ IV3 + IV4 + IV5,
control=list(opt="nlminb"), data=data,
                   random = list(id=pdDiag(~1+IV1*IV2)),
                   na.action=na.omit)

When I try to use plot_model from the package
"sjPlot" with this model:

plot_model(model,type="pred",terms=c("V1","V2"),mdrt.values="meansd")

It writes the error:

Error in gregexpr(pattern = "\\|", re)[[1]] : subscript out of bounds

here is a data sample:

set.seed(42)
n <- 90
data <- data.frame ( id = rep(1:6, each = 15),
                  DV=rnorm(n),
                  IV1=rnorm(n),
                  IV2=rnorm(n),
                  IV3=rnorm(n),
                  IV4=rnorm(n),
                  IV5=rnorm(n)
                  )

Would be grateful for an answer


问:
Remove h1- and h3-tags around logo and filter-titles on Zella-Theme for Wordpress/WooCom
I'm using the
Zella Theme
(and a child theme) for Wordpress / WooCom and I want to remove the h1 tag around the logo and the h3 tag around the filter title on the web shop's page.

How do I do it in the best way?

I've looked through the files and can't find anything to run a filter or hook on.


问:
How to do left join with tables with composite key and condition?
Table1

Table2

I would like to join these table so that I need fruits with number 1 and fruits with number 12.

It should look like this:
Query

The problem is even if I use left join I still need a criteria that it should be 12 or nothing, but if it doesnt exist in the second table it wont show it.


问:
Commercejs PayPal checkout internal error
I am running into an internal error when trying to capture the checkout order with PayPal. When I run commerce.checkout.capture with paypal gateway and relevant details (payerId and paymentid) it throws a 500 internal error with this error message:

```<code>{
    "message": "Unsuccessful response (500: ) received",
    "statusCode": 500,
    "statusText": "",
    "data": {
        "status_code": 500,
        "error": {
            "message": "There was an internal error. We have been notified.",
            "type": "internal_error"
        },
        "id": "e231f6adc6e3469b95468b770ee2c5b1"
    },
    "originalError": {
        "message": "Request failed with status code 500",
        "name": "Error",
        "stack": "Error: Request failed with status code 500\n    at e.exports (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:27209)\n    at e.exports (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:29644)\n    at XMLHttpRequest.y (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:22514)",
        "config": {
            "url": "checkouts/chkt_gvRjwOGzeew4mN",
            "method": "post",
            "data": "{\"customer\":{\"firstname\":\"Matthew\",\"lastname\":\"Bloemetje\",\"email\":\"mattb007@gmail.com\"},\"payment\":{\"id\":\"gway_9l6LJmxJE8Oyo1\",\"gateway\":\"paypal\",\"paypal\":{\"action\":\"capture\",\"payment_id\":\"0YE34089FH8264019\",\"payer_id\":\"Q29FF5HGE63PG\"}}}",
            "headers": {
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json",
                "X-Authorization": "pk_47885dbdd0e55e008c1c4982d9e35fb2c99247830bdc9",
                "X-Chec-Agent": "commerce.js/v2",
                "Chec-Version": "2021-09-29"
            },
            "params": null,
            "baseURL": "https://api.chec.io/v1/",
            "transformRequest": [
                null
            ],
            "transformResponse": [
                null
            ],
            "timeout": 60000,
            "xsrfCookieName": "XSRF-TOKEN",
            "xsrfHeaderName": "X-XSRF-TOKEN",
            "maxContentLength": -1,
            "maxBodyLength": -1,
            "transitional": {
                "silentJSONParsing": true,
                "forcedJSONParsing": true,
                "clarifyTimeoutError": false
            }
        }
    }
}
</code>```

I tried to capture the paypal checkout data with commerce.checkout.capture. Expected to return order data with success message and redirect to confirmation page of the order

Body:
I am running into an internal error when trying to capture the checkout order with PayPal. When I run commerce.checkout.capture with paypal gateway and relevant details (payerId and paymentid) it throws a 500 internal error with this error message:

{
    "message": "Unsuccessful response (500: ) received",
    "statusCode": 500,
    "statusText": "",
    "data": {
        "status_code": 500,
        "error": {
            "message": "There was an internal error. We have been notified.",
            "type": "internal_error"
        },
        "id": "e231f6adc6e3469b95468b770ee2c5b1"
    },
    "originalError": {
        "message": "Request failed with status code 500",
        "name": "Error",
        "stack": "Error: Request failed with status code 500\n    at e.exports (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:27209)\n    at e.exports (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:29644)\n    at XMLHttpRequest.y (https://www.alchemyremember.me/app-33ce862eff9a0d293497.js:2:22514)",
        "config": {
            "url": "checkouts/chkt_gvRjwOGzeew4mN",
            "method": "post",
            "data": "{\"customer\":{\"firstname\":\"Matthew\",\"lastname\":\"Bloemetje\",\"email\":\"mattb007@gmail.com\"},\"payment\":{\"id\":\"gway_9l6LJmxJE8Oyo1\",\"gateway\":\"paypal\",\"paypal\":{\"action\":\"capture\",\"payment_id\":\"0YE34089FH8264019\",\"payer_id\":\"Q29FF5HGE63PG\"}}}",
            "headers": {
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json",
                "X-Authorization": "pk_47885dbdd0e55e008c1c4982d9e35fb2c99247830bdc9",
                "X-Chec-Agent": "commerce.js/v2",
                "Chec-Version": "2021-09-29"
            },
            "params": null,
            "baseURL": "https://api.chec.io/v1/",
            "transformRequest": [
                null
            ],
            "transformResponse": [
                null
            ],
            "timeout": 60000,
            "xsrfCookieName": "XSRF-TOKEN",
            "xsrfHeaderName": "X-XSRF-TOKEN",
            "maxContentLength": -1,
            "maxBodyLength": -1,
            "transitional": {
                "silentJSONParsing": true,
                "forcedJSONParsing": true,
                "clarifyTimeoutError": false
            }
        }
    }
}

I tried to capture the paypal checkout data with commerce.checkout.capture. Expected to return order data with success message and redirect to confirmation page of the order


问:
AWS TimeStream Java SDK - configure max number of columns
I am using the AWS timestream Java SDK to query timestream table.

My code

String query = """
            SELECT
              Response,
              ResponseSize,
              RequestSize,
              Url,
              StatusCode,
              time AS RequestTime,
              measure_value::bigint AS RequestDuration
            FROM (table name)
            WHERE (clause)
            """;
QueryRequest queryRequest = QueryRequest.builder()
        .queryString(query)
        .build();

var queryResult = timestreamQueryClient.query(queryRequest);

System.out.println(queryResult.rows().size()); // 5000
```
<p>The response contains all of the columns but with 0 rows and says there are more results. In the AWS console query editor, all works fine.</p>
<p>Experimentally I found out that if I select 7 cols max in the select statement it works. I wanted to use <code>SELECT *</code> and that's how I found out about it</p>
<p>In the code above if I just add one more col in the select 'TestId' the number of rows becomes 0</p>
<pre class="lang-java prettyprint-override"><code>String query = """
            SELECT
              TestId,
              Response,
              ResponseSize,
              RequestSize,
              Url,
              StatusCode,
              time AS RequestTime,
              measure_value::bigint AS RequestDuration
            FROM (table name)
            WHERE (clause)
            """;
QueryRequest queryRequest = QueryRequest.builder()
        .queryString(query)
        .build();

var queryResult = timestreamQueryClient.query(queryRequest);

System.out.println(queryResult.rows().size()); // 0 Rows
</code>```

Both request are successful.

So first of all is there a way to set this number somehow in the SDK and secondly is this a bug? I would expect the response to be 400 telling me that max cols are (something) and not an empty row list.

Body:
I am using the AWS timestream Java SDK to query timestream table.

My code

String query = """
            SELECT
              Response,
              ResponseSize,
              RequestSize,
              Url,
              StatusCode,
              time AS RequestTime,
              measure_value::bigint AS RequestDuration
            FROM (table name)
            WHERE (clause)
            """;
QueryRequest queryRequest = QueryRequest.builder()
        .queryString(query)
        .build();

var queryResult = timestreamQueryClient.query(queryRequest);

System.out.println(queryResult.rows().size()); // 5000

The response contains all of the columns but with 0 rows and says there are more results. In the AWS console query editor, all works fine.

Experimentally I found out that if I select 7 cols max in the select statement it works. I wanted to use SELECT * and that's how I found out about it

In the code above if I just add one more col in the select 'TestId' the number of rows becomes 0

String query = """
            SELECT
              TestId,
              Response,
              ResponseSize,
              RequestSize,
              Url,
              StatusCode,
              time AS RequestTime,
              measure_value::bigint AS RequestDuration
            FROM (table name)
            WHERE (clause)
            """;
QueryRequest queryRequest = QueryRequest.builder()
        .queryString(query)
        .build();

var queryResult = timestreamQueryClient.query(queryRequest);

System.out.println(queryResult.rows().size()); // 0 Rows

Both request are successful.

So first of all is there a way to set this number somehow in the SDK and secondly is this a bug? I would expect the response to be 400 telling me that max cols are (something) and not an empty row list.


问:
Run a script every day at a certain time automatically javascript
I have a visual studio code project with a main function main() in javascript, which I would like to run every day at 8am automatically without doing anything. Is there any way?
main function

I've seen things related to setInterval and so on but this doesn't run my project automatically.


问:
Firebase FCM API Scheduled
I tried to figure out if it's possible to manage notifications which are created / planned via FCM API, as it can be done in the firebase dashboard.

Is there any way to get an ID, when notifications are created/planned, which can be used to modify / delete the planned push notification, before they are sent?

I'm working in a PHP environment

Title: Firebase FCM API Scheduled


问:
How to get the time when Caffine cache is emptied due to project restart
Requirements:
There has a huge number of data from rabbitMq every hour, but the environment is not stable and may cause the project restart and data lack. I want to know the number of the data lack when it occure everyday. Beacuse the volume of data is huge I have to use caffine cache. The large volume of data led me to use caffine caching instead of using database record information. Now the problem is that when the project is restarted, the data in the Caffine cache is cleared and I have no way of knowing when a data miss occurs.

I used to use mongodb to record the time I received data and calcute the time period


问:
How to set default select values from drop down for multiple fields using mat-select-autocomplete
I'm using a custom plugin to display the custom form, which will show several dynamic multiple drop-down fields. However, I'm having trouble with the default value not being selected from the drop-down menu.

```<code><mat-select-autocomplete
                    [placeholder]="'Options Selection'"
                    [options]="filter.items"
                    [display]="'label'"
                    [value]="'value'"
                    [multiple]='true'
                    [labelCount]="2"
                    [selectedOptions]="selectedValuesMap.get(filter)"
                    (selectionChange)="getSelectedOptions($event, filter)">
</code>```

I tried using [formControl] and [(ngModel)] attributes but not working. I want to set the default value from the drop down for all the different field drop downs

Body:
I'm using a custom plugin to display the custom form, which will show several dynamic multiple drop-down fields. However, I'm having trouble with the default value not being selected from the drop-down menu.

<mat-select-autocomplete
                    [placeholder]="'Options Selection'"
                    [options]="filter.items"
                    [display]="'label'"
                    [value]="'value'"
                    [multiple]='true'
                    [labelCount]="2"
                    [selectedOptions]="selectedValuesMap.get(filter)"
                    (selectionChange)="getSelectedOptions($event, filter)">

I tried using [formControl] and [(ngModel)] attributes but not working. I want to set the default value from the drop down for all the different field drop downs


问:
How to debug cmake
I am trying to figure out why configure step for Qt6.4 on MacOS fails.

As investigating logs and googling leads nowhere I started to debug underlying cmake.

Now I am in function that looks like:

```<code>function(qt_evaluate_to_boolean expressionVar)
    if(${${expressionVar}})
        set(${expressionVar} ON PARENT_SCOPE)
    else()
        set(${expressionVar} OFF PARENT_SCOPE)
    endif()
endfunction()
</code>```

Where expressionVar is TEST_openssl_headers.

The result of this operation is FALSE. I need to know why.

In the logs there is no TEST_openssl_headers, so apparently the test compilation is not even called.

Why? How can I know what happens at the "if" line? Where it calls? How does it evaluate if it is true?

Title: How to debug cmake

Body:
I am trying to figure out why configure step for Qt6.4 on MacOS fails.

As investigating logs and googling leads nowhere I started to debug underlying cmake.

Now I am in function that looks like:

function(qt_evaluate_to_boolean expressionVar)
    if(${${expressionVar}})
        set(${expressionVar} ON PARENT_SCOPE)
    else()
        set(${expressionVar} OFF PARENT_SCOPE)
    endif()
endfunction()

Where expressionVar is TEST_openssl_headers.

The result of this operation is FALSE. I need to know why.

In the logs there is no TEST_openssl_headers, so apparently the test compilation is not even called.

Why? How can I know what happens at the "if" line? Where it calls? How does it evaluate if it is true?


问:
How to call function once on max length of input in Angular?
Here is simple function I want to call confirm when input length = 6 but the issue in this way is that some time it call multiple time same function on max length. I want to call function once only when max length reach.

```<code> onOtpChange(event: any) {
    if (event.length == 6) {
      this.authcode = event
      this.confirm();
    }
  }
</code>```

Call function at once on max input length

Body:
Here is simple function I want to call confirm when input length = 6 but the issue in this way is that some time it call multiple time same function on max length. I want to call function once only when max length reach.

 onOtpChange(event: any) {
    if (event.length == 6) {
      this.authcode = event
      this.confirm();
    }
  }

Call function at once on max input length


问:
Laravel : Why i got 403 error after submit form in laravel
I submitted value of special characters in form and i got 403 error.

I stored <!DOCTYPE html> this type of values but database not accept to this type of values so how can i solve this error?

Blade file:

```<code><form action="submit-course-detail" method="POST" accept-charset="UTF-8">
                    @csrf
                    <label>Course Name</label>
                    <select name="course_name" class="form-control" style="width:70%;">
                        <option value="">Select Course Name</option>
                        @foreach($course as $cou)
                        <option value="{{ $cou->id }}">{{ $cou->course_name }}</option>
                        @endforeach
                    </select>
                    <label class="mt-4">Topic Name</label>
                    <input class="form-control" name="topic_name" placeholder="Enter Topic Name" style="width:70%;">
                    <script src="https://cdn.ckeditor.com/4.19.1/full/ckeditor.js"></script>
                    <label class="mt-4">Description 1</label>
                    <textarea name="desc_one" placeholder="Write your code"></textarea>
                    <script>
                            CKEDITOR.replace( 'desc_one' );
                    </script>
                    <label class="mt-4">Description 2</label>
                    <textarea name="desc_two" placeholder="Write your code"></textarea>
                    <script>
                            CKEDITOR.replace( 'desc_two' );
                    </script>

                    <button type="submit" class="btn btn-success mt-3">Submit</button>
                </form>
</code>```

in this desc_one and desc_two is not accept character value so how to solve?

Body:
I submitted value of special characters in form and i got 403 error.

I stored <!DOCTYPE html> this type of values but database not accept to this type of values so how can i solve this error?

Blade file:

<form action="submit-course-detail" method="POST" accept-charset="UTF-8">
                    @csrf
                    Course Name
                    <select name="course_name" class="form-control" style="width:70%;">
                        <option value="">Select Course Name</option>
                        @foreach($course as $cou)
                        <option value="{{ $cou->id }}">{{ $cou->course_name }}</option>
                        @endforeach
                    </select>
                    Topic Name
                    <input class="form-control" name="topic_name" placeholder="Enter Topic Name" style="width:70%;">

                    Description 1
                    <textarea name="desc_one" placeholder="Write your code"></textarea>

                    Description 2
                    <textarea name="desc_two" placeholder="Write your code"></textarea>

                    <button type="submit" class="btn btn-success mt-3">Submit</button>
                </form>

in this desc_one and desc_two is not accept character value so how to solve?


问:
python: Access Blocked with google Authenticate
I am using the google authenticate flow and works great when credentials are granted. However, if user Access is Blocked (i.e a user that is not in the business organisation was trying to access), the code hangs. Is there any way to force the code to timeout? or capture the fact that the access was blocked.

Thanks in advance

```<code>creds = None

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
           loc + 'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
    return creds
</code>```

Body:
I am using the google authenticate flow and works great when credentials are granted. However, if user Access is Blocked (i.e a user that is not in the business organisation was trying to access), the code hangs. Is there any way to force the code to timeout? or capture the fact that the access was blocked.

Thanks in advance

creds = None

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
           loc + 'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
    return creds


问:
Javascript: How can I display a timer variable inside the canvas?
I have made this simple program which currently triggers a red circle to travel upwards if the question answered is correctly ,which in turn increases the score.I have now decided to introduce a timer which should display in the centre of the canvas and when the timer runs out it should display and alert with the score they got and to restart.The problem I have is not the timer working,but its not displaying as it is below the canvas,where you'll see a timer counting down.If you test the program it clearly shows the "count" in the canvas,but because count is not linked to an id it gets very confusing for me,i don't know how to go about it, can someone please help me out.</p>
```<code> <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    width: 100%;
    background-color: black;
}
</style>
</head>

<h1 align="center"></h1>my jumper game </h1>
<p align="center"> </p>A Fun flappy-bird like game</p><//p>

<div>
<p>What is 10 times 4 ? <input type ="number" id="Q1"></p>
<p>What is 5 * 5 ? <input type ="number" id="Q2"></p>
<p>What is 5 * 3 ? <input type ="number" id="Q3"></p>
<button onclick="submitAnswers()">Submit</button>

</div>

<canvas id="canvas" width="900" height="400">
  Your browser does not support the HTML5 canvas tag.

</canvas>
<br> </br>

<body onload="startGame()">

<div>Time left = <span id="timer"></span>
<script>

window.onload = function() {
  let btn = document.getElementById("submitAnswers");
  btn.onclick = jump;

};

document.getElementById('timer').innerHTML =
  01 + ":" + 11;
startTimer();

function startTimer() {
  var presentTime = document.getElementById('timer').innerHTML;
  var timeArray = presentTime.split(/[:]+/);
  var m = timeArray[0];
  var s = checkSecond((timeArray[1] - 1));
  if(s==59){m=m-1}
  if(m<0){
    return
  }

  document.getElementById('timer').innerHTML =
    m + ":" + s;
  console.log(m)
  setTimeout(startTimer, 1000);

}

function checkSecond(sec) {
  if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
  if (sec < 0) {sec = "59"};
  return sec;
}

function submitAnswers(){

  const answer1 = document.querySelector("#Q1").value
  if (answer1 == 40)

  jump();

  const answer2 = document.querySelector("#Q2").value
  if (answer2 == 25)
  jump();

}

let count = 0;

let timer = 'timer';

function jump() {
    count += 1;
    //changing the y position
    y -= 25;
    //clearing the canvas
    context.clearRect(0, 0, 600, 400);

    //redrawing the circle
    context.beginPath();
    context.arc(x, y, 50, 0, 2 * Math.PI);
    context.fillStyle="red";
    context.fill();

    //drawing the count value
    context.font = '25px Arial';
    context.fillStyle = 'white';

  context.fillText("Count: " + count, 20, 30);

  context.font = '25px Arial';
    context.fillStyle = 'white';

  context.fillText("Timer: " + timer, 200, 30);

if (y <= 0) {
            y = 350  ;
        }
        window.requestAnimationFrame(draw);

}

var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var x = 450;
    var y = 350;

</script>

</body>
</html>
</code>```

Body:
I have made this simple program which currently triggers a red circle to travel upwards if the question answered is correctly ,which in turn increases the score.I have now decided to introduce a timer which should display in the centre of the canvas and when the timer runs out it should display and alert with the score they got and to restart.The problem I have is not the timer working,but its not displaying as it is below the canvas,where you'll see a timer counting down.If you test the program it clearly shows the "count" in the canvas,but because count is not linked to an id it gets very confusing for me,i don't know how to go about it, can someone please help me out.

 <!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

my jumper game

A Fun flappy-bird like game
<//p>

What is 10 times 4 ? <input type ="number" id="Q1">

What is 5 * 5 ? <input type ="number" id="Q2">

What is 5 * 3 ? <input type ="number" id="Q3">

<button onclick="submitAnswers()">Submit</button>

<canvas id="canvas" width="900" height="400">
  Your browser does not support the HTML5 canvas tag.

</canvas>

Time left =


问:
thymeleaf header doesnt display as it should
I am new to Thymeleaf and I'm simply trying to include a navigation bar in my pages.

I tried to use the code sample from the Thymeleaf documentation, some code samples from SO and from other websites but everytime the navigation bar doesn't display. However, I can see a menu, but this is not what I want.

header.html :

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>navbar</title>

</head>
    <body>

        <nav th:fragment="navbar" class="navbar navbar-inverse navbar-static-top">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" th:href="@{/}">Homepage</a>
                </div>
                <ul class="nav navbar-nav">
                    <li><a class="nav-link" th:href="@{/itinerary}">Itinerary</a></li>
                </ul>
            </div>
        </nav>

    </body>
</html>
</code>```

index.html :

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Homepage</title>
</head>
<body>

<div th:replace="fragments/header"> </div>

</body>
</html>
</code>```

file structure :

templates

fragments

header.html

index.html

I was expecting to see a navigation bar, but this is the result :

result

Body:
I am new to Thymeleaf and I'm simply trying to include a navigation bar in my pages.

I tried to use the code sample from the Thymeleaf documentation, some code samples from SO and from other websites but everytime the navigation bar doesn't display. However, I can see a menu, but this is not what I want.

header.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>navbar</title>

                    Homepage

Itinerary

index.html :

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Homepage</title>

file structure :

templates

fragments

header.html

index.html

I was expecting to see a navigation bar, but this is the result :

result


问:
Access USB device on Mac in python using pyusb an libusb
I would like to read the signal from a USB keyboard that is attached to my MacBook Pro. I am using PyCharm to write my script and I installed pyusb and libusb for the backend. Really, I am at the very beginning so please excuse my little knowledge. The problems I am faced with is that I do [Errno 13] permission error when running the script in PyCharm or when saving it and running it with PyLauncher I get a "No backend available error".

The final aim of this project is to control the vlc-media player using the vlc module based on the input of a usb device.

The current code:

```<code>import usb
import libusb_package
backend = libusb_package.get_libusb1_backend()

# find device
keyboard = usb.core.find(idVendor=0x046d, idProduct=0xc318, backend = backend)

if keyboard is None:
    raise ValueError('ADU Device not found. Please ensure it is connected.')
    sys.exit(1)

usb.util.claim_interface(keyboard, 0)
</code>```

I would really appreciate any hints or suggestions what packages to use, which tutorials to read for usb devices and python and how to improve in this project.

Thank you very much!

All the best,

ie

Body:
I would like to read the signal from a USB keyboard that is attached to my MacBook Pro. I am using PyCharm to write my script and I installed pyusb and libusb for the backend. Really, I am at the very beginning so please excuse my little knowledge. The problems I am faced with is that I do [Errno 13] permission error when running the script in PyCharm or when saving it and running it with PyLauncher I get a "No backend available error".

The final aim of this project is to control the vlc-media player using the vlc module based on the input of a usb device.

The current code:

import usb
import libusb_package
backend = libusb_package.get_libusb1_backend()

# find device
keyboard = usb.core.find(idVendor=0x046d, idProduct=0xc318, backend = backend)

if keyboard is None:
    raise ValueError('ADU Device not found. Please ensure it is connected.')
    sys.exit(1)

usb.util.claim_interface(keyboard, 0)

I would really appreciate any hints or suggestions what packages to use, which tutorials to read for usb devices and python and how to improve in this project.

Thank you very much!

All the best,

ie


问:
Get elasticsearch to ignore diacritics and accents in search hit
I want to search data on elasticsearch with different languages, and expect the data will be retrieved no matter if there is a diacritics or accent.

``
for example I have this data:

``

```<code>POST ابجد/_doc/31
{
  "name":"def",
  "city":"Tulkarem"
}
</code>```

``

POST ابجٌد/_doc/31 { "name":"def", "city":"Tulkarem" }

```<code>PUT /abce
{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "default" : {
                    "tokenizer" : "standard",
                    "filter" : ["my_ascii_folding"]
                }
            },
            "filter" : {
                "my_ascii_folding" : {
                    "type" : "asciifolding",
                    "preserve_original" : true
                }
            }
        }
    }
}
</code>```

The difference between the two indexes is the diacritics.

Trying to get data:

GET ابجد/_search

I need it to retrieve both index, currently it is revering this:

```<code>`{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "ابجد",
        "_id": "31",
        "_score": 1,
        "_source": {
          "name": "def",
          "city": "Tulkarem"
        }
      }
    ]
  }
}
</code>```

Body:
I want to search data on elasticsearch with different languages, and expect the data will be retrieved no matter if there is a diacritics or accent.

``
for example I have this data:

``

POST ابجد/_doc/31
{
  "name":"def",
  "city":"Tulkarem"
}

``

POST ابجٌد/_doc/31 { "name":"def", "city":"Tulkarem" }

PUT /abce
{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "default" : {
                    "tokenizer" : "standard",
                    "filter" : ["my_ascii_folding"]
                }
            },
            "filter" : {
                "my_ascii_folding" : {
                    "type" : "asciifolding",
                    "preserve_original" : true
                }
            }
        }
    }
}

The difference between the two indexes is the diacritics.

Trying to get data:

GET ابجد/_search

I need it to retrieve both index, currently it is revering this:

`{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "ابجد",
        "_id": "31",
        "_score": 1,
        "_source": {
          "name": "def",
          "city": "Tulkarem"
        }
      }
    ]
  }
}


问:
Using TimeoutHandler to stop processing the request after 1 sec on server side
I was going through this document related to timeouts and deadlines for HTTP servers in Go. It is a good doc, but I have one question on http.TimeoutHandler.

```<code>func slowHandler(w http.ResponseWriter, req *http.Request) {
    time.Sleep(10 * time.Second)
    log.Print("Slow API call done after 10 seconds")
    io.WriteString(w, "I am slow!\n")
}

func main() {
    srv := http.Server{
        Addr:         ":8888",
        WriteTimeout: 5 * time.Second,
        Handler:      http.TimeoutHandler(http.HandlerFunc(slowHandler), 1*time.Second, "Timeout!\n"),
    }

    if err := srv.ListenAndServe(); err != nil {
        fmt.Printf("Server failed: %s\n", err)
    }
}
</code>```

In the doc, it is mentioned that

After a second, our TimeoutHandler will kick in, stop processing the slowHandler, and return a plain “Timeout!” message

curl request output:

```<code># time curl localhost:8888
*   Trying 127.0.0.1:8888...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8888 (#0)
> GET / HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 503 Service Unavailable
< Date: Wed, 14 Dec 2022 10:19:15 GMT
< Content-Length: 9
< Content-Type: text/plain; charset=utf-8
<
Timeout!
* Connection #0 to host localhost left intact
curl localhost:8888 -v  0.01s user 0.01s system 1% cpu 1.018 total
</code>```

Indeed, the response is sent back in 1 sec.

But I also noticed that I got this message in server logs after approx 10 seconds.

```<code>2022/12/14 15:49:24 Slow API call done after 10 seconds
</code>```

15:49:24 in GMT would be 10:19:24

So, I guess the slowHandler was still processing the request in the background and wasn't canceled by TimeoutHandler. It was still running in the background.

Am I understanding this correctly? And if so, then what would happen if slowHandler has an infinite loop - something like this?

```<code>func slowHandler(w http.ResponseWriter, req *http.Request) {
    for {} //infinite loop
    log.Print("infinite loop")
    io.WriteString(w, "I am slow!\n")
}
</code>```

Will it keep running forever in the background?

Body:
I was going through this document related to timeouts and deadlines for HTTP servers in Go. It is a good doc, but I have one question on http.TimeoutHandler.

func slowHandler(w http.ResponseWriter, req *http.Request) {
    time.Sleep(10 * time.Second)
    log.Print("Slow API call done after 10 seconds")
    io.WriteString(w, "I am slow!\n")
}

func main() {
    srv := http.Server{
        Addr:         ":8888",
        WriteTimeout: 5 * time.Second,
        Handler:      http.TimeoutHandler(http.HandlerFunc(slowHandler), 1*time.Second, "Timeout!\n"),
    }

    if err := srv.ListenAndServe(); err != nil {
        fmt.Printf("Server failed: %s\n", err)
    }
}

In the doc, it is mentioned that

After a second, our TimeoutHandler will kick in, stop processing the slowHandler, and return a plain “Timeout!” message

curl request output:

# time curl localhost:8888
*   Trying 127.0.0.1:8888...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8888 (#0)
> GET / HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 503 Service Unavailable
< Date: Wed, 14 Dec 2022 10:19:15 GMT
< Content-Length: 9
< Content-Type: text/plain; charset=utf-8
<
Timeout!
* Connection #0 to host localhost left intact
curl localhost:8888 -v  0.01s user 0.01s system 1% cpu 1.018 total

Indeed, the response is sent back in 1 sec.

But I also noticed that I got this message in server logs after approx 10 seconds.

2022/12/14 15:49:24 Slow API call done after 10 seconds

15:49:24 in GMT would be 10:19:24

So, I guess the slowHandler was still processing the request in the background and wasn't canceled by TimeoutHandler. It was still running in the background.

Am I understanding this correctly? And if so, then what would happen if slowHandler has an infinite loop - something like this?

func slowHandler(w http.ResponseWriter, req *http.Request) {
    for {} //infinite loop
    log.Print("infinite loop")
    io.WriteString(w, "I am slow!\n")
}

Will it keep running forever in the background?


问:
ZipArchive PHP show Pop Up Execute

I used ZipArchive to create file ZIP and when i click it show Pop Up like that

I don't know why file show like that, but content file still working

i have code like

```<code>$zip = new ZipArchive;

$zip->open($zip_path . $zipname, ZIPARCHIVE::CREATE);

$content = tar_write_contents_text()

$zip->addFromString($content)

    public function tar_write_contents_text($phisfn, $head = "")
{
    if (@is_dir($phisfn)) {
        return;
    }
    else {
        $r = null;
        if (!file_exists($phisfn)) {
            return;
        }
        $f2 = fopen($phisfn, "rb");
        if ($head) $r .= $head;
        while (!feof($f2)) {
            $r .= fgets($f2, 1024);
            ob_flush();
            flush();
        }
        fclose($f2);
        return $r;
    }
}
</code>```

Thanks for all your help

Title: ZipArchive PHP show Pop Up Execute

Body:
I used ZipArchive to create file ZIP and when i click it show Pop Up like that

I don't know why file show like that, but content file still working

i have code like

$zip = new ZipArchive;

$zip->open($zip_path . $zipname, ZIPARCHIVE::CREATE);

$content = tar_write_contents_text()

$zip->addFromString($content)

    public function tar_write_contents_text($phisfn, $head = "")
{
    if (@is_dir($phisfn)) {
        return;
    }
    else {
        $r = null;
        if (!file_exists($phisfn)) {
            return;
        }
        $f2 = fopen($phisfn, "rb");
        if ($head) $r .= $head;
        while (!feof($f2)) {
            $r .= fgets($f2, 1024);
            ob_flush();
            flush();
        }
        fclose($f2);
        return $r;
    }
}

Thanks for all your help


问:
flutter with facebook login
I am trying to implement facebook login in flutter app (having issue in android).
Here is my code.

```<code>Future facebookLogin() async {
print('*');
try {
  final LoginResult result = await FacebookAuth.instance
      .login(); // by default we request the email and the public profile

  if (result.status == LoginStatus.success) {
    // you are logged

    final AccessToken accessToken = result.accessToken!;

    final userData = await FacebookAuth.i.getUserData();
    print(userData['name']);
  }
} catch (e) {
  print(e);
}
}
</code>```

I run the app and then I click facebook login button, it asks to continue with my profile then some permission page appears, that is where I am stuck. Screen shots are attached too.

Little guidance will be appreciated.
Thanks.

Title: flutter with facebook login

Body:
I am trying to implement facebook login in flutter app (having issue in android).
Here is my code.

Future facebookLogin() async {
print('*');
try {
  final LoginResult result = await FacebookAuth.instance
      .login(); // by default we request the email and the public profile

  if (result.status == LoginStatus.success) {
    // you are logged

    final AccessToken accessToken = result.accessToken!;

    final userData = await FacebookAuth.i.getUserData();
    print(userData['name']);
  }
} catch (e) {
  print(e);
}
}

I run the app and then I click facebook login button, it asks to continue with my profile then some permission page appears, that is where I am stuck. Screen shots are attached too.

Little guidance will be appreciated.
Thanks.


问:
Navigating back to flutter app from external app doesent work on iOS
I have a flutter app which launches an url that opens an external application which automatically starts a task. I want the app to return to the flutter app after it has completed its task. This seems to work automatically on android, but on iOS it stays on the external app and i have to manually switch.

Is there a way for this to work on iOS aswell?

Here is my code for launching the external app:

 launchUrl(Uri.parse(uri), webOnlyWindowName: "_blank", mode: LaunchMode.externalApplication);


问:
How to handle onChange and onClick event used in each row of Mui Table
How can I populate same type of dropdown and button in each row of table? I am using reusable table component to populate table data but how to manage handleChange and handleClick for each row separately.

CodeSandBox link: https://codesandbox.io/s/stupefied-feynman-6mdj77?file=/demo.js:0-390

Reusable table
tableComponent.jsx :

```<code>import * as React from "react";
import { Table, TableBody, TableHead, Paper, Box } from "@mui/material";
import { StyledTableCell, StyledTableRow, StyledContainer } from "./tableStyle";
export default function CustomTable({ cols, data }) {
  console.log("CustomTable", cols, data);
  return (
    <Paper>
      <StyledContainer>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <StyledTableRow>
              {cols.map((headerItem, index) => (
                <StyledTableCell key={index}>
                  <Box sx={{ textAlign: "center", fontSize: "14px" }}>
                    {headerItem.title}
                  </Box>
                </StyledTableCell>
              ))}
            </StyledTableRow>
          </TableHead>
          <TableBody>
            {data.map((item, index) => (
              <StyledTableRow key={index}>
                {cols.map((col, key) => (
                  <StyledTableCell key={key}>
                    {col.render(item)}
                  </StyledTableCell>
                ))}
              </StyledTableRow>
            ))}
          </TableBody>
        </Table>
      </StyledContainer>
    </Paper>
  );
}
</code>```

tableConstant.js :

```<code>import React from "react";
import { Box, MenuItem, Select, Button } from "@mui/material";

export const TableConstants = (handleChange, handleClick) => {
  const [name, setName] = React.useState("");
  return [
    {
      title: "No.",
      render: (rowData) => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            {rowData.id}
          </Box>
        );
      }
    },
    {
      title: "Manage",

      render: () => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            {" "}
            <Select
              // onChange={}
              fullWidth
              size="small"
              MenuProps={{ MenuListProps: { disablePadding: true } }}
              sx={{
                fontSize: "14px",
                width: "100px",

                height: "28px"
              }}
            >
              <MenuItem
                sx={{
                  height: "25px",
                  width: "100%"
                }}
                value="Allow"
              >
                Allow
              </MenuItem>
              <MenuItem
                sx={{
                  height: "30px",
                  width: "100%"
                }}
                value="Decline"
              >
                Decline
              </MenuItem>
            </Select>
          </Box>
        );
      }
    },
    {
      title: "Name",
      render: (rowData) => {
        return <Box>{rowData.name}</Box>;
      }
    },
    {
      title: "Designation",
      render: (rowData) => {
        return <Box>{rowData.designation}</Box>;
      }
    },
    {
      title: "Email",
      render: (rowData) => {
        return <Box>{rowData.email}</Box>;
      }
    },
    {
      title: "Mobile",

      render: (rowData) => {
        return <Box>{rowData.mobile}</Box>;
      }
    },

    {
      title: "Access",
      render: () => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            <Button
            // onClick={}
            >
              {" "}
              view
            </Button>
          </Box>
        );
      }
    }
  ];
};

</code>```

data.js:

```<code>export const data = [
  {
    id: 1,
    name: "Leanne Graham",
    designation: "Tester",
    email: "Sincere@april.biz",
    mobile: "1-770-736-8031 x56442"
  },
  {
    id: 2,
    name: "Ervin Howell",
    designation: "Developer",
    email: "Shanna@melissa.tv",
    mobile: "010-692-6593 x09125"
  },
  {
    id: 3,
    name: "Clementine Bauch",
    designation: "Designer",
    email: "Nathan@yesenia.net",
    mobile: "1-463-123-4447"
  },
  {
    id: 4,
    name: "Patricia Lebsack",
    designation: "Analyst",
    email: "Julianne.OConner@kory.org",
    mobile: "493-170-9623 x156"
  },
  {
    id: 5,
    name: "Chelsey Dietrich",
    designation: "Deta Engineer",
    email: "Lucio_Hettinger@annie.ca",
    mobile: "(254)954-1289"
  }
];

</code>```

Final Table :

```<code>import React from "react";
import Table from "./table";
import { data } from "./data";
import { TableConstants } from "./tableConstant";
const handleChange = (item) => {
  alert(JSON.stringify(item));
};

const ManageAccess = () => {
  return (
    <React.Fragment>
      <Table cols={TableConstants(handleChange)} data={data} />
    </React.Fragment>
  );
};

export default ManageAccess;

</code>```

Body:
How can I populate same type of dropdown and button in each row of table? I am using reusable table component to populate table data but how to manage handleChange and handleClick for each row separately.

CodeSandBox link: https://codesandbox.io/s/stupefied-feynman-6mdj77?file=/demo.js:0-390

Reusable table
tableComponent.jsx :

import * as React from "react";
import { Table, TableBody, TableHead, Paper, Box } from "@mui/material";
import { StyledTableCell, StyledTableRow, StyledContainer } from "./tableStyle";
export default function CustomTable({ cols, data }) {
  console.log("CustomTable", cols, data);
  return (
    <Paper>

              ))}
            </StyledTableRow>
          </TableHead>
          <TableBody>
            {data.map((item, index) => (

                ))}
              </StyledTableRow>
            ))}
          </TableBody>

      </StyledContainer>
    </Paper>
  );
}

tableConstant.js :

import React from "react";
import { Box, MenuItem, Select, Button } from "@mui/material";

export const TableConstants = (handleChange, handleClick) => {
  const [name, setName] = React.useState("");
  return [
    {
      title: "No.",
      render: (rowData) => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            {rowData.id}
          </Box>
        );
      }
    },
    {
      title: "Manage",

      render: () => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            {" "}
            <Select
              // onChange={}
              fullWidth
              size="small"
              MenuProps={{ MenuListProps: { disablePadding: true } }}
              sx={{
                fontSize: "14px",
                width: "100px",

                height: "28px"
              }}
            >
              <MenuItem
                sx={{
                  height: "25px",
                  width: "100%"
                }}
                value="Allow"
              >
                Allow
              </MenuItem>
              <MenuItem
                sx={{
                  height: "30px",
                  width: "100%"
                }}
                value="Decline"
              >
                Decline
              </MenuItem>
            </Select>
          </Box>
        );
      }
    },
    {
      title: "Name",
      render: (rowData) => {
        return <Box>{rowData.name}</Box>;
      }
    },
    {
      title: "Designation",
      render: (rowData) => {
        return <Box>{rowData.designation}</Box>;
      }
    },
    {
      title: "Email",
      render: (rowData) => {
        return <Box>{rowData.email}</Box>;
      }
    },
    {
      title: "Mobile",

      render: (rowData) => {
        return <Box>{rowData.mobile}</Box>;
      }
    },

    {
      title: "Access",
      render: () => {
        return (
          <Box
            sx={{
              display: "flex",
              alignItem: "center",
              justifyContent: "center"
            }}
          >
            <Button
            // onClick={}
            >
              {" "}
              view
            </Button>
          </Box>
        );
      }
    }
  ];
};

data.js:

export const data = [
  {
    id: 1,
    name: "Leanne Graham",
    designation: "Tester",
    email: "Sincere@april.biz",
    mobile: "1-770-736-8031 x56442"
  },
  {
    id: 2,
    name: "Ervin Howell",
    designation: "Developer",
    email: "Shanna@melissa.tv",
    mobile: "010-692-6593 x09125"
  },
  {
    id: 3,
    name: "Clementine Bauch",
    designation: "Designer",
    email: "Nathan@yesenia.net",
    mobile: "1-463-123-4447"
  },
  {
    id: 4,
    name: "Patricia Lebsack",
    designation: "Analyst",
    email: "Julianne.OConner@kory.org",
    mobile: "493-170-9623 x156"
  },
  {
    id: 5,
    name: "Chelsey Dietrich",
    designation: "Deta Engineer",
    email: "Lucio_Hettinger@annie.ca",
    mobile: "(254)954-1289"
  }
];

Final Table :

import React from "react";
import Table from "./table";
import { data } from "./data";
import { TableConstants } from "./tableConstant";
const handleChange = (item) => {
  alert(JSON.stringify(item));
};

const ManageAccess = () => {
  return (
    <React.Fragment>

    </React.Fragment>
  );
};

export default ManageAccess;


问:
My custom 404 error view laravel does not display online but works on local server
I have an application that use laravel 8.75. I made custom views for 404 and 500 errors.
When I deployed my website, custom error view shows but seems that styles doesn't work on it.

So I realized that I made a mistake on the stylesheet call. I made correction and the css file is correctly call. But style still doesn't work on my error view.
So I clear the framework cache data and views and I clear the serviceworker cache.

Now my custom error does not appear at all, only standard navigator error (and not laravel standard error).

I want to precise that it works on local server.
I think it's due to cache but I don't understand the problem.

Has anyone had this problem before?
Do you have any idea of the cause of the problem?


问:
Better way to handle Future with ChangeNotifier in Flutter
I have an object model in my app which needs to be accessed on different pages. I get the object model via a REST interface and store it in a variable (here simplified SomeObjectModel). Since the object model can change through various events, I decided to use a ChangeNotifier to update the UI.

My problem: The return value from the REST call is an object of type Future<SomeObjectModel> which I assign to my private variable in the asynchronous method _getCurrentState. If I want to read a value from the object model (e.g. actualTemperature) I always have to check if the object model is not null. Is there a better way to implement this?

Here my simplified Code:

ChangeNotifier Class

```<code>class CarouselItemModel extends ChangeNotifier {
  SomeObjectModel? _someObjectModel;

  CarouselItemModel() {
    _getCurrentState();
  }

  _getCurrentState() async {
    _someObjectModel = await Rest().getCurrentState();
    notifyListeners();
  }

  double getActualTemperature() {
    if (_someObjectModel != null) {
      return _someObjectModel!.actualTemperature;
    } else {
      return 0.0;   // Default value if no connection to the server is possible.
    }
  }
}
</code>```

Consumer in Widget

```<code>Consumer<CarouselItemModel>(
  builder: (context, carouselItemModel, child) {
    return Text(
        "Temperature: ${carouselItemModel.getActualTemperature()} °C");
  },
),
</code>```

Body:
I have an object model in my app which needs to be accessed on different pages. I get the object model via a REST interface and store it in a variable (here simplified SomeObjectModel). Since the object model can change through various events, I decided to use a ChangeNotifier to update the UI.

My problem: The return value from the REST call is an object of type Future<SomeObjectModel> which I assign to my private variable in the asynchronous method _getCurrentState. If I want to read a value from the object model (e.g. actualTemperature) I always have to check if the object model is not null. Is there a better way to implement this?

Here my simplified Code:

ChangeNotifier Class

class CarouselItemModel extends ChangeNotifier {
  SomeObjectModel? _someObjectModel;

  CarouselItemModel() {
    _getCurrentState();
  }

  _getCurrentState() async {
    _someObjectModel = await Rest().getCurrentState();
    notifyListeners();
  }

  double getActualTemperature() {
    if (_someObjectModel != null) {
      return _someObjectModel!.actualTemperature;
    } else {
      return 0.0;   // Default value if no connection to the server is possible.
    }
  }
}

Consumer in Widget

Consumer<CarouselItemModel>(
  builder: (context, carouselItemModel, child) {
    return Text(
        "Temperature: ${carouselItemModel.getActualTemperature()} °C");
  },
),


问:
Check if timestamp is between limits
I m looking for a solution to  make inside a reading log file processus a compare to check the time range within of the current line

currently I have :

variables : datetime_ed & datetime_sd as enddate & startdate with each fd_fmt as '%Y-%m-%d-%H-%M'

the current existing code block looks like

```<code>with open(f, "r") as fi:#, open(output_file, "w") as fo:
     for line in fi:
     #for pattern in REGEXES:
          if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
               match = REGEXES[1].search(line)
               if match:
                    line_id = match.group(1)
                    # doing stuff here
</code>```

so I would do something like

```<code>with open(f, "r") as fi:#, open(output_file, "w") as fo:
     for line in fi:
     #for pattern in REGEXES:
          if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
               match = REGEXES[1].search(line)
               #ONLY IF LINE CONTAIN DATE BETWEEN datetime_ed & datetime_sd
                    if match:
                        line_id = match.group(1)
                        # doing stuff here
</code>```

how to do that ?
didn't found a function to do so in datetime documents

as temporary solution I made that :

```<code>                with open(f, "r") as fi:#, open(output_file, "w") as fo:
                        for line in fi:

                                try:
                                        ts = datetime.datetime.strptime(line[:16], fd_fmt) # try/except to avoid issues with non-dated lines
                                except ValueError:
                                        pass
                                #print("ts ",ts)
                                if datetime_sd < ts < datetime_ed :
                                        #for pattern in REGEXES:
                                        if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
                                                match = REGEXES[1].search(line)
                                                if match:
#etc...
</code>```

Is this good / correct ?

Title: Check if timestamp is between limits

Body:
I m looking for a solution to  make inside a reading log file processus a compare to check the time range within of the current line

currently I have :

variables : datetime_ed & datetime_sd as enddate & startdate with each fd_fmt as '%Y-%m-%d-%H-%M'

the current existing code block looks like

with open(f, "r") as fi:#, open(output_file, "w") as fo:
     for line in fi:
     #for pattern in REGEXES:
          if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
               match = REGEXES[1].search(line)
               if match:
                    line_id = match.group(1)
                    # doing stuff here

so I would do something like

with open(f, "r") as fi:#, open(output_file, "w") as fo:
     for line in fi:
     #for pattern in REGEXES:
          if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
               match = REGEXES[1].search(line)
               #ONLY IF LINE CONTAIN DATE BETWEEN datetime_ed & datetime_sd
                    if match:
                        line_id = match.group(1)
                        # doing stuff here

how to do that ?
didn't found a function to do so in datetime documents

as temporary solution I made that :

                with open(f, "r") as fi:#, open(output_file, "w") as fo:
                        for line in fi:

                                try:
                                        ts = datetime.datetime.strptime(line[:16], fd_fmt) # try/except to avoid issues with non-dated lines
                                except ValueError:
                                        pass
                                #print("ts ",ts)
                                if datetime_sd < ts < datetime_ed :
                                        #for pattern in REGEXES:
                                        if REGEXES[0].search(line):  # search by ID instead of the wordslist at first
                                                match = REGEXES[1].search(line)
                                                if match:
#etc...

Is this good / correct ?


问:
I am getting "AAR:002 No JWT found" error while doing GET request in PHP
I am trying to execute a PHP code base for GET API request, but I am getting

"AAR: 002" "No JWT Found"

error. below is the code

I am executing a GET request with cURL commands in PHP . The same code base and keys are working fine in Java and C# but when trying in PHP got this error.

When I try executing the below query

```<code>function getOpenSSLErrors()

{
    $messages = [];

    while ($msg = openssl_error_string()) {
    $messages[] = $msg;
    }
    return $messages;
}

//function to generate JW token

function
generateJWT($algo,$header,$payload) {

    $headerEncoded = str_replace(['+','/','='], ['-','_',''], base64_encode(json_encode($header)));
    $payloadEncoded =str_replace(['+','/','='], ['-','_',''], base64_encode(json_encode($payload)));

    // Delimit with period (.)

    $dataEncoded ="$headerEncoded.$payloadEncoded";

 $filename = "C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\scbapibankingprivatekey.pem";

 //$filename = "C:\\Ranjit\\xampp\\htdocs\\certs\\scb-api-banking-privatekey.pem";

 $file1 = fopen($filename,"r");
$privateKey = fread($file1,filesize($filename));
//This will be your private key.- scb-api-banking-privatekey.pem
 fclose($file1);
 //echo $privateKey;

  echo '************************************************************************************\n';

    $privateKeyResource = openssl_pkey_get_private($privateKey,'123456');//password to fetch private key
    $result = openssl_sign($dataEncoded,$signature,$privateKeyResource,$algo);
  if ($result ===false)
{
throw new RuntimeException("Failed to generate signature: ".implode("\n",getOpenSSLErrors()));

}
 $signatureEncoded =str_replace(['+','/','='], ['-','_',''],base64_encode($signature));
$jwt ="$dataEncoded.$signatureEncoded";
 return $jwt;
}
// JWT Header
$header = ["alg" => "RS256","typ" => "JWT" ];
$iat = time();

$exp=$iat+30;
// JWT Payload data

$payload =['jti'=>'CLIENT','exp'=>$exp, 'iss'=>"CLIENT",
                                'aud'=>"SCB-APIBanking",'iat'=>$iat
                                ];

// Create the JWT

$jwt = generateJWT('sha256',$header,$payload);
$sslCertPass = '123456';                                        //This will be the passphrase for p12 certificate

//$sslCert='client.cer';

$filenameCert = "C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\client.pem";

//$filenameCert = "C:\\Ranjit\\xampp\\htdocs\\certs\\client.pem";

    $sslCert = fread( fopen($filenameCert,"r"),filesize($filenameCert));

    //This will be your private key.- scb-api-banking-privatekey.pem

 //This will be the client.cer provided as part of activation - CURLOPT_SSLCERT

 //echo $sslCert;

//$sslKey = 'scb-apibanking-client-cert-private-key.pem';           //This will be your private key.pem

$privatekey_sslkey=realpath("C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\clientcertsslprivatekey.pem");

//$privatekey_sslkey=realpath("C:\\Ranjit\\xampp\\htdocs\\certs\\scb-apibanking-client-cert-key.pem");

if(!$privatekey_sslkey || !is_readable($privatekey_sslkey)){

    die("error: client.pem is not readable! realpath:\"{$privatekey_sslkey}\"- working dir: \"".getcwd()."\"effective user: ".print_r(posix_getpwuid(posix_geteuid()),true));

}

// $url = "https://apitest.standardchartered.com/activate";

//$url = "https://apitest.standardchartered.com/uat2/openapi/subscriptions/v2/credit-debit-advice";

$url = "https://apitest.standardchartered.com/uat2/openapi/subscriptions/v2";

//Post the activation token

$ch = curl_init($url );
$variable = "sample";

$pem=realpath("C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\client.pem");

if(!$pem || !is_readable($pem)){

    die("error: client.pem is not readable! realpath:\"{$pem}\" - working dir: \"".getcwd()."\"effective user: ".print_r(posix_getpwuid(posix_geteuid()),true));

}//echo $jwt ;

    $options = array(
        //CURLOPT_FAILONERROR => false,
        CURLOPT_RETURNTRANSFER => true,
        // CURLOPT_AUTOREFERER => true,
        //  CURLOPT_HEADER => true,
        //  CURLOPT_NOBODY =>true,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_SSLKEY =>$privatekey_sslkey,
        CURLOPT_SSLCERT => $pem,
        CURLOPT_KEYPASSWD => $sslCertPass,
        CURLOPT_SSLCERTPASSWD =>$sslCertPass,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_SSL_VERIFYPEER => true,
        // CURLOPT_POST => false,
        // CURLOPT_POSTFIELDS => $jwt,
        CURLOPT_HTTPHEADER => array(
            "Content-Type => application/json",
            "JWTToken => $jwt",
            "Pragma => akamai-x-get-extracted-values"
        ),
    );

    //print_r( $options);
    curl_setopt_array($ch,$options );
    $resp = curl_exec($ch);
    echo $resp;
    $ch_errno = curl_errno($ch);
    $ch_erro = curl_error($ch);
    curl_close($ch);

    if ($ch_errno)
    {
        echo "cURL Error #:". $ch_erro;
    }
    else
    {
        echo "Response:".$resp;
    }
    ?>
</code>```

Body:
I am trying to execute a PHP code base for GET API request, but I am getting

"AAR: 002" "No JWT Found"

error. below is the code

I am executing a GET request with cURL commands in PHP . The same code base and keys are working fine in Java and C# but when trying in PHP got this error.

When I try executing the below query

function getOpenSSLErrors()

{
    $messages = [];

    while ($msg = openssl_error_string()) {
    $messages[] = $msg;
    }
    return $messages;
}

//function to generate JW token

function
generateJWT($algo,$header,$payload) {

    $headerEncoded = str_replace(['+','/','='], ['-','_',''], base64_encode(json_encode($header)));
    $payloadEncoded =str_replace(['+','/','='], ['-','_',''], base64_encode(json_encode($payload)));

    // Delimit with period (.)

    $dataEncoded ="$headerEncoded.$payloadEncoded";

 $filename = "C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\scbapibankingprivatekey.pem";

 //$filename = "C:\\Ranjit\\xampp\\htdocs\\certs\\scb-api-banking-privatekey.pem";

 $file1 = fopen($filename,"r");
$privateKey = fread($file1,filesize($filename));
//This will be your private key.- scb-api-banking-privatekey.pem
 fclose($file1);
 //echo $privateKey;

  echo '************************************************************************************\n';

    $privateKeyResource = openssl_pkey_get_private($privateKey,'123456');//password to fetch private key
    $result = openssl_sign($dataEncoded,$signature,$privateKeyResource,$algo);
  if ($result ===false)
{
throw new RuntimeException("Failed to generate signature: ".implode("\n",getOpenSSLErrors()));

}
 $signatureEncoded =str_replace(['+','/','='], ['-','_',''],base64_encode($signature));
$jwt ="$dataEncoded.$signatureEncoded";
 return $jwt;
}
// JWT Header
$header = ["alg" => "RS256","typ" => "JWT" ];
$iat = time();

$exp=$iat+30;
// JWT Payload data

$payload =['jti'=>'CLIENT','exp'=>$exp, 'iss'=>"CLIENT",
                                'aud'=>"SCB-APIBanking",'iat'=>$iat
                                ];

// Create the JWT

$jwt = generateJWT('sha256',$header,$payload);
$sslCertPass = '123456';                                        //This will be the passphrase for p12 certificate

//$sslCert='client.cer';

$filenameCert = "C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\client.pem";

//$filenameCert = "C:\\Ranjit\\xampp\\htdocs\\certs\\client.pem";

    $sslCert = fread( fopen($filenameCert,"r"),filesize($filenameCert));

    //This will be your private key.- scb-api-banking-privatekey.pem

 //This will be the client.cer provided as part of activation - CURLOPT_SSLCERT

 //echo $sslCert;

//$sslKey = 'scb-apibanking-client-cert-private-key.pem';           //This will be your private key.pem

$privatekey_sslkey=realpath("C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\clientcertsslprivatekey.pem");

//$privatekey_sslkey=realpath("C:\\Ranjit\\xampp\\htdocs\\certs\\scb-apibanking-client-cert-key.pem");

if(!$privatekey_sslkey || !is_readable($privatekey_sslkey)){

    die("error: client.pem is not readable! realpath:\"{$privatekey_sslkey}\"- working dir: \"".getcwd()."\"effective user: ".print_r(posix_getpwuid(posix_geteuid()),true));

}

// $url = "https://apitest.standardchartered.com/activate";

//$url = "https://apitest.standardchartered.com/uat2/openapi/subscriptions/v2/credit-debit-advice";

$url = "https://apitest.standardchartered.com/uat2/openapi/subscriptions/v2";

//Post the activation token

$ch = curl_init($url );
$variable = "sample";

$pem=realpath("C:\\Jeyanthi\\xampp\\htdocs\\Jeyanthi_keys\\client.pem");

if(!$pem || !is_readable($pem)){

    die("error: client.pem is not readable! realpath:\"{$pem}\" - working dir: \"".getcwd()."\"effective user: ".print_r(posix_getpwuid(posix_geteuid()),true));

}//echo $jwt ;

    $options = array(
        //CURLOPT_FAILONERROR => false,
        CURLOPT_RETURNTRANSFER => true,
        // CURLOPT_AUTOREFERER => true,
        //  CURLOPT_HEADER => true,
        //  CURLOPT_NOBODY =>true,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_SSLKEY =>$privatekey_sslkey,
        CURLOPT_SSLCERT => $pem,
        CURLOPT_KEYPASSWD => $sslCertPass,
        CURLOPT_SSLCERTPASSWD =>$sslCertPass,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_SSL_VERIFYPEER => true,
        // CURLOPT_POST => false,
        // CURLOPT_POSTFIELDS => $jwt,
        CURLOPT_HTTPHEADER => array(
            "Content-Type => application/json",
            "JWTToken => $jwt",
            "Pragma => akamai-x-get-extracted-values"
        ),
    );

    //print_r( $options);
    curl_setopt_array($ch,$options );
    $resp = curl_exec($ch);
    echo $resp;
    $ch_errno = curl_errno($ch);
    $ch_erro = curl_error($ch);
    curl_close($ch);

    if ($ch_errno)
    {
        echo "cURL Error #:". $ch_erro;
    }
    else
    {
        echo "Response:".$resp;
    }
    ?>


问:
Firefox flickering when using CSS "filter: drop-shadow()"
Firefox flickering when using CSS "filter: drop-shadow()"

This is the CSS:

```<code>.glow {
  filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.25));
  -webkit-filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.25));
  transition: all 0.33s ease-in-out;
}

.glow:hover {
  filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.75));
  -webkit-filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.75));
}
</code>```

GIF on how it looks like on Firefox (unexpected behavior)
https://i.gyazo.com/4b74faab24bea75198a9c2323e2b0b2f.mp4

GIF on how it looks like on Chrome (expected behavior)
https://i.gyazo.com/c4fff9b1e954723aca3230aae2579f02.mp4

It seems to work fine whenever the video above is not interacted with, in other words paused. If I hover my mouse over the video and play the video, it constantly flickers like shown above.

How can I fix this?

I've tried adding -webkit-filter but it doesn't seem to help.

Body:
Firefox flickering when using CSS "filter: drop-shadow()"

This is the CSS:

.glow {
  filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.25));
  -webkit-filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.25));
  transition: all 0.33s ease-in-out;
}

.glow:hover {
  filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.75));
  -webkit-filter: drop-shadow(0px 0px 50px rgba(26, 100, 243, 0.75));
}

GIF on how it looks like on Firefox (unexpected behavior)
https://i.gyazo.com/4b74faab24bea75198a9c2323e2b0b2f.mp4

GIF on how it looks like on Chrome (expected behavior)
https://i.gyazo.com/c4fff9b1e954723aca3230aae2579f02.mp4

It seems to work fine whenever the video above is not interacted with, in other words paused. If I hover my mouse over the video and play the video, it constantly flickers like shown above.

How can I fix this?

I've tried adding -webkit-filter but it doesn't seem to help.


问:
How to add margin for the text of radio ant design

Want to apply margin-top on the text here so that it will be align. Using antd Radio group

```<code>  <Radio.Group
           key={data.id}>
            {data.choices.map(item => (
              <Radio
                disabled={surveyQuestion?.userAttempt?.status === 'COMPLETED'}
                value={item.id}
                >
                {item.title}
              </Radio>
            ))}
          </Radio.Group>
</code>```

Body:
Want to apply margin-top on the text here so that it will be align. Using antd Radio group

  <Radio.Group
           key={data.id}>
            {data.choices.map(item => (
              <Radio
                disabled={surveyQuestion?.userAttempt?.status === 'COMPLETED'}
                value={item.id}
                >
                {item.title}
              </Radio>
            ))}
          </Radio.Group>


问:
Django admin AttributeError: Unable to lookup `FIELD` on 'MODEL_1' on 'MODEL_2' on 'MODEL_3'
This answer didn't solve the issue for me, Generating django admin and foreignkey error.

I added a new field over a MODEL_1 everything works fine when I open the table in django dashboard but when I open an entry in MODEL_1 I get the error ```Unable to lookup 'model_1' on MODEL_1 or MODEL_1Admin or MODEL_1Form````

```<code>class Battery(TimeStampedModel):
    charging_counts = models.IntegerField(default=0)
    # tracking details
    status_updated_at = models.DateTimeField(null=True, blank=True)

</code>```

Admin:

```<code>class BatteryAdmin(RemoveAddOptionMixin, VogoAbstractBaseModelAdmin):
     list_disply = ['charging_counts', 'status_updated_at', ]
     search_fields = ()

</code>```

Body:
This answer didn't solve the issue for me, Generating django admin and foreignkey error.

I added a new field over a MODEL_1 everything works fine when I open the table in django dashboard but when I open an entry in MODEL_1 I get the error ```Unable to lookup 'model_1' on MODEL_1 or MODEL_1Admin or MODEL_1Form````

class Battery(TimeStampedModel):
    charging_counts = models.IntegerField(default=0)
    # tracking details
    status_updated_at = models.DateTimeField(null=True, blank=True)

Admin:

class BatteryAdmin(RemoveAddOptionMixin, VogoAbstractBaseModelAdmin):
     list_disply = ['charging_counts', 'status_updated_at', ]
     search_fields = ()


问:
Is there any algorithm to achieve some optimization for hanger placement?
I need to do a job where I need to place a particular object(Hanger) in a standard distance.

The rules are:

We should try to place each object in a given standard distance from each other.

There is a max distance from one object to adjacent object which in no way should be violated.

From the start and end also similar standard and maximum distance rule applies.

And there are some portions given where the objects placement needs to be avoided.

I'm not even able to start... which algorithm to use.
If anyone has any suggestion how I can achieve this or some related source please let me know.


问:
Cannot destructure property using useSelector in redux toolkit
I have tried to persist redux state with redux-persist, as I am new to redux I don't know which thing I am missing. I am trying to destruct state variable but it shows the error:

```<code>
Login.jsx:13 Uncaught TypeError: Cannot destructure property 'isSuccess' of '(0 , react_redux__WEBPACK_IMPORTED_MODULE_3__.useSelector)(...)' as it is undefined.
    at Login (Login.jsx:13:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25sjsj850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)
</code>```

Here is a userSlice.js file code,

```<code>
const userToken = localStorage.getItem("token")
  ? localStorage.getItem("token")
  : null;

export const userSlice = createSlice({
  name: "user",
  initialState: {
    userInfo: {},
    userToken,
    isFetching: false,
    isSuccess: false,
    isError: false,
    errorMessage: "",
  },
  extraReducers: {
    [otp_verify.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.userInfo = payload.phone;
      state.userToken = payload.token;
      return state;
    },
    [otp_verify.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [otp_verify.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
    [signupUser.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [signupUser.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [signupUser.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
    [loginUser.fulfilled]: (state, { payload }) => {
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [loginUser.rejected]: (state, { error }) => {
      console.log("payload", error);
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = error.message;
      return state;
    },
    [loginUser.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [fetchUserBytoken.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [fetchUserBytoken.fulfilled]: (state, { payload }) => {
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [fetchUserBytoken.rejected]: (state, { error }) => {
      console.log("fetchUserBytoken");
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = error.message;
      return state;
    },
    [logout.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.userToken = null;
      return state;
    },
    [logout.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [logout.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
  },
});

// export const { clearState } = userSlice.actions;
const { reducer } = userSlice;
export default reducer;

</code>```

And I have used redux-perist in this store.js file,

```<code>
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/user/userSlice";
import storage from "redux-persist/lib/storage";
import thunk from "redux-thunk";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, userReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

const persistor = persistStore(store);

export { store, persistor };

</code>```

I am trying to destruct variable in Login.js file as below,

```<code>
import { useSelector, useDispatch } from "react-redux";
import { loginUser } from "../../features/user/userSlice";

const Login = () => {
  const [phn, setPhn] = useState("");
  const navigate = useNavigate();
  const { isSuccess, isError, errorMessage } = useSelector(
    (state) => state.user
  );

</code>```

I have tried to figure out what the problem is, but couldn't find it. Can someone please help?

Body:
I have tried to persist redux state with redux-persist, as I am new to redux I don't know which thing I am missing. I am trying to destruct state variable but it shows the error:

Login.jsx:13 Uncaught TypeError: Cannot destructure property 'isSuccess' of '(0 , react_redux__WEBPACK_IMPORTED_MODULE_3__.useSelector)(...)' as it is undefined.
    at Login (Login.jsx:13:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25sjsj850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)

Here is a userSlice.js file code,

const userToken = localStorage.getItem("token")
  ? localStorage.getItem("token")
  : null;

export const userSlice = createSlice({
  name: "user",
  initialState: {
    userInfo: {},
    userToken,
    isFetching: false,
    isSuccess: false,
    isError: false,
    errorMessage: "",
  },
  extraReducers: {
    [otp_verify.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.userInfo = payload.phone;
      state.userToken = payload.token;
      return state;
    },
    [otp_verify.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [otp_verify.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
    [signupUser.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [signupUser.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [signupUser.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
    [loginUser.fulfilled]: (state, { payload }) => {
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [loginUser.rejected]: (state, { error }) => {
      console.log("payload", error);
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = error.message;
      return state;
    },
    [loginUser.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [fetchUserBytoken.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [fetchUserBytoken.fulfilled]: (state, { payload }) => {
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.phone = payload.phone;
      return state;
    },
    [fetchUserBytoken.rejected]: (state, { error }) => {
      console.log("fetchUserBytoken");
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = error.message;
      return state;
    },
    [logout.fulfilled]: (state, { payload }) => {
      console.log("payload", payload);
      state.isFetching = false;
      state.isSuccess = true;
      state.errorMessage = null;
      state.isError = false;
      state.userToken = null;
      return state;
    },
    [logout.pending]: (state) => {
      state.isFetching = true;
      state.isSuccess = null;
      state.errorMessage = null;
      state.isError = null;
    },
    [logout.rejected]: (state, { payload }) => {
      state.isFetching = false;
      state.isError = true;
      state.isSuccess = false;
      state.errorMessage = payload.message;
      return state;
    },
  },
});

// export const { clearState } = userSlice.actions;
const { reducer } = userSlice;
export default reducer;

And I have used redux-perist in this store.js file,

import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/user/userSlice";
import storage from "redux-persist/lib/storage";
import thunk from "redux-thunk";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, userReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

const persistor = persistStore(store);

export { store, persistor };

I am trying to destruct variable in Login.js file as below,

import { useSelector, useDispatch } from "react-redux";
import { loginUser } from "../../features/user/userSlice";

const Login = () => {
  const [phn, setPhn] = useState("");
  const navigate = useNavigate();
  const { isSuccess, isError, errorMessage } = useSelector(
    (state) => state.user
  );

I have tried to figure out what the problem is, but couldn't find it. Can someone please help?


问:
Power BI using image as map
In Power BI, I want to use an image to act as map. I do not need a map per se, I need to show an image of a mechanical assembly to highlight areas of it when some values are highlighted in a graph next to it and viceversa.

Like when one clicks on California and the map highlights California only, as an example, the same I would like to achieve by someone else clicking on, say, an engine from a car's image, so values from the engine only are highlighted in another graph into the dashboard.

Is this ever possible?

I tried to look for information by Google, but I cannot come up with the right wording for "custom image that has clickable parts that act like a map".

Title: Power BI using image as map


问:
Does ReactJS remove adjacent sibling element of root element in index.html?
I try to present landing element just before rendering React component at first mount when access my web service.

I refered to this stackoverflow issue

When I add adjacent sibling element of root element as landing element, the element just removed just after React Main component rendered.
So, I don't need to do add/remove className etc.

But, I want to give animation about "fade out" effect to landing page.
I can't. Because it was removed from DOM right after React component rendered.

So, I placed landing element to right before root div element in index.html and it was not removed after React component renderd.
Then, finally I can present fade out effect of landing element.

I'm wondering,
officialy ReactJS remove adjacent sibling element of root element And not remove forwared sibling element??

Is there any explanation page about it in official React web site?

Or

is it just accidental action I found?

// index.html
// this is couldn't give effect

// This is possible to make effect

```