问:
Elasticsearch batch not indexing all items using PHP client
I've been trying to build an index in ES and add the initial items to it (around 350k), using PHP.

I tried all kinds of batch sizes (from 10 items to 1k), check the count, check the threshold, but for some reason it doesn't index every item.

It just skips over some random items, without any errors in the batch result response. I feel like I tried everything and I have to idea what to do next

I'm using Amazon OpenSearch with the latest supported ES (7.10).

The index looks like this:

```<code>{
    "wonder-search": {
        "aliases": {},
        "mappings": {
            "properties": {
                "address": {
                    "type": "text"
                },
                "city": {
                    "type": "text"
                },
                "city_id": {
                    "type": "integer"
                },
                "duration": {
                    "type": "integer"
                },
                "filename": {
                    "type": "text"
                },
                "geo_point": {
                    "type": "geo_point"
                },
                "icon": {
                    "type": "keyword"
                },
                "is_sandbox": {
                    "type": "integer"
                },
                "item_id": {
                    "type": "integer"
                },
                "item_label": {
                    "type": "keyword"
                },
                "latitude": {
                    "type": "float"
                },
                "longitude": {
                    "type": "float"
                },
                "search_text_caption_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_city_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_completion": {
                    "type": "completion",
                    "analyzer": "simple",
                    "preserve_separators": true,
                    "preserve_position_increments": true,
                    "max_input_length": 50,
                    "contexts": [
                        {
                            "name": "type",
                            "type": "CATEGORY"
                        }
                    ]
                },
                "search_text_country_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_cuisine_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_location_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_state_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_tag_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_username_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "sort": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "sort_score": {
                    "type": "double"
                },
                "type": {
                    "type": "text"
                },
                "user_icon": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "user_id": {
                    "type": "integer"
                },
                "username": {
                    "type": "keyword"
                },
                "vanity_url": {
                    "type": "keyword"
                },
                "video_count": {
                    "type": "integer"
                }
            }
        },
        "settings": {
            "index": {
                "routing": {
                    "allocation": {
                        "include": {
                            "_tier_preference": "data_content"
                        }
                    }
                },
                "mapping": {
                    "ignore_malformed": "true"
                },
                "number_of_shards": "1",
                "provided_name": "wonder-search",
                "creation_date": "1671003076106",
                "number_of_replicas": "1",
                "uuid": "YQh1q40WTneLE4MWDWhArw",
                "version": {
                    "created": "7100199"
                }
            }
        }
    }
}
</code>```

and one item looks like this:

```<code>{
    "_index": "wonder-search",
    "_type": "_doc",
    "_id": "wq2LD4UBUAuy7FQPhtZh",
    "_version": 1,
    "_seq_no": 2003,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "sort": "4004",
        "item_id": "4934",
        "user_id": "434",
        "user_icon": "/site-content/avatars/Sp8AXjTJvMbRao2oZbuiUuSVH042-1597776099045.jpeg",
        "username": "chuurros",
        "item_label": "Kyoto Katsugyu【京都勝牛】",
        "search_text_username_json": [
            "chuurros"
        ],
        "search_text_caption_json": [
            "Absolutely love their gyukatsu (beef katsu) here! Delicious and will keep you wanting more! "
        ],
        "search_text_city_json": [
            "Toronto"
        ],
        "search_text_state_json": [
            "Ontario"
        ],
        "search_text_country_json": [
            "Canada"
        ],
        "search_text_location_name_json": [
            "Kyoto Katsugyu【京都勝牛】"
        ],
        "search_text_tag_name_json": [
            "japanese",
            "restaurant",
            "asian",
            "dining",
            "topcollection-4934"
        ],
        "search_text_cuisine_name_json": [],
        "type": "video",
        "vanity_url": "",
        "icon": "",
        "city": "Toronto",
        "city_id": "439",
        "latitude": "43.65682410",
        "longitude": "-79.37617410",
        "address": "134 Dundas St E",
        "duration": "9.57",
        "video_count": "0",
        "sort_score": "43",
        "filename": "373d75fd-4292-4e5b-a239-4b1c39ffc86c.MOV",
        "is_sandbox": "0",
        "geo_point": {
            "lat": "43.65682410",
            "lon": "-79.37617410"
        },
        "search_text_completion": {
            "input": [
                "Kyoto Katsugyu【京都勝牛】"
            ],
            "contexts": {
                "type": [
                    "video"
                ]
            }
        }
    }
}
</code>```

Any ideas why does it work like this?

Body:
I've been trying to build an index in ES and add the initial items to it (around 350k), using PHP.

I tried all kinds of batch sizes (from 10 items to 1k), check the count, check the threshold, but for some reason it doesn't index every item.

It just skips over some random items, without any errors in the batch result response. I feel like I tried everything and I have to idea what to do next

I'm using Amazon OpenSearch with the latest supported ES (7.10).

The index looks like this:

{
    "wonder-search": {
        "aliases": {},
        "mappings": {
            "properties": {
                "address": {
                    "type": "text"
                },
                "city": {
                    "type": "text"
                },
                "city_id": {
                    "type": "integer"
                },
                "duration": {
                    "type": "integer"
                },
                "filename": {
                    "type": "text"
                },
                "geo_point": {
                    "type": "geo_point"
                },
                "icon": {
                    "type": "keyword"
                },
                "is_sandbox": {
                    "type": "integer"
                },
                "item_id": {
                    "type": "integer"
                },
                "item_label": {
                    "type": "keyword"
                },
                "latitude": {
                    "type": "float"
                },
                "longitude": {
                    "type": "float"
                },
                "search_text_caption_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_city_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_completion": {
                    "type": "completion",
                    "analyzer": "simple",
                    "preserve_separators": true,
                    "preserve_position_increments": true,
                    "max_input_length": 50,
                    "contexts": [
                        {
                            "name": "type",
                            "type": "CATEGORY"
                        }
                    ]
                },
                "search_text_country_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_cuisine_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_location_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_state_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_tag_name_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "search_text_username_json": {
                    "type": "text",
                    "index_phrases": true
                },
                "sort": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "sort_score": {
                    "type": "double"
                },
                "type": {
                    "type": "text"
                },
                "user_icon": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "user_id": {
                    "type": "integer"
                },
                "username": {
                    "type": "keyword"
                },
                "vanity_url": {
                    "type": "keyword"
                },
                "video_count": {
                    "type": "integer"
                }
            }
        },
        "settings": {
            "index": {
                "routing": {
                    "allocation": {
                        "include": {
                            "_tier_preference": "data_content"
                        }
                    }
                },
                "mapping": {
                    "ignore_malformed": "true"
                },
                "number_of_shards": "1",
                "provided_name": "wonder-search",
                "creation_date": "1671003076106",
                "number_of_replicas": "1",
                "uuid": "YQh1q40WTneLE4MWDWhArw",
                "version": {
                    "created": "7100199"
                }
            }
        }
    }
}

and one item looks like this:

{
    "_index": "wonder-search",
    "_type": "_doc",
    "_id": "wq2LD4UBUAuy7FQPhtZh",
    "_version": 1,
    "_seq_no": 2003,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "sort": "4004",
        "item_id": "4934",
        "user_id": "434",
        "user_icon": "/site-content/avatars/Sp8AXjTJvMbRao2oZbuiUuSVH042-1597776099045.jpeg",
        "username": "chuurros",
        "item_label": "Kyoto Katsugyu【京都勝牛】",
        "search_text_username_json": [
            "chuurros"
        ],
        "search_text_caption_json": [
            "Absolutely love their gyukatsu (beef katsu) here! Delicious and will keep you wanting more! "
        ],
        "search_text_city_json": [
            "Toronto"
        ],
        "search_text_state_json": [
            "Ontario"
        ],
        "search_text_country_json": [
            "Canada"
        ],
        "search_text_location_name_json": [
            "Kyoto Katsugyu【京都勝牛】"
        ],
        "search_text_tag_name_json": [
            "japanese",
            "restaurant",
            "asian",
            "dining",
            "topcollection-4934"
        ],
        "search_text_cuisine_name_json": [],
        "type": "video",
        "vanity_url": "",
        "icon": "",
        "city": "Toronto",
        "city_id": "439",
        "latitude": "43.65682410",
        "longitude": "-79.37617410",
        "address": "134 Dundas St E",
        "duration": "9.57",
        "video_count": "0",
        "sort_score": "43",
        "filename": "373d75fd-4292-4e5b-a239-4b1c39ffc86c.MOV",
        "is_sandbox": "0",
        "geo_point": {
            "lat": "43.65682410",
            "lon": "-79.37617410"
        },
        "search_text_completion": {
            "input": [
                "Kyoto Katsugyu【京都勝牛】"
            ],
            "contexts": {
                "type": [
                    "video"
                ]
            }
        }
    }
}

Any ideas why does it work like this?


来源: stackexchange

问:
DataTable sort column with letters and numbers javascript
Iam using html and javascript to present the data on a datatable, and have a problem with title sorting.
How to sort title which contain letters and numbers. I want to show the title as it is and sorting by numbers in the title only.

The titles comes from the database like this:

```<code>ARA #23-1400
ARA #23-304
ARA #23-420
ARA #23-1002
ARA #23-900
ARA #23-457
</code>```

When I click on the up/down arrows on the table title column, it should be sorted like this:

```<code>ARA #23-304
ARA #23-420
ARA #23-457
ARA #23-900
ARA #23-1002
ARA #23-1400
</code>```

Or like this

```<code>ARA #23-1400
ARA #23-1002
ARA #23-900
ARA #23-457
ARA #23-420
ARA #23-304
</code>```

How to fix the sorting on DataTable column.push?

```<code><div id="new_tab" class="tab-pane p-20>">
    <h3 class="card-title"> Test</h3>
    <div class="table-responsive">
        <table class="table table-hover table-striped table-bordered test-table" cellspacing="0" width="100%">
            <thead>
            <tr>
                <th>Number</th>
                <th>Title</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function () {

      get_test_table();

        var columns = [];

        // Number
        columns.push({
            name: 'number',
            render: function (data, type, row, meta) {
                var number = '#' + row.number;
                return number;
            }
        });

        // Title
        columns.push({
            data: 'title',
        });

        function get_test_table(){
            $('.test-table').DataTable({
                order: [[0, "desc"]],
                pageLength: 25,
                lengthMenu: [[10, 25, 50], [10, 25, 50]],
                serverSide: true,
                processing: true,
                bDestroy: true,
                ajax: {
                    url: '/test/get_test_table/',
                    data: function (d) {

                    },
                },
                columns: columns,
                dom: 'frBtilp',

            });
        }
    });

</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Iam using html and javascript to present the data on a datatable, and have a problem with title sorting.
How to sort title which contain letters and numbers. I want to show the title as it is and sorting by numbers in the title only.

The titles comes from the database like this:

ARA #23-1400
ARA #23-304
ARA #23-420
ARA #23-1002
ARA #23-900
ARA #23-457

When I click on the up/down arrows on the table title column, it should be sorted like this:

ARA #23-304
ARA #23-420
ARA #23-457
ARA #23-900
ARA #23-1002
ARA #23-1400

Or like this

ARA #23-1400
ARA #23-1002
ARA #23-900
ARA #23-457
ARA #23-420
ARA #23-304

How to fix the sorting on DataTable column.push?

">

 Test

                Number
                Title


问:
New session is created every time a request is made through react app [ `withCredentials: true` option is set in axios ]
Every time a request is made, a new express session is created even when withCredentials is set to true in axios options.

Express Code

```<code>  const mongoUrl = (await mongoConfig()).mongoConfig.uri;
  app.use(
    session({
      secret: 'my-secret',
      resave: false,
      saveUninitialized: true,
      store: new MongoStore({ mongoUrl }),
      cookie: {
        maxAge: 60 * 60 * 1000 * 5,
        httpOnly: false, // not working for true as well
      },
    }),
  );
</code>```

React Axios Code:

```<code>let api = create({
    baseURL: BASE_URL,
    headers: {
        Accept: 'application/json',
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/json',
    },
    timeout: 45000,
    withCredentials: true,
});
</code>```

Body:
Every time a request is made, a new express session is created even when withCredentials is set to true in axios options.

Express Code

  const mongoUrl = (await mongoConfig()).mongoConfig.uri;
  app.use(
    session({
      secret: 'my-secret',
      resave: false,
      saveUninitialized: true,
      store: new MongoStore({ mongoUrl }),
      cookie: {
        maxAge: 60 * 60 * 1000 * 5,
        httpOnly: false, // not working for true as well
      },
    }),
  );

React Axios Code:

let api = create({
    baseURL: BASE_URL,
    headers: {
        Accept: 'application/json',
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/json',
    },
    timeout: 45000,
    withCredentials: true,
});


问:
Angular Material table sorting not working from 2nd page
I am using angular material table, and I am grabbing data individually for each page, so 50 rows for page 1 for example. The sorting works in the first page with no issues, however, from 2nd page onwards, if I click sort in any column, all the rows disappear, or more specifically, the matNoDataRow row is shown, which appears if there is no data.

Is the fact that I am grabbing data individually for each page a factor to why sorting is not working from 2nd page onwards?

below are the HTML code details:

```<code><div class="mat-elevation-z8">
    <mat-progress-bar mode="indeterminate" *ngIf="isLoading"></mat-progress-bar>
    <table mat-table [dataSource]="dataSource" matSort>

        <!-- Title Column -->
        <ng-container matColumnDef="title">
            <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by title">
                {{'createevent.clone.eventitle' | translate}}</th>
            <td mat-cell *matCellDef="let element" class="max-w-prose truncate pr-2" [matTooltip]="element.title"> <span
                    class="mobile-label mr-15">{{'createevent.clone.eventitle' | translate}}: </span>
                <span>{{element.title}}</span>
            </td>
        </ng-container>

        <!-- Location Column -->
        <ng-container matColumnDef="fullLocation">
            <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by location">
                {{'createevent.clone.location' | translate}} </th>
            <td mat-cell *matCellDef="let element" class="max-w-prose truncate pr-2"
                [matTooltip]="element.fullLocation">
                <span class="mobile-label mr-15">{{'createevent.clone.location' | translate}}: </span>
                <span>{{element.fullLocation}}</span>
            </td>
        </ng-container>

        <!-- Date Created Column -->
        <ng-container matColumnDef="createdDate">
            <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by Date Created">
                {{'createevent.clone.datecreated' | translate}} </th>
            <td mat-cell *matCellDef="let element"> <span class="mobile-label mr-15">{{'createevent.clone.datecreated' |
                    translate}}: </span> <span>{{element.createdDate | date: 'dd/MM/yyyy'}}</span> </td>
        </ng-container>

        <!-- Start Date Column -->
        <ng-container matColumnDef="startDate">
            <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by Start Date">
                {{'createevent.clone.startdate' | translate}} </th>
            <td mat-cell *matCellDef="let element"> <span class="mobile-label mr-15">{{'createevent.clone.startdate' |
                    translate}}: </span> <span>{{element.startDate | date: 'dd/MM/yyyy'}}</span> </td>
        </ng-container>

        <!-- Button Column -->
        <ng-container matColumnDef="action">
            <th mat-header-cell *matHeaderCellDef> Action </th>
            <td mat-cell *matCellDef="let row"> <button mat-button type="button" color="primary"
                    (click)="cloneEvent(row.id)">
                    <mat-icon>content_copy</mat-icon> <span
                        class="hidden tablet:inline-block">{{'createevent.clone.button' |
                        translate}}</span>
                </button> </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

        <!-- Row shown when there is no matching data. -->
        <tr class="mat-row" *matNoDataRow>
            <td class="mat-cell" *ngIf="!isLoading" colspan="4">No data matching the filter "{{searchInput.value}}"</td>
        </tr>
    </table>

    <mat-paginator #paginator [pageSize]="[query.pageSize]" [pageSizeOptions]="[5, 10, 25, 50]"
        [pageIndex]="query.pageNumber - 1" (page)="updateTable($event)" showFirstLastButtons aria-label="Event List">
    </mat-paginator>
</div>
</code>```

Values I initialized:

```<code>query: EventSearchQuery = {
  organizerId: 0,
  eventVersion: 2,
  searchText: '',
  pageSize: 5,
  pageNumber: 1
};

@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
displayedColumns: string[] = ['title', 'fullLocation', 'createdDate', 'startDate', 'action'];
dataSource = new MatTableDataSource();
</code>```

Below are the Typescript code details:

```<code>getEvents() {
  this.isLoading = true;

  // get all organizer events and initialize table
  this.newEventService.getOrganizerEvents(this.query).subscribe(res => {
    // map location name to fullLocation for easier data manipulation
    const events = res.map((event) => {
      const fullLocation = event.location.name;
      return { ...event, fullLocation };
    })

    //initialize table headers
    this.dataSource = new MatTableDataSource<any>(events);

    //initialize pagination
    setTimeout(() => {
      this.paginator.pageIndex = this.query.pageNumber - 1;
      this.paginator.pageSize = this.query.pageSize;
      this.paginator.length = this.filteredEventsCount;
    });
    this.dataSource.paginator = this.paginator;

    // initialize sorting
    this.dataSource.sort = this.sort;

    // filters title and location
    this.dataSource.filterPredicate = (data: OrganizersEvent, filter: string) => {

      return (data.title.trim().toLowerCase().indexOf(filter) !== -1 ||
        data.fullLocation.trim().toLowerCase().indexOf(filter) !== -1);
    };
    this.isLoading = false;
  }, error => {
    console.log(error);
    this.isLoading = false;
  })
}

updateTable(event ?: PageEvent) {
  this.query.pageNumber = event.pageIndex + 1;
  this.query.pageSize = event.pageSize;
  this.getEvents();
  return event;
}
</code>```

Body:
I am using angular material table, and I am grabbing data individually for each page, so 50 rows for page 1 for example. The sorting works in the first page with no issues, however, from 2nd page onwards, if I click sort in any column, all the rows disappear, or more specifically, the matNoDataRow row is shown, which appears if there is no data.

Is the fact that I am grabbing data individually for each page a factor to why sorting is not working from 2nd page onwards?

below are the HTML code details:

    <mat-progress-bar mode="indeterminate" *ngIf="isLoading"></mat-progress-bar>

        <ng-container matColumnDef="title">

                {{'createevent.clone.eventitle' | translate}}
             {{'createevent.clone.eventitle' | translate}}:
                {{element.title}}

        </ng-container>

        <ng-container matColumnDef="fullLocation">

                {{'createevent.clone.location' | translate}}

                {{'createevent.clone.location' | translate}}:
                {{element.fullLocation}}

        </ng-container>

        <ng-container matColumnDef="createdDate">

                {{'createevent.clone.datecreated' | translate}}
             {{'createevent.clone.datecreated' |
                    translate}}:  {{element.createdDate | date: 'dd/MM/yyyy'}}
        </ng-container>

        <ng-container matColumnDef="startDate">

                {{'createevent.clone.startdate' | translate}}
             {{'createevent.clone.startdate' |
                    translate}}:  {{element.startDate | date: 'dd/MM/yyyy'}}
        </ng-container>

        <ng-container matColumnDef="action">
             Action
             <button mat-button type="button" color="primary"
                    (click)="cloneEvent(row.id)">
                    <mat-icon>content_copy</mat-icon> {{'createevent.clone.button' |
                        translate}}
                </button>
        </ng-container>

            No data matching the filter "{{searchInput.value}}"

    <mat-paginator #paginator [pageSize]="[query.pageSize]" [pageSizeOptions]="[5, 10, 25, 50]"
        [pageIndex]="query.pageNumber - 1" (page)="updateTable($event)" showFirstLastButtons aria-label="Event List">
    </mat-paginator>

Values I initialized:

query: EventSearchQuery = {
  organizerId: 0,
  eventVersion: 2,
  searchText: '',
  pageSize: 5,
  pageNumber: 1
};

@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
displayedColumns: string[] = ['title', 'fullLocation', 'createdDate', 'startDate', 'action'];
dataSource = new MatTableDataSource();

Below are the Typescript code details:

getEvents() {
  this.isLoading = true;

  // get all organizer events and initialize table
  this.newEventService.getOrganizerEvents(this.query).subscribe(res => {
    // map location name to fullLocation for easier data manipulation
    const events = res.map((event) => {
      const fullLocation = event.location.name;
      return { ...event, fullLocation };
    })

    //initialize table headers
    this.dataSource = new MatTableDataSource<any>(events);

    //initialize pagination
    setTimeout(() => {
      this.paginator.pageIndex = this.query.pageNumber - 1;
      this.paginator.pageSize = this.query.pageSize;
      this.paginator.length = this.filteredEventsCount;
    });
    this.dataSource.paginator = this.paginator;

    // initialize sorting
    this.dataSource.sort = this.sort;

    // filters title and location
    this.dataSource.filterPredicate = (data: OrganizersEvent, filter: string) => {

      return (data.title.trim().toLowerCase().indexOf(filter) !== -1 ||
        data.fullLocation.trim().toLowerCase().indexOf(filter) !== -1);
    };
    this.isLoading = false;
  }, error => {
    console.log(error);
    this.isLoading = false;
  })
}

updateTable(event ?: PageEvent) {
  this.query.pageNumber = event.pageIndex + 1;
  this.query.pageSize = event.pageSize;
  this.getEvents();
  return event;
}


问:
How to launch Jupyter Notebooks with their own folder as the working directory in Visual Studio code
When I launch R-based Jupyter Notebooks in Visual Studio Code, I want each R notebook to have its working directory set to the directory the file sits in. However, this is not happening (details below).

Various iterations of this question have been asked, but the solutions seem to work only for Python-based Jupyter notebooks in Visual Studio code. For those, the solution is simply to update the VS Code settings to set Notebook File Root to ${fileDirname}:

That works perfectly fine for my Python code. However, it does not work for R-based Jupyter notebooks in Visual Studio Code on macOS. More specifically, I find that the first R notebook launches with its own folder set as the working directory, as expected. But subsequent R notebooks launch in the same folder as the first R notebook that I launch. (Unlike Python notebooks, which again open just as expected.)

Has anyone gotten R notebooks to open in their expected directory in VS Code (version 1.74.0)?


问:
Programmatically delete a row from a CSV file after 24 hours are elapsed
So, I am trying to add a user entry with a timestamp in a CSV in C++.

The CSV looks like this:

NAME
TIMESTAMP

DULQUERSALMAN
12:00:00

And I need to delete this DULQUERSALMAN entry after 24 hrs from the CSV. How can I do this?

This is the code I currently have, which adds the row above including the timestamp:

#include <iostream>
#include <fstream>
#include <sstream>
#include <chrono>
using namespace std;

int main() {
    string name;
    fstream myfile;
    myfile.open ("Data.csv", ios::out | ios::app);
    cout << "Enter the name:";
    cin >> name;

    auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());

    myfile <<  name << ";" << ctime(&givemetime);
}
```

Now I need to delete the entry when it gets older than 24 hours. How can I do this?

Body:
So, I am trying to add a user entry with a timestamp in a CSV in C++.

The CSV looks like this:

NAME
TIMESTAMP

DULQUERSALMAN
12:00:00

And I need to delete this DULQUERSALMAN entry after 24 hrs from the CSV. How can I do this?

This is the code I currently have, which adds the row above including the timestamp:

#include <iostream>
#include <fstream>
#include <sstream>
#include <chrono>
using namespace std;

int main() {
    string name;
    fstream myfile;
    myfile.open ("Data.csv", ios::out | ios::app);
    cout << "Enter the name:";
    cin >> name;

    auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());

    myfile <<  name << ";" << ctime(&givemetime);
}

Now I need to delete the entry when it gets older than 24 hours. How can I do this?


问:
Is it possible to sync on-demand table on two mysql servers at different location?
Looking for suggestions on how can I sync a mysql table over two different server at different location.
We do not want to sync complete database, only want to sync 1 or may be somemore on demand tables.</p>


问:
Python Pandas dataframe does contain all values
I've been trying to read data from a dynamodb database using Boto3 in python. After collecting all the data i write everything to a csv file on our local server. After writing the "raw" data of database i use again the data frame but it looks like its missing some Columns Looking at the first exported csv it contains 85 columns which is correct.But the second file only has 66? Have no clue why 19 columns dissapeard somehow.Here is the code:</p>
```<code>import boto3
import pandas as pd

#Export Raw data
#Dynamodb client connection instance
dynamo_client = boto3.resource(...)

#List services by resource
dynamo_client.get_available_subresources()

#Testing connection with table
vopak_table = dynamo_client.Table('vopakdata2')
print(vopak_table.table_status)

#Get all items from Dynamodb
response = vopak_table.scan()
data = response['Items']

while 'LastEvaluatedKey' in response:
    response = vopak_table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
    data.extend(response['Items'])

#Write data to CSV

df = pd.DataFrame(data)

#Time column first in sheet
first_column = df.pop('time')
df.insert(0,'time',first_column)
#Save as CSV
df.to_csv(r'C:\export.csv',index=False, header=True)

#MMA Calculation
#Remove hours from timestamp
df['time'] = df['time'].astype("datetime64").dt.date
#Use time as index
df = df.set_index("time")
#Add the MMA columns
df = df.groupby(df.index).agg(['min', 'max', 'mean'])

#Save as CSV
df = df.reset_index()
print(df)
df = df.to_csv(r'C:\exportMMA.csv', index=False,header=True)
</code>```

Body:
I've been trying to read data from a dynamodb database using Boto3 in python. After collecting all the data i write everything to a csv file on our local server. After writing the "raw" data of database i use again the data frame but it looks like its missing some Columns Looking at the first exported csv it contains 85 columns which is correct.But the second file only has 66? Have no clue why 19 columns dissapeard somehow.Here is the code:

import boto3
import pandas as pd

#Export Raw data
#Dynamodb client connection instance
dynamo_client = boto3.resource(...)

#List services by resource
dynamo_client.get_available_subresources()

#Testing connection with table
vopak_table = dynamo_client.Table('vopakdata2')
print(vopak_table.table_status)

#Get all items from Dynamodb
response = vopak_table.scan()
data = response['Items']

while 'LastEvaluatedKey' in response:
    response = vopak_table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
    data.extend(response['Items'])

#Write data to CSV

df = pd.DataFrame(data)

#Time column first in sheet
first_column = df.pop('time')
df.insert(0,'time',first_column)
#Save as CSV
df.to_csv(r'C:\export.csv',index=False, header=True)

#MMA Calculation
#Remove hours from timestamp
df['time'] = df['time'].astype("datetime64").dt.date
#Use time as index
df = df.set_index("time")
#Add the MMA columns
df = df.groupby(df.index).agg(['min', 'max', 'mean'])

#Save as CSV
df = df.reset_index()
print(df)
df = df.to_csv(r'C:\exportMMA.csv', index=False,header=True)


问:
Change JavaScript allow notification popup to custom
I am using firebase web push to send web push notifications to users on my web application , I want to know if I can customize the default JavaScript notification allowance popup to meet my web application's design.

I have tried to build my own popup and customize it but the default JavaScript notification popup keeps appearing .
If please anyone has done it before to help and guide me .


问:
Deserializer not unwrapping java objects
```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = A.class, name = "a"),
  @JsonSubTypes.Type(value = B.class, name = "b") )
public interface classX<T extends P, I extends Q> {

  /** @return */ String getProp();

  JavaObjectClass getJavaObjectClass();
}
</code>```
```<code>@Getter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
public abstract class classY<T extends P, I extends Q> implements class<Event, Identifier> {

private T obj1;

private String obj2;

private I obj3;

private JavaObjectClass obj4;

protected classY( T obj1, String obj2, I obj3, JavaObjectClass obj4)
{
  this.obj1 = obj1;
  this.obj2 = obj2;
  this.obj3 = obj3;
  this.obj4 = obj4;
}

@Override
public final String getProp()
    { return obj1.getSubProp(); }

@Override
public JavaObjectClass getJavaObjectClass()
    { return obj4; }

}
</code>```
```<code>@ToString
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class JavaObjectClass {

private String L;
private String M;
public Instant N;
public Date O;

public JavaObjectClass(AnotherClass input) {
this.N= input.getN();
this.M = input.getM();
this.L = input.getL();
this.O = Date.from(N);

 }
}
</code>```
```<code>@Getter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
public class A extends classZ<EnumClass> {

private K k;

@Builder //... }

</code>```

I have these following code. When deserializing using object mapper, I get the values of JavaObjectClass=null but for K I am able to get all the values. I can't figure out why this is happening. For string dataTypes i am able to get the value but when its a java object, then its coming as null.  Basically what i can understand is that it is not able to recognize the object itself.

Is there a way to unwrap the JavaObjectClass?

Body:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = A.class, name = "a"),
  @JsonSubTypes.Type(value = B.class, name = "b") )
public interface classX<T extends P, I extends Q> {

  /** @return */ String getProp();

  JavaObjectClass getJavaObjectClass();
}

@Getter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
public abstract class classY<T extends P, I extends Q> implements class<Event, Identifier> {

private T obj1;

private String obj2;

private I obj3;

private JavaObjectClass obj4;

protected classY( T obj1, String obj2, I obj3, JavaObjectClass obj4)
{
  this.obj1 = obj1;
  this.obj2 = obj2;
  this.obj3 = obj3;
  this.obj4 = obj4;
}

@Override
public final String getProp()
    { return obj1.getSubProp(); }

@Override
public JavaObjectClass getJavaObjectClass()
    { return obj4; }

}

@ToString
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class JavaObjectClass {

private String L;
private String M;
public Instant N;
public Date O;

public JavaObjectClass(AnotherClass input) {
this.N= input.getN();
this.M = input.getM();
this.L = input.getL();
this.O = Date.from(N);

 }
}

@Getter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
public class A extends classZ<EnumClass> {

private K k;

@Builder //... }

I have these following code. When deserializing using object mapper, I get the values of JavaObjectClass=null but for K I am able to get all the values. I can't figure out why this is happening. For string dataTypes i am able to get the value but when its a java object, then its coming as null.  Basically what i can understand is that it is not able to recognize the object itself.

Is there a way to unwrap the JavaObjectClass?


问:
ImageCapture doesn't work as I can't get into the error function nor the success function
everyone. I have an app in which I want to take a photo. I followed Google's guide (https://developer.android.com/codelabs/camerax-getting-started#1). However, I cannot take a photo. I can't get to the error function nor the success function within takePicture(). I use SDK 30.</p>
```<code>    private fun takePhoto() {
    // Get a stable reference of the modifiable image capture use case
    //Here the return is called
    val imageCapture = imageCapture ?: return

    // Create time stamped name and MediaStore entry.
    val name = SimpleDateFormat(FILENAME_FORMAT, Locale.GERMAN)
        .format(System.currentTimeMillis())
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
        }
    }

    // Create output options object which contains file + metadata
    val outputOptions = ImageCapture.OutputFileOptions
        .Builder(contentResolver,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues)
        .build()

    // Set up image capture listener, which is triggered after photo has
    // been taken

    imageCapture.takePicture(
        outputOptions,
        ContextCompat.getMainExecutor(this),
        object : ImageCapture.OnImageSavedCallback {
           //Will never be called
            override fun onError(exc: ImageCaptureException) {
                Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
            }
             //Will never be called
            override fun
                    onImageSaved(output: ImageCapture.OutputFileResults){
                val msg = "Photo capture succeeded: ${output.savedUri}"
                Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                Log.d(TAG, msg)
            }
        }
    )}
</code>```

Body:
everyone. I have an app in which I want to take a photo. I followed Google's guide (https://developer.android.com/codelabs/camerax-getting-started#1). However, I cannot take a photo. I can't get to the error function nor the success function within takePicture(). I use SDK 30.

    private fun takePhoto() {
    // Get a stable reference of the modifiable image capture use case
    //Here the return is called
    val imageCapture = imageCapture ?: return

    // Create time stamped name and MediaStore entry.
    val name = SimpleDateFormat(FILENAME_FORMAT, Locale.GERMAN)
        .format(System.currentTimeMillis())
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
        }
    }

    // Create output options object which contains file + metadata
    val outputOptions = ImageCapture.OutputFileOptions
        .Builder(contentResolver,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues)
        .build()

    // Set up image capture listener, which is triggered after photo has
    // been taken

    imageCapture.takePicture(
        outputOptions,
        ContextCompat.getMainExecutor(this),
        object : ImageCapture.OnImageSavedCallback {
           //Will never be called
            override fun onError(exc: ImageCaptureException) {
                Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
            }
             //Will never be called
            override fun
                    onImageSaved(output: ImageCapture.OutputFileResults){
                val msg = "Photo capture succeeded: ${output.savedUri}"
                Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                Log.d(TAG, msg)
            }
        }
    )}


问:
Glassfish 5.0 virtual server dns resolution problem in the running system
I have a problem about Glassfish Server 5.0 . I have a virtual server in Glassfish in Windows Server 2019. Although not often, sometimes dns resolution cannot be performed at uncertain times. However, the application can be accessed from the IP.

This problem goes away when I restart the operating system. Has anyone encountered this situation and know how to avoid it?


问:
Apple SSO Use multiple applications with different names
I have a use-case where I need to use apple login on two application (one has a iOS mobile app also) which belong to the same company but have different logos, is it possible to use the same apple login service in both. More specifically I had an issue with apple private relay with hide my email, as the accounts were duplicating on my iCloud profile. Is there way to link those two client_id so they don't create duplicates.

I've checked the apple documentation but it doesn't cover this topic.


问:
How to avoid reloading a fragment when switching to another fragment?
How to avoid reloading a fragment when switching to another fragment? Example: I go to the main page, the list is loaded on it, when you switch to another fragment, the list is also loaded in it, when you return to the main page, the list should appear without reloading it.</p>


问:
Why would some PRs won't show up in GitHub API
I want to list all the PRs that are merged, and have the label: codepeak 22.

Therefore, I am using this endpoint: https://api.github.com/search/issues?q=is%3Apr+is%3Amerged+label%3A%22codepeak+22%22

However, some PRs are not showing up, even after being merged and being labelled codepeak 22. I have noted that the label name is not case sensitive.

Example of PRs that are not being showed up -

https://github.com/infinity1729/EventListing/pull/11

https://github.com/mohit200008/FoodSaver20008/pull/55

What am I missing here?


问:
A large CSV/TXT file need to be split into multiple small files based on the number of lines given. using GO bufio.NewScanner
I'm new to GOLANG. I try to do one tiny task .
A large CSV/TXT file need to be split into multiple small files based on the number of lines given.
Input File  :  abc.csv  (assume 200 lines),   NoofLines required per file: 50
output File:  abc_1.csv,  abc_2.csv, abc_3.csv, abc_4.csv
Let me to paste the code into this thread.  Currently my script is creating 4 files.

Each file contain not expected data and format.
Is there an easy way to create?

```<code>package main

import (
    "bufio"
    "encoding/csv"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("abc.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    sc := bufio.NewScanner(file)
    lines := make([]string, 0)

    // Read through 'tokens' until an EOF is encountered.
    linecnt := 1
    filecnt := 1
    var fname string
    fname = fmt.Sprint("abc_", filecnt, ".csv")
    file, _ = os.Create(fname)
    fmt.Println("file :", fname)
    for sc.Scan() {
        lines = append(lines, sc.Text())
        if linecnt == 50 {
            linecnt = 0
            filecnt++
            //var fname string
            fname = fmt.Sprint("abc_", filecnt, ".csv")
            file, _ = os.Create(fname)
            writer := csv.NewWriter(file)
            defer writer.Flush()
            writer.Write(lines)
            defer file.Close()
            fmt.Println("file :", fname)
        } else {
            linecnt++
            writer := csv.NewWriter(file)
            defer writer.Flush()
            writer.Write(lines)
        }

    }

    if err := sc.Err(); err != nil {
        log.Fatal(err)
    }
}

</code>```

Body:
I'm new to GOLANG. I try to do one tiny task .
A large CSV/TXT file need to be split into multiple small files based on the number of lines given.
Input File  :  abc.csv  (assume 200 lines),   NoofLines required per file: 50
output File:  abc_1.csv,  abc_2.csv, abc_3.csv, abc_4.csv
Let me to paste the code into this thread.  Currently my script is creating 4 files.

Each file contain not expected data and format.
Is there an easy way to create?

package main

import (
    "bufio"
    "encoding/csv"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("abc.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    sc := bufio.NewScanner(file)
    lines := make([]string, 0)

    // Read through 'tokens' until an EOF is encountered.
    linecnt := 1
    filecnt := 1
    var fname string
    fname = fmt.Sprint("abc_", filecnt, ".csv")
    file, _ = os.Create(fname)
    fmt.Println("file :", fname)
    for sc.Scan() {
        lines = append(lines, sc.Text())
        if linecnt == 50 {
            linecnt = 0
            filecnt++
            //var fname string
            fname = fmt.Sprint("abc_", filecnt, ".csv")
            file, _ = os.Create(fname)
            writer := csv.NewWriter(file)
            defer writer.Flush()
            writer.Write(lines)
            defer file.Close()
            fmt.Println("file :", fname)
        } else {
            linecnt++
            writer := csv.NewWriter(file)
            defer writer.Flush()
            writer.Write(lines)
        }

    }

    if err := sc.Err(); err != nil {
        log.Fatal(err)
    }
}


问:
WHY is there no change in the weights in my only numpy neural network
I was trying to build a three layer neural network with each having one neuron using numpy. One was the input layer, one was the hidden layer and one was the output layer. The hidden layer had relu activation and the output layer had sigmoid activation. I tried to make the gradient descent and mean squared error all in numpy, where the gradient descent had an array as input where all the data was. The data was actually random numbers where if the input is more than 18 then the ouput will be 1.But the problem is that the weights and biases are initialized to 1 and after any amount of epoch given, the weights and biases wont change but the loss will decrease. The structure if it helps: (x)---((y1 = w1 * x + b1)|(z1 = relu(y1)))----((y2 =  w2 * z1 + b2)|(z2 = sigmoid(y2))). The code:

```<code>import numpy as np
import math
import random as r

# dataset generation
x = []
y = []
for i in range (100):
    age = r.randint(0, 80)
    x.append(age)
    if age  > 18:
        y.append(1)
    else:
        y.append(0)
# forward pass functions
def sig(x):
    y = []
    for i in x:
        y.append(1/(1+math.exp(-i)))
    return y

def relu(x):
    y = []
    for i in x:
        if i > 0:
            y.append(i)
        else:
            y.append(0)
    return y

def mse(ytrue,ypred):
    total = 0
    for yt,yp in zip(ytrue,ypred):
        total += (yt - yp)**2
    return total/len(ytrue)
# backward pass functions
def dmse(ytrue,ypred):
    total = []
    for yt,yp in zip(ytrue,ypred):
        total.append((yt - yp)*2)
    return total

def d_of_relu(x):
    y = []
    for i in x:
        if i > 0:
            y.append(1)
        else:
            y.append(0)
    return y

def d_of_sig(x):
    y = []
    for i in y:
        y.append(y*(1-y))
    return y
# additional functions
def y_calculation(x,w,b):
    y = []
    for i in x:
        y.append(i*w+b)
    return y

def chain_addition_second_layer_with_weight(dcdz2,dz2dy2,dy2dw2):
    total = 0
    for a,b in zip(dcdz2,dz2dy2):
        total += a*b*dy2dw2
    return total/len(dcdz2)

def chain_addition_second_layer_with_bias(dcdz2,dz2dy2):
    total = 0
    for a,b in zip(dcdz2,dz2dy2):
        total += a*b*1
    return total/len(dcdz2)

def chain_addition_first_layer_with_bias(dcdz2,dz2dy2,dy2dz1,dz1dy1):
    total = 0
    for a,b,d in zip(dcdz2,dz2dy2,dz1dy1):
        total += a*b*dy2dz1*d*1
    return total/len(dcdz2)

def chain_addition_first_layer_with_weight(dcdz2,dz2dy2,dy2dz1,dz1dy1,dy1dw1):
    total = 0
    for a,b,d in zip(dcdz2,dz2dy2,dz1dy1):
        total += a*b*dy2dz1*d*dy1dw1
    return total/len(dcdz2)
# actual gradient descend
def gradient_descend(x,y,lr,epoch):
    w1 = w2 = b1 = b2 = 2
    for i in range(epoch):
        y1 = y_calculation(x,w1,b1)
        z1 = relu(y1)
        y2 = y_calculation(z1,w2,b2)
        z2 = sig(y2)
        cost = mse(y,z2)
        dcdz2 = dmse(y,z2)
        dz2dy2 = d_of_sig(z2)
        dy2dw2 = z1
        dy2db2 = 1
        dy2dz1 = w2
        dz1dy1 = d_of_relu(z1)
        dy1dw1 = x
        w2 = w2 - lr * chain_addition_second_layer_with_weight(dcdz2,dz2dy2,dy2dw2)
        b2 = b2 - lr * chain_addition_second_layer_with_bias(dcdz2,dz2dy2)
        w1 = w1 - lr * chain_addition_first_layer_with_weight(dcdz2,dz2dy2,dy2dz1,dz1dy1,dy1dw1)
        b1 = b1 - lr * chain_addition_first_layer_with_bias(dcdz2,dz2dy2,dy2dz1,dz1dy1)
    return w2,b2,w1,b1,cost
print(gradient_descend(x,y,0.1,300))
</code>```

If anyone replies the necessary changes, it wil be very helpful. Thanks in advance

Body:
I was trying to build a three layer neural network with each having one neuron using numpy. One was the input layer, one was the hidden layer and one was the output layer. The hidden layer had relu activation and the output layer had sigmoid activation. I tried to make the gradient descent and mean squared error all in numpy, where the gradient descent had an array as input where all the data was. The data was actually random numbers where if the input is more than 18 then the ouput will be 1.But the problem is that the weights and biases are initialized to 1 and after any amount of epoch given, the weights and biases wont change but the loss will decrease. The structure if it helps: (x)---((y1 = w1 * x + b1)|(z1 = relu(y1)))----((y2 =  w2 * z1 + b2)|(z2 = sigmoid(y2))). The code:

import numpy as np
import math
import random as r

# dataset generation
x = []
y = []
for i in range (100):
    age = r.randint(0, 80)
    x.append(age)
    if age  > 18:
        y.append(1)
    else:
        y.append(0)
# forward pass functions
def sig(x):
    y = []
    for i in x:
        y.append(1/(1+math.exp(-i)))
    return y

def relu(x):
    y = []
    for i in x:
        if i > 0:
            y.append(i)
        else:
            y.append(0)
    return y

def mse(ytrue,ypred):
    total = 0
    for yt,yp in zip(ytrue,ypred):
        total += (yt - yp)**2
    return total/len(ytrue)
# backward pass functions
def dmse(ytrue,ypred):
    total = []
    for yt,yp in zip(ytrue,ypred):
        total.append((yt - yp)*2)
    return total

def d_of_relu(x):
    y = []
    for i in x:
        if i > 0:
            y.append(1)
        else:
            y.append(0)
    return y

def d_of_sig(x):
    y = []
    for i in y:
        y.append(y*(1-y))
    return y
# additional functions
def y_calculation(x,w,b):
    y = []
    for i in x:
        y.append(i*w+b)
    return y

def chain_addition_second_layer_with_weight(dcdz2,dz2dy2,dy2dw2):
    total = 0
    for a,b in zip(dcdz2,dz2dy2):
        total += a*b*dy2dw2
    return total/len(dcdz2)

def chain_addition_second_layer_with_bias(dcdz2,dz2dy2):
    total = 0
    for a,b in zip(dcdz2,dz2dy2):
        total += a*b*1
    return total/len(dcdz2)

def chain_addition_first_layer_with_bias(dcdz2,dz2dy2,dy2dz1,dz1dy1):
    total = 0
    for a,b,d in zip(dcdz2,dz2dy2,dz1dy1):
        total += a*b*dy2dz1*d*1
    return total/len(dcdz2)

def chain_addition_first_layer_with_weight(dcdz2,dz2dy2,dy2dz1,dz1dy1,dy1dw1):
    total = 0
    for a,b,d in zip(dcdz2,dz2dy2,dz1dy1):
        total += a*b*dy2dz1*d*dy1dw1
    return total/len(dcdz2)
# actual gradient descend
def gradient_descend(x,y,lr,epoch):
    w1 = w2 = b1 = b2 = 2
    for i in range(epoch):
        y1 = y_calculation(x,w1,b1)
        z1 = relu(y1)
        y2 = y_calculation(z1,w2,b2)
        z2 = sig(y2)
        cost = mse(y,z2)
        dcdz2 = dmse(y,z2)
        dz2dy2 = d_of_sig(z2)
        dy2dw2 = z1
        dy2db2 = 1
        dy2dz1 = w2
        dz1dy1 = d_of_relu(z1)
        dy1dw1 = x
        w2 = w2 - lr * chain_addition_second_layer_with_weight(dcdz2,dz2dy2,dy2dw2)
        b2 = b2 - lr * chain_addition_second_layer_with_bias(dcdz2,dz2dy2)
        w1 = w1 - lr * chain_addition_first_layer_with_weight(dcdz2,dz2dy2,dy2dz1,dz1dy1,dy1dw1)
        b1 = b1 - lr * chain_addition_first_layer_with_bias(dcdz2,dz2dy2,dy2dz1,dz1dy1)
    return w2,b2,w1,b1,cost
print(gradient_descend(x,y,0.1,300))

If anyone replies the necessary changes, it wil be very helpful. Thanks in advance


问:
Net::Amazon::S3::Client Produces Error on initiate_multipart_upload
There seems to be some issue triggering initiate_multipart_upload in Net::Amazon::S3::Client. When I do so, I receive the error:

```<code>Can't call method "findvalue" on an undefined value at /usr/local/share/perl5/Net/Amazon/S3/Operation/Object/Upload/Create/Response.pm line 17.
</code>```

I can do a normal put on the object without any error. All else seems to be functional, with lists of the bucket working, etc. Here is a code snippet of what I'm trying:

```<code>use Net::Amazon::S3;
our $s3 = Net::Amazon::S3->new({
    aws_access_key_id  => $config{'access_key_id'},
    aws_secret_access_key => $config{'access_key'},
    retry => 1
});

our $s3client = Net::Amazon::S3::Client->new( s3 => $s3 );

my $bucket = $s3client->bucket( name => $bucketName );

my $s3object = $bucket->object( key => 'test.txt' );
print 'Key: ' . $s3object->key;

my $uploadId = $s3object->initiate_multipart_upload;
</code>```

Net::Amazon::S3::Client doesn't object to creating the bucket or the object.

I've been able to initialize a multipart upload using the Paws::S3 library on this bucket just fine. I switched to Net::Amazon::S3::Client since Paws::S3 seems to get stuck at around the 21% mark of uploading my multipart file.

Body:
There seems to be some issue triggering initiate_multipart_upload in Net::Amazon::S3::Client. When I do so, I receive the error:

Can't call method "findvalue" on an undefined value at /usr/local/share/perl5/Net/Amazon/S3/Operation/Object/Upload/Create/Response.pm line 17.

I can do a normal put on the object without any error. All else seems to be functional, with lists of the bucket working, etc. Here is a code snippet of what I'm trying:

use Net::Amazon::S3;
our $s3 = Net::Amazon::S3->new({
    aws_access_key_id  => $config{'access_key_id'},
    aws_secret_access_key => $config{'access_key'},
    retry => 1
});

our $s3client = Net::Amazon::S3::Client->new( s3 => $s3 );

my $bucket = $s3client->bucket( name => $bucketName );

my $s3object = $bucket->object( key => 'test.txt' );
print 'Key: ' . $s3object->key;

my $uploadId = $s3object->initiate_multipart_upload;

Net::Amazon::S3::Client doesn't object to creating the bucket or the object.

I've been able to initialize a multipart upload using the Paws::S3 library on this bucket just fine. I switched to Net::Amazon::S3::Client since Paws::S3 seems to get stuck at around the 21% mark of uploading my multipart file.


问:
Can Excel 2016 pivot tables display "Count of Max" for a given column?
I have a large dataset that details treatments and how much patients have paid for those treatments. The payments are capped at a certain amount, and I want to know how many patients have paid the MAX amount (in this case 350,68).

As seen in the screenshot, which is an extract of my pivot table, the pivot has "Count of amount paid" and "Max of amount paid".

Is there a way to add a "count of max paid" to a pivot table? In this case I want it to show that there were 8 patients that paid the max of 350,68 for treatment 1 and so on and so forth for treatment 2, 3, X, Y, Z.

Picture with explanation

Preferably this should be a part of the pivot table, as the size of the dataset is already pushing the limits of what my PC seems to accept of processing in Excel.


问:
How to get confidence score in keras_ocr
I am using keras_ocr from here. How to get output confidence score in this. I go through the official documentation of keras_ocr from here and I found that for some popular datasets they set confidence score = 1. And also I searched internet and found that confidence score functionality will be implemented in future. Currently how to get confidence score.</p>


问:
Bootstrap 5 analogue of Flutter's FittedBox
Flutter has a FittedBox widget that automatically reduces the entire size inside itself depending on the size of the parent to fit inside the parent. Is there something similar in Bootstrap? Or how would it be more correct to do it? I have tried to reduce all size-related properties in a similar way, but it looks like a very crooked solution.

```<code>{
    ...
    font-size: calc(0.25rem + ((1vw - 2px) * 4.5455));
    ...
}
</code>```

I'm new to Bootstrap, so I don't understand how to solve this problem concisely yet

Body:
Flutter has a FittedBox widget that automatically reduces the entire size inside itself depending on the size of the parent to fit inside the parent. Is there something similar in Bootstrap? Or how would it be more correct to do it? I have tried to reduce all size-related properties in a similar way, but it looks like a very crooked solution.

{
    ...
    font-size: calc(0.25rem + ((1vw - 2px) * 4.5455));
    ...
}

I'm new to Bootstrap, so I don't understand how to solve this problem concisely yet


问:
How to format double to raw number, not format in number scientist
My problem is value of variable "interest" is showned in format number scientist have E. for example: i want value when return is 23874928374923749823749823749 but actually is 387492837492375E28

How do i resolve it?
Thanks so much!

Controller:

```<code>@Slf4j
@RestController
@RequestMapping("/api/i/v1/calculate")
public class CalculateController {
@RequestMapping(value = "/calculate", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON })
    public ResponseEntity<List<RespDto>> calculate() {
        return ResponseEntity.ok(service.calculate());
    }
}
</code>```

File response dto: RespDto

```<code>@NoArgsConstructor
@AllArgsConstructor
@Data
public class RespDto implements Serializable {
    private Double interest;
}
</code>```

Body:
My problem is value of variable "interest" is showned in format number scientist have E. for example: i want value when return is 23874928374923749823749823749 but actually is 387492837492375E28

How do i resolve it?
Thanks so much!

Controller:

@Slf4j
@RestController
@RequestMapping("/api/i/v1/calculate")
public class CalculateController {
@RequestMapping(value = "/calculate", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON })
    public ResponseEntity<List<RespDto>> calculate() {
        return ResponseEntity.ok(service.calculate());
    }
}

File response dto: RespDto

@NoArgsConstructor
@AllArgsConstructor
@Data
public class RespDto implements Serializable {
    private Double interest;
}


问:
Plotting variable number of columns in pandas
I have CSV file that has a date column and measurements column. Sometimes there are 4 or more measurement columns. Regardless of the number of columns, I would like to plot all columns on the same plot (same axis, not as subplots). Right now I have the following syntax for plotting all 4 data - how do I generalize plotting for any number of columns?

```<code>ax1 = df.plot(x="Date",y=["M1","M2","M3","M4"])
</code>```

Thanks.

Body:
I have CSV file that has a date column and measurements column. Sometimes there are 4 or more measurement columns. Regardless of the number of columns, I would like to plot all columns on the same plot (same axis, not as subplots). Right now I have the following syntax for plotting all 4 data - how do I generalize plotting for any number of columns?

ax1 = df.plot(x="Date",y=["M1","M2","M3","M4"])

Thanks.


问:
How to pass query to api server located in nginx proxy_pass?
Proxy_passed nginx through the trailing path to api-server.com using rewrite.

```<code>server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $host;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        rewrite ^/api(.*)$ $1?$args break;

        proxy_pass http://api-server.com;

    }

}
</code>```

localhost/api/ -> api-server.com/

This URL worked fine.

However, in the code above, the trailing path was not passed and only a not_found error occurred.

```<code>localhost/api/goods/info?code=1234 -> api-server.com/goods/info?code=1234

</code>```

I tried something like http://api-server.com/$args, but it only gave me a not_found error and couldn't pass it on.
(Find that trailing path localhost.)

I am very curious if there is a way to do it.

Body:
Proxy_passed nginx through the trailing path to api-server.com using rewrite.

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $host;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        rewrite ^/api(.*)$ $1?$args break;

        proxy_pass http://api-server.com;

    }

}

localhost/api/ -> api-server.com/

This URL worked fine.

However, in the code above, the trailing path was not passed and only a not_found error occurred.

localhost/api/goods/info?code=1234 -> api-server.com/goods/info?code=1234

I tried something like http://api-server.com/$args, but it only gave me a not_found error and couldn't pass it on.
(Find that trailing path localhost.)

I am very curious if there is a way to do it.


问:
Microsoft UI Automation - trigger click of Hyperlink in Grid WPF
I am working on UI automation of WPF application for which i am using Micrososft Automation UI tool for automation. I have one situation where i need to click on hyperlink which is inside first column of Data grid in WPF.

below is My Ui code:

```<code><DataGridTemplateColumn Header="Load Data" Width="85" Visibility="{Binding DataContext.IsLoaded, Source={StaticResource ProxyElement}}" >
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">

                                    <Image Width="15" Height="15" VerticalAlignment="Top" Cursor="Hand" Source="/Dummy.Dashboard;component/Images/Load.png" MouseDown="OnHyperlinkClick"/>
                                    <TextBlock>
                                        <Hyperlink Click="OnHyperlinkClick" x:Uid="TemplateLoadLink">
                                            Template
                                        </Hyperlink>
                                    </TextBlock>
                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
</code>```

And in UI test case i have used below code to access it:

```<code> AutomationElement mainGrid = null;
 mainGrid = aeCryptoCalc.FindFirst(TreeScope.Subtree,
    new PropertyCondition(AutomationElement.AutomationIdProperty,
          "CompanyGrid"));
 AutomationElement templateLink = null;
            templateLink = mainGrid.FindFirst(TreeScope.Descendants,
          new PropertyCondition(AutomationElement.AutomationIdProperty,
          "TemplateLoadLink"));

            InvokePattern itemPattern = (InvokePattern)templateLink.GetCurrentPattern(InvokePattern.Pattern) ;
            itemPattern.Invoke();
</code>```

but still Link is not getting clicked . Can someone suggest on this.

Body:
I am working on UI automation of WPF application for which i am using Micrososft Automation UI tool for automation. I have one situation where i need to click on hyperlink which is inside first column of Data grid in WPF.

below is My Ui code:

<DataGridTemplateColumn Header="Load Data" Width="85" Visibility="{Binding DataContext.IsLoaded, Source={StaticResource ProxyElement}}" >
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">

                                    <Image Width="15" Height="15" VerticalAlignment="Top" Cursor="Hand" Source="/Dummy.Dashboard;component/Images/Load.png" MouseDown="OnHyperlinkClick"/>
                                    <TextBlock>
                                        <Hyperlink Click="OnHyperlinkClick" x:Uid="TemplateLoadLink">
                                            Template
                                        </Hyperlink>
                                    </TextBlock>
                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

And in UI test case i have used below code to access it:

 AutomationElement mainGrid = null;
 mainGrid = aeCryptoCalc.FindFirst(TreeScope.Subtree,
    new PropertyCondition(AutomationElement.AutomationIdProperty,
          "CompanyGrid"));
 AutomationElement templateLink = null;
            templateLink = mainGrid.FindFirst(TreeScope.Descendants,
          new PropertyCondition(AutomationElement.AutomationIdProperty,
          "TemplateLoadLink"));

            InvokePattern itemPattern = (InvokePattern)templateLink.GetCurrentPattern(InvokePattern.Pattern) ;
            itemPattern.Invoke();

but still Link is not getting clicked . Can someone suggest on this.


问:
NestJS code first graphQL missing federation directives
I'am trying to use the graphQL federation v2 (supergraph) with NestJS in a code first approach. My problem is that I need to use some specific directives such as @inaccessible, @shareable or @provides, but those directives are not defined in the @nestjs/graphql module.

How can use these specific directives in a code first approach with NestJS ?

Taking a quick look in the source code of @nestjs/graphql there's however some reference to those directives here :
https://github.com/nestjs/graphql/blob/6864eb257f949652f7b1a57067c0d9f0a695c03e/packages/graphql/lib/federation/type-defs-federation2.decorator.ts#L8-L17

But when I use the following code :

```<code>@Field(type => Profile)
@Directive('@inaccessible')
profile: Profile
</code>```

I have this error :

```<code>GraphQLError: The schema is not a valid GraphQL schema.. Caused by:
Unknown directive "@inaccessible". If you meant the "@inaccessible" federation directive, you should use fully-qualified name "@federation__inaccessible" or add "@inaccessible" to the `import` argument of the @link to the federation specification.
</code>```

Edit

Following what it is said in the error message, I succeeded in using the @inaccessible directive like this :

```<code>@Field(type => Profile)
@Directive('@federation__inaccessible')
profile: Profile
</code>```

By using the fully-qualified name it worked, but I find this rather inelegant ... So if you have a way to fix this.

Thank you for your help

Body:
I'am trying to use the graphQL federation v2 (supergraph) with NestJS in a code first approach. My problem is that I need to use some specific directives such as @inaccessible, @shareable or @provides, but those directives are not defined in the @nestjs/graphql module.

How can use these specific directives in a code first approach with NestJS ?

Taking a quick look in the source code of @nestjs/graphql there's however some reference to those directives here :
https://github.com/nestjs/graphql/blob/6864eb257f949652f7b1a57067c0d9f0a695c03e/packages/graphql/lib/federation/type-defs-federation2.decorator.ts#L8-L17

But when I use the following code :

@Field(type => Profile)
@Directive('@inaccessible')
profile: Profile

I have this error :

GraphQLError: The schema is not a valid GraphQL schema.. Caused by:
Unknown directive "@inaccessible". If you meant the "@inaccessible" federation directive, you should use fully-qualified name "@federation__inaccessible" or add "@inaccessible" to the `import` argument of the @link to the federation specification.

Edit

Following what it is said in the error message, I succeeded in using the @inaccessible directive like this :

@Field(type => Profile)
@Directive('@federation__inaccessible')
profile: Profile

By using the fully-qualified name it worked, but I find this rather inelegant ... So if you have a way to fix this.

Thank you for your help


问:
How can I resolve this nmcli issue?
I created a vpn profile using nm-connection-editor then i use nmcli conn up id PJATK PJATK(is the name of the VPN connection). In return, I get

```<code>Error: Connection activation failed: Unknown reason
Hint: use 'journalctl -xe NM_CONNECTION=d894277c-632a-42c8-844b-96ef586c58ab + NM_DEVICE=wlp0s20f3' to get more details.
</code>```

When I run journalctl -xe NM_CONNECTION=d894277c-632a-42c8-844b-96ef586c58ab + NM_DEVICE=wlp0s20f3 I get this:

```<code>Dec 14 09:38:17 archlinux NetworkManager[613]: <info>  [1671007097.8926] device (wlp0s20f3): state change: unmanaged -> unavailable (reason 'managed', sys-iface-state: 'external')
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.1032] device (wlp0s20f3): set-hw-addr: set MAC address to F6:E2:86:D4:0B:D7 (scanning)
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.3756] device (wlp0s20f3): supplicant interface state: internal-starting -> disconnected
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.3763] device (wlp0s20f3): state change: unavailable -> disconnected (reason 'supplicant-available', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4587] device (wlp0s20f3): Activation: starting connection 'UPC507959656' (b42ef2cb-61a6-4354-81cf-be67779b6d6c)
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4588] device (wlp0s20f3): state change: disconnected -> prepare (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4602] device (wlp0s20f3): set-hw-addr: reset MAC address to 38:FC:98:5B:F2:DE (preserve)
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4609] device (wlp0s20f3): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4612] device (wlp0s20f3): Activation: (wifi) access point 'UPC507959656' has security, but secrets are required.
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4612] device (wlp0s20f3): state change: config -> need-auth (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4614] sup-iface[d93b7494ebf16bd0,0,wlp0s20f3]: wps: type pbc start...
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4623] device (wlp0s20f3): state change: need-auth -> prepare (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4626] device (wlp0s20f3): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4629] device (wlp0s20f3): Activation: (wifi) connection 'UPC507959656' has security, and secrets exist.  No new secrets needed.
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5446] device (wlp0s20f3): supplicant interface state: disconnected -> authenticating
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5711] device (wlp0s20f3): supplicant interface state: authenticating -> associating
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5895] device (wlp0s20f3): supplicant interface state: associating -> associated
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.6022] device (wlp0s20f3): supplicant interface state: associated -> 4way_handshake
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9934] device (wlp0s20f3): supplicant interface state: 4way_handshake -> completed
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9935] device (wlp0s20f3): Activation: (wifi) Stage 2 of 5 (Device Configure) successful. Connected to wireless network "UPC50795965>
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9936] device (wlp0s20f3): state change: config -> ip-config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9939] dhcp4 (wlp0s20f3): activation: beginning transaction (timeout in 45 seconds)
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0374] dhcp4 (wlp0s20f3): state changed new lease, address=192.168.1.77
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0672] device (wlp0s20f3): state change: ip-config -> ip-check (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0712] device (wlp0s20f3): state change: ip-check -> secondaries (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0716] device (wlp0s20f3): state change: secondaries -> activated (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0736] device (wlp0s20f3): Activation: successful, device activated.
Dec 14 09:39:14 archlinux NetworkManager[613]: <info>  [1671007154.2239] vpn[0x556cbb96a160,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:39:14 archlinux NetworkManager[613]: <warn>  [1671007154.4751] vpn[0x556cbb96a160,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)
Dec 14 09:39:38 archlinux NetworkManager[613]: <info>  [1671007178.6187] vpn[0x556cbb96a3e0,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:39:38 archlinux NetworkManager[613]: <warn>  [1671007178.8895] vpn[0x556cbb96a3e0,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)
Dec 14 09:42:52 archlinux NetworkManager[613]: <info>  [1671007372.3769] vpn[0x556cbb96a660,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:42:52 archlinux NetworkManager[613]: <warn>  [1671007372.6223] vpn[0x556cbb96a660,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)
</code>```

How to resolve it?

Title: How can I resolve this nmcli issue?

Body:
I created a vpn profile using nm-connection-editor then i use nmcli conn up id PJATK PJATK(is the name of the VPN connection). In return, I get

Error: Connection activation failed: Unknown reason
Hint: use 'journalctl -xe NM_CONNECTION=d894277c-632a-42c8-844b-96ef586c58ab + NM_DEVICE=wlp0s20f3' to get more details.

When I run journalctl -xe NM_CONNECTION=d894277c-632a-42c8-844b-96ef586c58ab + NM_DEVICE=wlp0s20f3 I get this:

Dec 14 09:38:17 archlinux NetworkManager[613]: <info>  [1671007097.8926] device (wlp0s20f3): state change: unmanaged -> unavailable (reason 'managed', sys-iface-state: 'external')
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.1032] device (wlp0s20f3): set-hw-addr: set MAC address to F6:E2:86:D4:0B:D7 (scanning)
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.3756] device (wlp0s20f3): supplicant interface state: internal-starting -> disconnected
Dec 14 09:38:18 archlinux NetworkManager[613]: <info>  [1671007098.3763] device (wlp0s20f3): state change: unavailable -> disconnected (reason 'supplicant-available', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4587] device (wlp0s20f3): Activation: starting connection 'UPC507959656' (b42ef2cb-61a6-4354-81cf-be67779b6d6c)
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4588] device (wlp0s20f3): state change: disconnected -> prepare (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4602] device (wlp0s20f3): set-hw-addr: reset MAC address to 38:FC:98:5B:F2:DE (preserve)
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4609] device (wlp0s20f3): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4612] device (wlp0s20f3): Activation: (wifi) access point 'UPC507959656' has security, but secrets are required.
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4612] device (wlp0s20f3): state change: config -> need-auth (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4614] sup-iface[d93b7494ebf16bd0,0,wlp0s20f3]: wps: type pbc start...
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4623] device (wlp0s20f3): state change: need-auth -> prepare (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4626] device (wlp0s20f3): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.4629] device (wlp0s20f3): Activation: (wifi) connection 'UPC507959656' has security, and secrets exist.  No new secrets needed.
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5446] device (wlp0s20f3): supplicant interface state: disconnected -> authenticating
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5711] device (wlp0s20f3): supplicant interface state: authenticating -> associating
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.5895] device (wlp0s20f3): supplicant interface state: associating -> associated
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.6022] device (wlp0s20f3): supplicant interface state: associated -> 4way_handshake
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9934] device (wlp0s20f3): supplicant interface state: 4way_handshake -> completed
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9935] device (wlp0s20f3): Activation: (wifi) Stage 2 of 5 (Device Configure) successful. Connected to wireless network "UPC50795965>
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9936] device (wlp0s20f3): state change: config -> ip-config (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:21 archlinux NetworkManager[613]: <info>  [1671007101.9939] dhcp4 (wlp0s20f3): activation: beginning transaction (timeout in 45 seconds)
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0374] dhcp4 (wlp0s20f3): state changed new lease, address=192.168.1.77
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0672] device (wlp0s20f3): state change: ip-config -> ip-check (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0712] device (wlp0s20f3): state change: ip-check -> secondaries (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0716] device (wlp0s20f3): state change: secondaries -> activated (reason 'none', sys-iface-state: 'managed')
Dec 14 09:38:23 archlinux NetworkManager[613]: <info>  [1671007103.0736] device (wlp0s20f3): Activation: successful, device activated.
Dec 14 09:39:14 archlinux NetworkManager[613]: <info>  [1671007154.2239] vpn[0x556cbb96a160,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:39:14 archlinux NetworkManager[613]: <warn>  [1671007154.4751] vpn[0x556cbb96a160,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)
Dec 14 09:39:38 archlinux NetworkManager[613]: <info>  [1671007178.6187] vpn[0x556cbb96a3e0,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:39:38 archlinux NetworkManager[613]: <warn>  [1671007178.8895] vpn[0x556cbb96a3e0,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)
Dec 14 09:42:52 archlinux NetworkManager[613]: <info>  [1671007372.3769] vpn[0x556cbb96a660,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: starting sstp
Dec 14 09:42:52 archlinux NetworkManager[613]: <warn>  [1671007372.6223] vpn[0x556cbb96a660,d894277c-632a-42c8-844b-96ef586c58ab,"PJATK"]: dbus: failure: connect-failed (1)

How to resolve it?


问:
Can an apple Shortcut script prompt for an audio recording then continue with that as input?
I want to make a Shortcut for OSX/iOS/Apple-Watch that would prompt for an audio recording then, in my use case, send that recording on to an endpoint. Is part or all of this possible? I realize it may need to involve an app I create, but I would prefer not to have to do that. Since it would be a Siri command eventually, I am assuming that, if this is possible, a pause will stop the audio input section of the script. Thanks!</p>


问:
JSCPD code duplication linter giving a false positive in next.js project
I recently found out about GitHub actions superlinter which uses JSCPD to check for code duplication. It worked initially but I'm running into one specific false positive and I can't figure it out. JSCPD also has a package on npm and I tested it locally on that single file but it errored too. I have also tried adding new lines below but it didn't work too. The code and error are below.

Error:

2022-12-14 08:21:48 [INFO]   File:[/github/workspace/components/pages/editor/sidebar/index.tsx]
2022-12-14 08:21:49 [ERROR]   Found errors in [jscpd] linter!
2022-12-14 08:21:49 [ERROR]   Error code: 1. Command output:
------
Clone found (tsx):
 - /github/workspace/components/pages/editor/sidebar/index.tsx [40:7 - 58:3] (18 lines, 167 tokens)
   /github/workspace/components/pages/editor/sidebar/index.tsx [37:7 - 51:2]

Clone found (tsx):
 - /github/workspace/components/pages/editor/sidebar/index.tsx [40:7 - 58:3] (18 lines, 167 tokens)
   /github/workspace/components/pages/editor/sidebar/index.tsx [37:7 - 51:2]

 40 │ 37 │
 41 │ 38 │                  </GenButton>
 42 │ 39 │
 43 │ 40 │                  <GenButton props={{ label: "Sidebar: save" }}>
 44 │ 41 │
 45 │ 42 │                  </GenButton>
 46 │ 43 │
 47 │ 44 │                  <GenButton props={{ label: "Sidebar: language" }}>
 48 │ 45 │
 49 │ 46 │                  </GenButton>
 50 │ 47 │
 51 │ 48 │                  <GenButton props={{ label: "Sidebar: launch" }}>
 52 │ 49 │
 53 │ 50 │                  </GenButton>
 54 │ 51 │
 55 │ 52 │                  <GenButton props={{ label: "Sidebar: more info" }}>
 56 │ 53 │
 57 │ 54 │                  </GenButton>
 58 │ 55 │              </

Found 1 clones.
ERROR: jscpd found too many duplicates (11.18%) over threshold (0%)
Error: ERROR: jscpd found too many duplicates (11.18%) over threshold (0%)
    at ThresholdReporter.report (/node_modules/@jscpd/finder/dist/reporters/threshold.js:12:19)
    at /node_modules/@jscpd/finder/dist/in-files-detector.js:82:26
    at Array.forEach (<anonymous>)
    at /node_modules/@jscpd/finder/dist/in-files-detector.js:81:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
------```
</div>
</div>
</p>
<p>Code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { memo, useContext } from "react";
import ContextIndex from "../../../../utils/context/index";
import ContextGlobal from "../../../../utils/context/_global";
import GenButton from "../../../gen/button";
import GenImage from "../../../gen/image";
import EditorFileExplorer from "./fileExplorer";
import styles from "./index.module.css";
const EditorSidebar: React.FC = () => {
    const { isLightTheme, setIsLightTheme, session } = useContext(ContextGlobal);
    const {
        barState: { leftBarOpen, explorerOpen },
        updateBarState,
    } = useContext(ContextIndex);
    function handleAlert() {
        alert("Hello World");
    }

    return (
        <>
            <section
                className={
                    leftBarOpen ? styles.sidebarSectionOpen : styles.sidebarSection
                }
            >
                <div className={`${styles.flexButtons} hoverParent`}>
                    <GenButton
                        props={{
                            label: "Sidebar: toggle file explorer",
                            onClick:
                                session?.user !== undefined
                                    ? () => updateBarState({ type: "explorerOpen" })
                                    : handleAlert,
                        }}
                    >
                        <i className={"icon-docs"}></i>
                    </GenButton>

                    <GenButton props={{ label: "Sidebar: search" }}>
                        <i className={"icon-search"}></i>
                    </GenButton>

                    <GenButton props={{ label: "Sidebar: save" }}>
                        <i className={"icon-floppy"}></i>
                    </GenButton>

                    <GenButton props={{ label: "Sidebar: language" }}>
                        <i className={"icon-globe"}></i>
                    </GenButton>

                    <GenButton props={{ label: "Sidebar: launch" }}>
                        <i className={"icon-rocket"}></i>
                    </GenButton>

                    <GenButton props={{ label: "Sidebar: more info" }}>
                        <i className={"icon-info-circled"}></i>
                    </GenButton>
                </div>
                <div className={`${styles.flexButtons} hoverParent`}>
                    <GenButton props={{ label: "Sidebar: profile" }}>
                        {session?.user.image !== undefined ? (
                            <GenImage
                                props={{
                                    src: session.user.image,
                                    height: 40,
                                    width: 40,
                                    alt: session.user.name,
                                    className: styles.profileImage,
                                }}
                            />
                        ) : (
                            <i className={"icon-user-circle"}></i>
                        )}
                    </GenButton>
                    <GenButton
                        props={{
                            label: "Sidebar: toggle theme",
                            onClick: () => setIsLightTheme((prev) => !prev),
                        }}
                    >
                        {isLightTheme ? (
                            <i className={"icon-toggle-off"}></i>
                        ) : (
                            <i className={"icon-toggle-on"}></i>
                        )}
                    </GenButton>
                    <GenButton props={{ label: "Sidebar: settings" }}>
                        <i className={"icon-cog"}></i>
                    </GenButton>
                </div>
            </section>
            {explorerOpen && <EditorFileExplorer />}
        </>
    );
};

export default memo(EditorSidebar);</code>```

Body:
I recently found out about GitHub actions superlinter which uses JSCPD to check for code duplication. It worked initially but I'm running into one specific false positive and I can't figure it out. JSCPD also has a package on npm and I tested it locally on that single file but it errored too. I have also tried adding new lines below but it didn't work too. The code and error are below.

Error:

2022-12-14 08:21:48 [INFO]   File:[/github/workspace/components/pages/editor/sidebar/index.tsx]
2022-12-14 08:21:49 [ERROR]   Found errors in [jscpd] linter!
2022-12-14 08:21:49 [ERROR]   Error code: 1. Command output:
------
Clone found (tsx):
 - /github/workspace/components/pages/editor/sidebar/index.tsx [40:7 - 58:3] (18 lines, 167 tokens)
   /github/workspace/components/pages/editor/sidebar/index.tsx [37:7 - 51:2]

Clone found (tsx):
 - /github/workspace/components/pages/editor/sidebar/index.tsx [40:7 - 58:3] (18 lines, 167 tokens)
   /github/workspace/components/pages/editor/sidebar/index.tsx [37:7 - 51:2]

 40 │ 37 │
 41 │ 38 │                  </GenButton>
 42 │ 39 │
 43 │ 40 │                  <GenButton props={{ label: "Sidebar: save" }}>
 44 │ 41 │
 45 │ 42 │                  </GenButton>
 46 │ 43 │
 47 │ 44 │                  <GenButton props={{ label: "Sidebar: language" }}>
 48 │ 45 │
 49 │ 46 │                  </GenButton>
 50 │ 47 │
 51 │ 48 │                  <GenButton props={{ label: "Sidebar: launch" }}>
 52 │ 49 │
 53 │ 50 │                  </GenButton>
 54 │ 51 │
 55 │ 52 │                  <GenButton props={{ label: "Sidebar: more info" }}>
 56 │ 53 │
 57 │ 54 │                  </GenButton>
 58 │ 55 │              </

Found 1 clones.
ERROR: jscpd found too many duplicates (11.18%) over threshold (0%)
Error: ERROR: jscpd found too many duplicates (11.18%) over threshold (0%)
    at ThresholdReporter.report (/node_modules/@jscpd/finder/dist/reporters/threshold.js:12:19)
    at /node_modules/@jscpd/finder/dist/in-files-detector.js:82:26
    at Array.forEach (<anonymous>)
    at /node_modules/@jscpd/finder/dist/in-files-detector.js:81:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
------

Code:

import { memo, useContext } from "react";
import ContextIndex from "../../../../utils/context/index";
import ContextGlobal from "../../../../utils/context/_global";
import GenButton from "../../../gen/button";
import GenImage from "../../../gen/image";
import EditorFileExplorer from "./fileExplorer";
import styles from "./index.module.css";
const EditorSidebar: React.FC = () => {
    const { isLightTheme, setIsLightTheme, session } = useContext(ContextGlobal);
    const {
        barState: { leftBarOpen, explorerOpen },
        updateBarState,
    } = useContext(ContextIndex);
    function handleAlert() {
        alert("Hello World");
    }

    return (
        <>

                <div className={`${styles.flexButtons} hoverParent`}>
                    <GenButton
                        props={{
                            label: "Sidebar: toggle file explorer",
                            onClick:
                                session?.user !== undefined
                                    ? () => updateBarState({ type: "explorerOpen" })
                                    : handleAlert,
                        }}
                    >

                    </GenButton>

                    <GenButton props={{ label: "Sidebar: search" }}>

                    </GenButton>

                    <GenButton props={{ label: "Sidebar: save" }}>

                    </GenButton>

                    <GenButton props={{ label: "Sidebar: language" }}>

                    </GenButton>

                    <GenButton props={{ label: "Sidebar: launch" }}>

                    </GenButton>

                    <GenButton props={{ label: "Sidebar: more info" }}>

                    </GenButton>

                <div className={`${styles.flexButtons} hoverParent`}>
                    <GenButton props={{ label: "Sidebar: profile" }}>
                        {session?.user.image !== undefined ? (
                            <GenImage
                                props={{
                                    src: session.user.image,
                                    height: 40,
                                    width: 40,
                                    alt: session.user.name,
                                    className: styles.profileImage,
                                }}
                            />
                        ) : (

                        )}
                    </GenButton>
                    <GenButton
                        props={{
                            label: "Sidebar: toggle theme",
                            onClick: () => setIsLightTheme((prev) => !prev),
                        }}
                    >
                        {isLightTheme ? (

                        ) : (

                        )}
                    </GenButton>
                    <GenButton props={{ label: "Sidebar: settings" }}>

                    </GenButton>

            {explorerOpen && <EditorFileExplorer />}
        </>
    );
};

export default memo(EditorSidebar);


问:
How to load the data from Kafka to sql using talend
I am trying to load the data from tkafkainput to tdboutput, how to the data dynamically without stoping Kafka input

Kafka to sql using talend