问:
Laravel vue.js - Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500 (this happens to a only one API url, others are ok)
i'm kindof new to vue.js and i'm having CORS error with one of my API.
All API's are working perfectly but this particular api keeps giving me the following error. For some reason this only shows on production, but on my localhost it works properly.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://website.com/api/list/items. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500

Below is a sample of my vue.js axios post request

```<code>axios.post('https://website.com/api/list/items',
                    {
                            requestid: this.currentrequestid,
                            status: this.currentstatus,
                            user: this.currentpuserid,
                            ruser: this.currentruserid,
                            start: this.start,
                            take: this.take,
                            sortby: this.sortBy,
                            sortdir: this.sortdir,
                            stext: this.searchrequesttitle,
                            search: this.showclear,
                            type: this.currenttype,
                            supplier: this.currentsupplierid
                        },

                    {
                    headers: {
                        "Authorization" : "Bearer " + this.token,

                    },

                }).then((response) =>{

                        if(response.data.error){
                            this.$swal({
                                title: "Not Authorized",
                                text: "Close and reselect from tedBase",
                                icon: "error",
                                showConfirmButton: false
                            })

                        } else {
                            this.items = response.data.items;
                            console.log(this.items[0]);
                            this.numresults = response.data.results;
                            this.isBusy = false;

                            if(this.items.length === 0){
                                this.$swal({
                                    title: "Ooops",
                                    text: "Nothing found for search",
                                    icon: "warning",
                                    timer: 3000,
                                    showConfirmButton: false
                                });
                            }

                        }

                        }).catch(err => {
                            this.$swal({
                                title: "System Error",
                                text: err,
                                icon: "warning",
                                showConfirmButton: false
                                })
                    })
</code>```

This is my config/cors.php

```<code> 'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => false,

'supports_credentials' => true
</code>```

HandleCors.php

```<code><?php

namespace Fruitcake\Cors;

use Closure;
use Asm89\Stack\CorsService;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
use Symfony\Component\HttpFoundation\Response;

class HandleCors
{
    /** @var CorsService $cors */
    protected $cors;

    /** @var \Illuminate\Contracts\Container\Container $container */
    protected $container;

    public function __construct(CorsService $cors, Container $container)
    {
        $this->cors = $cors;
        $this->container = $container;
    }

    /**
     * Handle an incoming request. Based on Asm89\Stack\Cors by asm89
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        // Check if we're dealing with CORS and if we should handle it
        if (! $this->shouldRun($request)) {
            return $next($request);
        }

        // For Preflight, return the Preflight response
        if ($this->cors->isPreflightRequest($request)) {
            $response = $this->cors->handlePreflightRequest($request);

            $this->cors->varyHeader($response, 'Access-Control-Request-Method');

            return $response;
        }

        // Handle the request
        $response = $next($request);

        if ($request->getMethod() === 'OPTIONS') {
            $this->cors->varyHeader($response, 'Access-Control-Request-Method');
        }

        return $this->addHeaders($request, $response);
    }

    /**
     * Add the headers to the Response, if they don't exist yet.
     *
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    protected function addHeaders(Request $request, Response $response): Response
    {
        if (! $response->headers->has('Access-Control-Allow-Origin')) {
            // Add the CORS headers to the Response
            $response = $this->cors->addActualRequestHeaders($response, $request);
        }

        return $response;
    }

    /**
     * Add the headers to the Response, if they don't exist yet.
     *
     * @param RequestHandled $event
     * @deprecated
     */
    public function onRequestHandled(RequestHandled $event)
    {
        if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) {
            $this->addHeaders($event->request, $event->response);
        }
    }

    /**
     * Determine if the request has a URI that should pass through the CORS flow.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function shouldRun(Request $request): bool
    {
        return $this->isMatchingPath($request);
    }

    /**
     * The the path from the config, to see if the CORS Service should run
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function isMatchingPath(Request $request): bool
    {
        // Get the paths from the config or the middleware
        $paths = $this->getPathsByHost($request->getHost());

        foreach ($paths as $path) {
            if ($path !== '/') {
                $path = trim($path, '/');
            }

            if ($request->fullUrlIs($path) || $request->is($path)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Paths by given host or string values in config by default
     *
     * @param string $host
     * @return array
     */
    protected function getPathsByHost(string $host)
    {
        $paths = $this->container['config']->get('cors.paths', []);
        // If where are paths by given host
        if (isset($paths[$host])) {
            return $paths[$host];
        }
        // Defaults
        return array_filter($paths, function ($path) {
            return is_string($path);
        });
    }
}

</code>```

I also use "fruitcake/laravel-cors": "^2.0",

I've been on this for hours and i would appreciate your assistance.

I have added several headers to the request, i use fruitcake laravel package. but nothing seems to be working.

Only this url displays the CORS error, the other urls work perfectly. How is that possible?

Body:
i'm kindof new to vue.js and i'm having CORS error with one of my API.
All API's are working perfectly but this particular api keeps giving me the following error. For some reason this only shows on production, but on my localhost it works properly.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://website.com/api/list/items. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500

Below is a sample of my vue.js axios post request

axios.post('https://website.com/api/list/items',
                    {
                            requestid: this.currentrequestid,
                            status: this.currentstatus,
                            user: this.currentpuserid,
                            ruser: this.currentruserid,
                            start: this.start,
                            take: this.take,
                            sortby: this.sortBy,
                            sortdir: this.sortdir,
                            stext: this.searchrequesttitle,
                            search: this.showclear,
                            type: this.currenttype,
                            supplier: this.currentsupplierid
                        },

                    {
                    headers: {
                        "Authorization" : "Bearer " + this.token,

                    },

                }).then((response) =>{

                        if(response.data.error){
                            this.$swal({
                                title: "Not Authorized",
                                text: "Close and reselect from tedBase",
                                icon: "error",
                                showConfirmButton: false
                            })

                        } else {
                            this.items = response.data.items;
                            console.log(this.items[0]);
                            this.numresults = response.data.results;
                            this.isBusy = false;

                            if(this.items.length === 0){
                                this.$swal({
                                    title: "Ooops",
                                    text: "Nothing found for search",
                                    icon: "warning",
                                    timer: 3000,
                                    showConfirmButton: false
                                });
                            }

                        }

                        }).catch(err => {
                            this.$swal({
                                title: "System Error",
                                text: err,
                                icon: "warning",
                                showConfirmButton: false
                                })
                    })

This is my config/cors.php

 'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => false,

'supports_credentials' => true

HandleCors.php

<?php

namespace Fruitcake\Cors;

use Closure;
use Asm89\Stack\CorsService;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
use Symfony\Component\HttpFoundation\Response;

class HandleCors
{
    /** @var CorsService $cors */
    protected $cors;

    /** @var \Illuminate\Contracts\Container\Container $container */
    protected $container;

    public function __construct(CorsService $cors, Container $container)
    {
        $this->cors = $cors;
        $this->container = $container;
    }

    /**
     * Handle an incoming request. Based on Asm89\Stack\Cors by asm89
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        // Check if we're dealing with CORS and if we should handle it
        if (! $this->shouldRun($request)) {
            return $next($request);
        }

        // For Preflight, return the Preflight response
        if ($this->cors->isPreflightRequest($request)) {
            $response = $this->cors->handlePreflightRequest($request);

            $this->cors->varyHeader($response, 'Access-Control-Request-Method');

            return $response;
        }

        // Handle the request
        $response = $next($request);

        if ($request->getMethod() === 'OPTIONS') {
            $this->cors->varyHeader($response, 'Access-Control-Request-Method');
        }

        return $this->addHeaders($request, $response);
    }

    /**
     * Add the headers to the Response, if they don't exist yet.
     *
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    protected function addHeaders(Request $request, Response $response): Response
    {
        if (! $response->headers->has('Access-Control-Allow-Origin')) {
            // Add the CORS headers to the Response
            $response = $this->cors->addActualRequestHeaders($response, $request);
        }

        return $response;
    }

    /**
     * Add the headers to the Response, if they don't exist yet.
     *
     * @param RequestHandled $event
     * @deprecated
     */
    public function onRequestHandled(RequestHandled $event)
    {
        if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) {
            $this->addHeaders($event->request, $event->response);
        }
    }

    /**
     * Determine if the request has a URI that should pass through the CORS flow.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function shouldRun(Request $request): bool
    {
        return $this->isMatchingPath($request);
    }

    /**
     * The the path from the config, to see if the CORS Service should run
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function isMatchingPath(Request $request): bool
    {
        // Get the paths from the config or the middleware
        $paths = $this->getPathsByHost($request->getHost());

        foreach ($paths as $path) {
            if ($path !== '/') {
                $path = trim($path, '/');
            }

            if ($request->fullUrlIs($path) || $request->is($path)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Paths by given host or string values in config by default
     *
     * @param string $host
     * @return array
     */
    protected function getPathsByHost(string $host)
    {
        $paths = $this->container['config']->get('cors.paths', []);
        // If where are paths by given host
        if (isset($paths[$host])) {
            return $paths[$host];
        }
        // Defaults
        return array_filter($paths, function ($path) {
            return is_string($path);
        });
    }
}

I also use "fruitcake/laravel-cors": "^2.0",

I've been on this for hours and i would appreciate your assistance.

I have added several headers to the request, i use fruitcake laravel package. but nothing seems to be working.

Only this url displays the CORS error, the other urls work perfectly. How is that possible?


来源: stackexchange

问:
Does a widcard cert invalidate existing subdomain certs?
I have several certs from godaddy for subdomains like vpn.mysite.com and data-server.mysite.com. If I purchase a wildcard cert for *.mysite.com will my current certs become invalid and need replacing? Or can I use them til they expire then swap them out for the wildcard?</p>

ContentLicense: CC BY-SA 4.0


问:
Add checkboxes and multi-select-dropdown in angular-datatables v8.0.0
Facing issues with implementing checkboxes and multi-select dropdown in angular datatables.
npm package angular-datatables: 8.0.0

Trying to create checkbox and ng-multiselect-dropdown column in angular datatables. but after the implementation of following code getting [Object, Object] in the browser display.

```<code>in .ts file this is the following code
this.dtOptions = {
pagingType: 'full_numbers',
responsive: true,
serverSide: true,
processing: true,
autoWidth: true,
searchHighlight: true,
visible: true,
api: true,
"ordering": true,
searchDelay: 2000,
"scrollCollapse": true,
'columnDefs': [ {
'orderable': false,
targets: 0,
width: 20,
className: 'select-checkbox'
},
{
targets: 1,
}],
ajax: (dataTablesParameters: any, callback) => {
this.checkClass = "overlay";
this.newService.getNewList("test", dataTablesParameters)
.subscribe(resp => {
this.checkClass = "hiddenOverlay";
this.totRecs = 15;
if (this.totRecs === 10000 && this.showPop) {
this.delayedPopover();
}
callback({
recordsTotal: 15,// assign total records
recordsFiltered: 15,// assign total records
data: resp.body['data'],
});
});
},
columns: [
{ data: null  },//checkbox1
{ data: null  },//checkbox2
{ data: 'FIELD1', "defaultContent": "N/A" },
{ data: null }, //multiselect
],
};
in .html file
<thead style="width:100%; font-size: 12px;">
<tr>
<th>Submit</th>
<th>Skip</th>
<th class="non-editable-column astrik">Claim No</th>
<th>Drivers</th>
</tr>
</thead>

<tbody style="width:100%; font-size: 12px;">
<tr *ngFor="let c of test; let i of index">
<td><input type="checkbox" name="websitecheck"> </td>
<td><input type="checkbox"  name="websitecheck1" > </td>
<td >{{c.FIELD1}}</td>
<td>
<ng-multiselect-dropdown
[style.pointer-events]="c.SKIPPED==1 ? 'none' : 'auto'"
[disabled]="c.SKIPPED==1?1:0"
class="custom-font-size"
[placeholder]="'Select Drivers'"
[settings]="dropdownSettings"
[data]="dropdownList"
[(ngModel)]="c.DRIVERS"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
>
</ng-multiselect-dropdown>
</td>
</tr>
</tbody>`
</code>```

Body:
Facing issues with implementing checkboxes and multi-select dropdown in angular datatables.
npm package angular-datatables: 8.0.0

Trying to create checkbox and ng-multiselect-dropdown column in angular datatables. but after the implementation of following code getting [Object, Object] in the browser display.

in .ts file this is the following code
this.dtOptions = {
pagingType: 'full_numbers',
responsive: true,
serverSide: true,
processing: true,
autoWidth: true,
searchHighlight: true,
visible: true,
api: true,
"ordering": true,
searchDelay: 2000,
"scrollCollapse": true,
'columnDefs': [ {
'orderable': false,
targets: 0,
width: 20,
className: 'select-checkbox'
},
{
targets: 1,
}],
ajax: (dataTablesParameters: any, callback) => {
this.checkClass = "overlay";
this.newService.getNewList("test", dataTablesParameters)
.subscribe(resp => {
this.checkClass = "hiddenOverlay";
this.totRecs = 15;
if (this.totRecs === 10000 && this.showPop) {
this.delayedPopover();
}
callback({
recordsTotal: 15,// assign total records
recordsFiltered: 15,// assign total records
data: resp.body['data'],
});
});
},
columns: [
{ data: null  },//checkbox1
{ data: null  },//checkbox2
{ data: 'FIELD1', "defaultContent": "N/A" },
{ data: null }, //multiselect
],
};
in .html file

Submit
Skip
Claim No
Drivers

<input type="checkbox" name="websitecheck">
<input type="checkbox"  name="websitecheck1" >
{{c.FIELD1}}

<ng-multiselect-dropdown
[style.pointer-events]="c.SKIPPED==1 ? 'none' : 'auto'"
[disabled]="c.SKIPPED==1?1:0"
class="custom-font-size"
[placeholder]="'Select Drivers'"
[settings]="dropdownSettings"
[data]="dropdownList"
[(ngModel)]="c.DRIVERS"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
>
</ng-multiselect-dropdown>

`


问:
Create all possible combinations of entries from multiple lists
I have different scalar metrics that I need to take inventory of in a large repository of data. The format of one entry for a metric would look something like this:

```<code>{a}_{b}_{c}_{d}
            # Where ${a} = subjid, ex. "1000061"
            # Where ${b} = "ROIstats"
            # Where ${c} = statistic, [mean, median, sigma]
            # Where ${d} = modality, [AX, FA, RAD, TR]
            # EXAMPLE DOWN BELOW:
            # {a}_{b}_{c}_{d} = 1000061_ROIstats_mean_FA
</code>```

There should be 24 combos total (as seen below):

I am attempting to use itertools.product after concatenating {a} and {b} since there is only one possible entry for both (one unique subject ID which I am getting from a list found_subjs, and "ROIstats" respectively. Is there a way I can combine {a}, {b}, {c}, and {d} together to capture all the points for each {a}_{b}?

Here is my attempt. I don't know if I need to change the formatting or put the combinations in a seperate list:

```<code>cs = ["mean", "median", "sigma"]
ds = ["AX", "FA", "fwAX", "fwFA", "fwRAD", "fwVF", "RAD", "TR"]

for s in found_subjs:
    os.chdir("{final_destination}\\{s}".format(final_destination=final_destination, s=s))
    for c,d in product(cs, ds):
        print(s+"_"+"ROIstats"+"_"+c+"_"+d)

Traceback (most recent call last):

  File "<ipython-input-34-7fa394581c24>", line 4, in <module>
    print(s+"_"+"ROIstats"+"_"+c+"_"+d)

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')

</code>```

Body:
I have different scalar metrics that I need to take inventory of in a large repository of data. The format of one entry for a metric would look something like this:

{a}_{b}_{c}_{d}
            # Where ${a} = subjid, ex. "1000061"
            # Where ${b} = "ROIstats"
            # Where ${c} = statistic, [mean, median, sigma]
            # Where ${d} = modality, [AX, FA, RAD, TR]
            # EXAMPLE DOWN BELOW:
            # {a}_{b}_{c}_{d} = 1000061_ROIstats_mean_FA

There should be 24 combos total (as seen below):

I am attempting to use itertools.product after concatenating {a} and {b} since there is only one possible entry for both (one unique subject ID which I am getting from a list found_subjs, and "ROIstats" respectively. Is there a way I can combine {a}, {b}, {c}, and {d} together to capture all the points for each {a}_{b}?

Here is my attempt. I don't know if I need to change the formatting or put the combinations in a seperate list:

cs = ["mean", "median", "sigma"]
ds = ["AX", "FA", "fwAX", "fwFA", "fwRAD", "fwVF", "RAD", "TR"]

for s in found_subjs:
    os.chdir("{final_destination}\\{s}".format(final_destination=final_destination, s=s))
    for c,d in product(cs, ds):
        print(s+"_"+"ROIstats"+"_"+c+"_"+d)

Traceback (most recent call last):

  File "<ipython-input-34-7fa394581c24>", line 4, in <module>
    print(s+"_"+"ROIstats"+"_"+c+"_"+d)

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')


问:
How to set values for react-select with dynamic rendering of select fields?
I was working on rendering dynamic select fields and trying to set the values for them . Let me explain clearly what i am trying .

At first i have this useState :

```<code>  const add_actions_options = [
    {value : "val1" , label:VAL1},
    {value : "val2" , label:VAL2 })}
  ]

  const [ actions , setActions ] = useState<any | undefined>([{type : add_actions_options[0].value , label : "" , data : ""} ])
</code>```

Initially 1 select field is rendered , but later i have a button which renders more select fields ( Max 4 select fields ) below is the related code for dynamic rendering of Select fields fields:

```<code>  function addAction(){
    if(actions.length < 4 ){
      setActions([...actions , {type : add_actions_options[0].value , label : "" , data : ""}])
   } else {
    toast('max 4 allowed', { type: "error" })
    }
  }

  const handleTypeChange = (index, value) => {
    const updatedFields = [...actions];
    updatedFields[index].type = value;
    setActions(updatedFields);
  }

  const handleLabelChange = (index , value) => {
    const updatedFields = [...actions];
    updatedFields[index].label = value;
    setActions(updatedFields);
  }
  const handleDataChange = (index, value) => {
    const updatedFields = [...actions];
    updatedFields[index].data = value;
    setActions(updatedFields);
  }

 <button className='btn btn-primary btn-sm btn-block' onClick={() => addAction()}>{intl.formatMessage({id: 'ADD.ACTION'})}</button>

 <div className='row my-6 '>
                      {actions.map((item , index) => {
                          return(
                            <div key={index} className='row my-6'>
                               <div className='col-4'>
                                 <h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.TYPE' })}*</label></h4>
                                 <Select
                                    defaultValue={add_actions_options[0]}
                                    onChange={(value) => handleTypeChange(index, value)}
                                    options={add_actions_options}
                                  />
                               </div>
                               <div className='col-4'>
                                 <h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.LABEL' })}*</label></h4>
                                 <input

                                      className="form-control form-control-lg form-control-solid"
                                      name='action.label'
                                      type="text"
                                      maxLength={30}
                                      onChange={(event) => handleLabelChange(index, event.target.value)}
                                      value={actions.label}
                                      required
                                     />
                               </div>
                               <div className='col-4'>
                                 <h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.DATA' })}*</label></h4>
                                 <input

                                      className="form-control form-control-lg form-control-solid"
                                      name='action.data'
                                      type="text"
                                      maxLength={100}
                                      onChange={(event) => handleDataChange(index, event.target.value)}
                                      value={actions.data}
                                      required
                                     />
                               </div>

                            </div>
                          )
                        })}
    </div>

</code>```

Here's what i wanted to achieve  , the data and label values for actions are working as expected , but the value is being set differently when i choose options from select dropdown,

Initially if i do not change any values for select component it is working as expected , the output :

```<code>0: {type:'val1' , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}
</code>```

Note : In above scenario I am just rendering one more select fields and initially the type is set to add_actions_options[0].value , but if I try to select val2 from the dropdown the output turns to :

```<code>0: {type: {value: 'val2', label: 'VAL2'} , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}

//DESIRED OUTPUT WHEN I CHOOSE DIFFERENT OPTION IN SELECT TAG
0: {type: 'val2' , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}
</code>```

I just want the val2 to be placed within type , but its placing whole selected option , can anyone help me pass this ? Would be great help for me !

Regards

Body:
I was working on rendering dynamic select fields and trying to set the values for them . Let me explain clearly what i am trying .

At first i have this useState :

  const add_actions_options = [
    {value : "val1" , label:VAL1},
    {value : "val2" , label:VAL2 })}
  ]

  const [ actions , setActions ] = useState<any | undefined>([{type : add_actions_options[0].value , label : "" , data : ""} ])

Initially 1 select field is rendered , but later i have a button which renders more select fields ( Max 4 select fields ) below is the related code for dynamic rendering of Select fields fields:

  function addAction(){
    if(actions.length < 4 ){
      setActions([...actions , {type : add_actions_options[0].value , label : "" , data : ""}])
   } else {
    toast('max 4 allowed', { type: "error" })
    }
  }

  const handleTypeChange = (index, value) => {
    const updatedFields = [...actions];
    updatedFields[index].type = value;
    setActions(updatedFields);
  }

  const handleLabelChange = (index , value) => {
    const updatedFields = [...actions];
    updatedFields[index].label = value;
    setActions(updatedFields);
  }
  const handleDataChange = (index, value) => {
    const updatedFields = [...actions];
    updatedFields[index].data = value;
    setActions(updatedFields);
  }

 <button className='btn btn-primary btn-sm btn-block' onClick={() => addAction()}>{intl.formatMessage({id: 'ADD.ACTION'})}</button>

                      {actions.map((item , index) => {
                          return(

{intl.formatMessage({ id: 'TEMPLATE.TYPE' })}*

                                 <Select
                                    defaultValue={add_actions_options[0]}
                                    onChange={(value) => handleTypeChange(index, value)}
                                    options={add_actions_options}
                                  />

{intl.formatMessage({ id: 'TEMPLATE.LABEL' })}*

                                 <input

                                      className="form-control form-control-lg form-control-solid"
                                      name='action.label'
                                      type="text"
                                      maxLength={30}
                                      onChange={(event) => handleLabelChange(index, event.target.value)}
                                      value={actions.label}
                                      required
                                     />

{intl.formatMessage({ id: 'TEMPLATE.DATA' })}*

                                 <input

                                      className="form-control form-control-lg form-control-solid"
                                      name='action.data'
                                      type="text"
                                      maxLength={100}
                                      onChange={(event) => handleDataChange(index, event.target.value)}
                                      value={actions.data}
                                      required
                                     />

                          )
                        })}

Here's what i wanted to achieve  , the data and label values for actions are working as expected , but the value is being set differently when i choose options from select dropdown,

Initially if i do not change any values for select component it is working as expected , the output :

0: {type:'val1' , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}

Note : In above scenario I am just rendering one more select fields and initially the type is set to add_actions_options[0].value , but if I try to select val2 from the dropdown the output turns to :

0: {type: {value: 'val2', label: 'VAL2'} , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}

//DESIRED OUTPUT WHEN I CHOOSE DIFFERENT OPTION IN SELECT TAG
0: {type: 'val2' , label : 'qwe' , data:'ujm'}
1: {type:'val1' , label : 'ujhn' , data: 'uhn'}

I just want the val2 to be placed within type , but its placing whole selected option , can anyone help me pass this ? Would be great help for me !

Regards


问:
How can I exclude certain scenarios from parallelization automatically with specflow?
We use SpecFlow with NUnit to write our BDD tests.

Since we switched our testruns to run parallel we have an issue with some tests failing because a shared resource seems to be altered which messes up the state we expect when running the scenario.

Unfortunately we cannot simply change this access to a global resource so I'd like to exclude scenarios automatically when they make use of a step that modifies said resource.

I saw that there is a setting addNonParallelizableMarkerForTags:

```<code>  "generator": {
    "addNonParallelizableMarkerForTags": [
      "NotParallel"
    ]
  },
</code>```

but unfortunatelly this seems to only work on feature level and not on scenario level. Also it has to be added manually, so developers could forget to add it.

Is such a thing supported in SpecFlow and if yes, how could this be done?

Body:
We use SpecFlow with NUnit to write our BDD tests.

Since we switched our testruns to run parallel we have an issue with some tests failing because a shared resource seems to be altered which messes up the state we expect when running the scenario.

Unfortunately we cannot simply change this access to a global resource so I'd like to exclude scenarios automatically when they make use of a step that modifies said resource.

I saw that there is a setting addNonParallelizableMarkerForTags:

  "generator": {
    "addNonParallelizableMarkerForTags": [
      "NotParallel"
    ]
  },

but unfortunatelly this seems to only work on feature level and not on scenario level. Also it has to be added manually, so developers could forget to add it.

Is such a thing supported in SpecFlow and if yes, how could this be done?


问:
VBScript Get Active Internal IP of Device Excluding Inactive or Disconnected
In need of a vbscript to grab the laptop or desktop local IP address, while ignoring things such as local adapters that are NOT actively in use.
Ignoring adapters with no gateway set, or no mac address.

Have tried the below but unable to get proper result, as I also have an adapter that has no gateway and it pulls that one... How to ignore?

```<code>strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress > '' AND IPEnabled = 'True'"

Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
Set colItems      = objWMIService.ExecQuery( strQuery, "WQL", 48 )

For Each objItem In colItems
    If IsArray( objItem.IPAddress ) Then
        If UBound( objItem.IPAddress ) = 0 Then
            strIP = "IP Address: " & objItem.IPAddress(0)
        Else
            strIP = "IP Addresses: " & Join( objItem.IPAddress, ",   IPv6: " )
        End If
    End If
Next
</code>```

I have tried adding "AND DefaultIPGateway > ''" to the query but this fails and returns nothing.

Body:
In need of a vbscript to grab the laptop or desktop local IP address, while ignoring things such as local adapters that are NOT actively in use.
Ignoring adapters with no gateway set, or no mac address.

Have tried the below but unable to get proper result, as I also have an adapter that has no gateway and it pulls that one... How to ignore?

strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress > '' AND IPEnabled = 'True'"

Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
Set colItems      = objWMIService.ExecQuery( strQuery, "WQL", 48 )

For Each objItem In colItems
    If IsArray( objItem.IPAddress ) Then
        If UBound( objItem.IPAddress ) = 0 Then
            strIP = "IP Address: " & objItem.IPAddress(0)
        Else
            strIP = "IP Addresses: " & Join( objItem.IPAddress, ",   IPv6: " )
        End If
    End If
Next

I have tried adding "AND DefaultIPGateway > ''" to the query but this fails and returns nothing.


问:
Steganography with Microsoft Word - DOCX
I write a application hide a of string within a .docx file.

A Docx file comprises of a collection of XML files that are contained inside a ZIP archive. So, My program treat that file like a zip file and hide secret string in it.

After research, I found a way to insert data to ZIP archive.

A Secret String is injected after a file section right before the 1st central directory header. After that, a pointer in an end of central directory record is updated to compensate the shift of the central directory header.

My output docx file work fine with typical file archivers (7-zip, WinRAR, File Roller, &c) or file managers (Windows Explorer).
But when I open my output docx file with Microsoft Word it said:

Here is link for input and output file

What step did I wrong or missing?


问:
how to run .net core api
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.DbContext Lifetime: Scoped ImplementationType:
GareebWebApi.Data.DataDbContext

I tryied this
builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

```<code>type here
</code>```

Title: how to run .net core api

Body:
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.DbContext Lifetime: Scoped ImplementationType:
GareebWebApi.Data.DataDbContext

I tryied this
builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

type here


问:
How to restrict access to Identity Toolkit API?
I have a Next.js website with firebase. It takes care of everything I need with authentication. However, In addition to the signInWithPopup, I am also using signInWithEmailAndPassword function in order to let my users authenticate using email and password.

The problem is that signInWithEmailAndPassword sends a request to:

```<code>https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[PUBLIC_KEY]
</code>```

And it returns a valid response with the authToken. And when I paste the request in Postman, I see that everyone can access this endpoint. How can I protect this route? I want this route to be accessible just from my website.

I saw that there is something called App-Check that can restrict access to API but couldn't find a way to make it work.

Thank you!

Body:
I have a Next.js website with firebase. It takes care of everything I need with authentication. However, In addition to the signInWithPopup, I am also using signInWithEmailAndPassword function in order to let my users authenticate using email and password.

The problem is that signInWithEmailAndPassword sends a request to:

https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[PUBLIC_KEY]

And it returns a valid response with the authToken. And when I paste the request in Postman, I see that everyone can access this endpoint. How can I protect this route? I want this route to be accessible just from my website.

I saw that there is something called App-Check that can restrict access to API but couldn't find a way to make it work.

Thank you!


问:
Python QT application crashing from memory error, how to debug?
I have a PyQt application that occasionally will crash due to memory issues with the error shown below

```<code>The instruction at 0X00007FFC450FA07 reference memory at 0X0000000000000048. The memory could not be read.
</code>```

I personally have not been able to reproduce this error in any way. It has happened on the computer's of a few people I work with while running my application. I have looked and see a lot of questions for languages like C# or C++, and it seems to be a pointer issue. Since I am using Python though, these questions and solutions are not very relevant since Python does not use pointers.

Seen here: C# example question the problem here is a long running thread. I do use threading in my application so I have been looking there. I have ran my application many times with the task manager open to monitor threads and have not seen any problems. All threads seem to close. If there is a better way to monitor this please let me know.

I am using PyCharm and my Python version is 3.9. I am also using Pyinstaller to create an executable version of the application. I have ran the program using the command line, launching the executable, and also directly through PyCharm and have not been able to see the error at all or debug it.

Is it possible this is happening due to bit related issues? Meaning that I am compiling my code using a 32-bit version of Python, could some computers have a problem with that? Would compiling with a 64 bit version possibly solve this?

Body:
I have a PyQt application that occasionally will crash due to memory issues with the error shown below

The instruction at 0X00007FFC450FA07 reference memory at 0X0000000000000048. The memory could not be read.

I personally have not been able to reproduce this error in any way. It has happened on the computer's of a few people I work with while running my application. I have looked and see a lot of questions for languages like C# or C++, and it seems to be a pointer issue. Since I am using Python though, these questions and solutions are not very relevant since Python does not use pointers.

Seen here: C# example question the problem here is a long running thread. I do use threading in my application so I have been looking there. I have ran my application many times with the task manager open to monitor threads and have not seen any problems. All threads seem to close. If there is a better way to monitor this please let me know.

I am using PyCharm and my Python version is 3.9. I am also using Pyinstaller to create an executable version of the application. I have ran the program using the command line, launching the executable, and also directly through PyCharm and have not been able to see the error at all or debug it.

Is it possible this is happening due to bit related issues? Meaning that I am compiling my code using a 32-bit version of Python, could some computers have a problem with that? Would compiling with a 64 bit version possibly solve this?


问:
Maven Unable to Collect Dependencies at Extra Repositories
I working on converting a project from ant to maven and am getting errors trying to pull in jars from geomajas.

I am not behind a firewall and the dependencies from maven central are downloading.  I have also added geomajas to the repositories in my projects pom.xml.

Below are the relevant portions from the pom.xml and the error I am getting.

If I instead define the jar dependency with a system path to a local copy of the jar the project builds successfully.

```<code>
<dependency>
    <groupId>org.lobobrowser</groupId>
    <artifactId>cobra</artifactId>
    <version>0.98.4</version>
</dependency>
.....
<repository>
    <id>geomajas</id>
    <name>Geomajas Maven Repository</name>
    <url>https://maven.geomajas.org/(https://maven.geomajas.org/)</url>
</repository>
</code>```
```<code>
[ERROR] Failed to execute goal on project niksun-services-util: Could not resolve dependencies for project com.niksun:niksun-services-util:jar:main: Failed to collect dependencies at org.lobobrowser:cobra:jar:0.98.4: Failed to read artifact descriptor for org.lobobrowser:cobra:jar:0.98.4: Could not transfer artifact org.lobobrowser:cobra:pom:0.98.4 from/to geomajas (http://maven.geomajas.org/(http://maven.geomajas.org/)): connect timed out -> [Help 1]
</code>```

Body:
I working on converting a project from ant to maven and am getting errors trying to pull in jars from geomajas.

I am not behind a firewall and the dependencies from maven central are downloading.  I have also added geomajas to the repositories in my projects pom.xml.

Below are the relevant portions from the pom.xml and the error I am getting.

If I instead define the jar dependency with a system path to a local copy of the jar the project builds successfully.

<dependency>
    <groupId>org.lobobrowser</groupId>
    <artifactId>cobra</artifactId>
    <version>0.98.4</version>
</dependency>
.....
<repository>
    <id>geomajas</id>
    <name>Geomajas Maven Repository</name>
    <url>https://maven.geomajas.org/(https://maven.geomajas.org/)</url>
</repository>

[ERROR] Failed to execute goal on project niksun-services-util: Could not resolve dependencies for project com.niksun:niksun-services-util:jar:main: Failed to collect dependencies at org.lobobrowser:cobra:jar:0.98.4: Failed to read artifact descriptor for org.lobobrowser:cobra:jar:0.98.4: Could not transfer artifact org.lobobrowser:cobra:pom:0.98.4 from/to geomajas (http://maven.geomajas.org/(http://maven.geomajas.org/)): connect timed out -> [Help 1]


问:
quarto yaml to render qmd files that start with _
I'm playing around with two different models for my website in quarto, one includes all the chapters in the index.qmd file so I have to name each chapter with an underscore in front.

When I try to render the chapters separately, they aren't rendered as they start with _, e.g. "chapters/_02-Intro_to_analysis_software.qmd".

I've tried explicitly telling quarto to render these chapters using _quarto.yml

```<code>project:
  type: website
  render:
    - index.qmd
    - about.qmd
    - "chapters/_01-Intro_to_quant_methods.qmd"
    - chapters/_02-Intro_to_analysis_software.qmd
</code>```

But when I run quarto render it only renders the about and index qmd files.

```<code>[...]
label: unnamed-chunk-1
  |......................................................................| 100%
  ordinary text without R code

?[31moutput file: index.knit.md

?[39m←[1m←[34m[2/2] about.qmd←[39m←[22m

Output created: _site\index.html
</code>```

How do I get quarto to render files that start with an underscore?

Body:
I'm playing around with two different models for my website in quarto, one includes all the chapters in the index.qmd file so I have to name each chapter with an underscore in front.

When I try to render the chapters separately, they aren't rendered as they start with _, e.g. "chapters/_02-Intro_to_analysis_software.qmd".

I've tried explicitly telling quarto to render these chapters using _quarto.yml

project:
  type: website
  render:
    - index.qmd
    - about.qmd
    - "chapters/_01-Intro_to_quant_methods.qmd"
    - chapters/_02-Intro_to_analysis_software.qmd

But when I run quarto render it only renders the about and index qmd files.

[...]
label: unnamed-chunk-1
  |......................................................................| 100%
  ordinary text without R code

?[31moutput file: index.knit.md

?[39m←[1m←[34m[2/2] about.qmd←[39m←[22m

Output created: _site\index.html

How do I get quarto to render files that start with an underscore?


问:
How can I have istio gateway traces in OpenTelemetry?
I'll be really gratefull if someone have a documentation or experience with this implementation and can share it. If there are unknown information from my side, please tell me to share it, because i dont know what is needed to describe my entire situation.
The version are Istio 1.61.1 and OtelCollector 0.68.0

I'm trying to get traces from the istio gateway and send to OpenTelemetry.
I'm using openCensus agent and following this documentation as guide (distributed-tracing/opencensusagent).
Unfortunately i cannot succeed, because i get traces on OpenTelemetry log, but the traces has no relation with request made across the gateway.
The objective is to get all the request chain including the istio gateway, to watch the entire time response.


问:
EXCEL: Getting a range of cells to always total 100%, even if new percentages are added or taken away (other cells update)
I am trying for an Excel formula that will perform the following: I have a series of rows that hold percentages (e.g. total % of business by account), and a sum row which, of course, equals 100%. I am trying to make this dynamic. So, for example, I add 5% to one of the cells where there was 0%, and the distribution changes in the other cells in the range to still equal 100%. Like, slicing the pie differently and always getting to 100%. Thanks for any assistance!

My experience level with Excel is better than most, but limited. To frame it for the pros, I can peform lookups, ifs, countifs, that level of stuff. So, I started looking online and stumbled into a few things I found  with MMULT, SEQUENCE, OFFSET, COUNTIF... they're not doing what I'm asking though. It's possilbel I don't know the name or phrase for what it is I am looking to do for my staff, and that is dead-ending me.


问:
How to access key values from .yml file in a .js file?
I have an application.yml file with keys like:

```<code>key1: "foo1"
key2: "foo2"
key3: "foo3" etc...
</code>```

I want to access, say, key3 in my .js file and interpolate it into a string.

The code I am working with in my js file is just this one line:

```<code>    'redirect_uri': `https://sample/file/path`
</code>```

I want to replace "sample" with "key3" from my .yml file. so that it reads:

```<code>'redirect_uri': `https://foo3/foo5/foo6`
</code>```

Ive tried to just interpolate the key as:

```<code>'redirect_uri': `https://${this.key3}/foo5/foo6`
</code>```

but this has obviosuly not worked.

Body:
I have an application.yml file with keys like:

key1: "foo1"
key2: "foo2"
key3: "foo3" etc...

I want to access, say, key3 in my .js file and interpolate it into a string.

The code I am working with in my js file is just this one line:

    'redirect_uri': `https://sample/file/path`

I want to replace "sample" with "key3" from my .yml file. so that it reads:

'redirect_uri': `https://foo3/foo5/foo6`

Ive tried to just interpolate the key as:

'redirect_uri': `https://${this.key3}/foo5/foo6`

but this has obviosuly not worked.


问:
how to cast __m128 to union when returning
I want to return the result of _mm_add_ps() but the returning type should be a custon union that has __m128 member inside.

I tested the performance of returning __m128 and a custom union. It seems that on MSVC this:

```<code>return _mm_add_ps(V1, V2);
</code>```

is faster than this:

```<code>vector4 x = { .vector = _mm_add_ps(left.vector, right.vector) };
return x;
</code>```

where vector4 is defined as:

```<code>typedef union vector4
{
    struct { float x; float y; float z; float w; };
    struct { float r; float g; float b; float a; };
    struct { float s; float t; float m; float q; };
    float points[4];
    __m128 vector;
}  __declspec(align(16)) vector4;
</code>```

I wonder if I can just cast the result of the _mm_add_ps() which is __m128 to union vector4 directly to avoid this performance differance. This is also measured in release build.

I tried to use: return (vector4) _mm_add_ps(left.vector, right.vector);
But it doesn't work. Returning the error: No suitable conversion from __m128 to "float" exists.

Body:
I want to return the result of _mm_add_ps() but the returning type should be a custon union that has __m128 member inside.

I tested the performance of returning __m128 and a custom union. It seems that on MSVC this:

return _mm_add_ps(V1, V2);

is faster than this:

vector4 x = { .vector = _mm_add_ps(left.vector, right.vector) };
return x;

where vector4 is defined as:

typedef union vector4
{
    struct { float x; float y; float z; float w; };
    struct { float r; float g; float b; float a; };
    struct { float s; float t; float m; float q; };
    float points[4];
    __m128 vector;
}  __declspec(align(16)) vector4;

I wonder if I can just cast the result of the _mm_add_ps() which is __m128 to union vector4 directly to avoid this performance differance. This is also measured in release build.

I tried to use: return (vector4) _mm_add_ps(left.vector, right.vector);
But it doesn't work. Returning the error: No suitable conversion from __m128 to "float" exists.


问:
THREAD WARNING: exec() call to BackgroundModeExt.foreground blocked the main thread for 41ms. Plugin should use CordovaInterface.getThreadPool()
I have this problem.

when I call cordova.plugins.backgroundMode.moveToForeground(); It always works for me the first time, then I enter another application, for example Facebook, and this message is displayed in the logcat, what is it due to or how can I solve it?

I am using: https://github.com/FWiner/cordova-plugin-android-background-mode

This is the code that Cordova use for open app for to foreground:

```<code>private void moveToForeground()
{
  Activity  app = getApp();
  Intent intent = getLaunchIntent();

  intent.addFlags(
  Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
     Intent.FLAG_ACTIVITY_SINGLE_TOP |
     Intent.FLAG_ACTIVITY_CLEAR_TOP);

  clearScreenAndKeyguardFlags();
  app.startActivity(intent);
}
</code>```

Attached video of my problem with  moveToForeground():
https://drive.google.com/file/d/1SQJ-6FNQ2Nr0nZxw7JBYwhGkYt9D33R_/view

VIDEO SUMMARY:

I have the app open, then I exit.

when running postman a service is sent and the app is brought to the foreground (which is the correct way)

then I leave the app and enter facebook. I run postman and the app doesn't open in the foreground anymore (this is the bug I want to fix).

enter image description here

I am trying to open my application when it is in background mode, I have modified the moveToForeground() method and I have not had any results.

Body:
I have this problem.

when I call cordova.plugins.backgroundMode.moveToForeground(); It always works for me the first time, then I enter another application, for example Facebook, and this message is displayed in the logcat, what is it due to or how can I solve it?

I am using: https://github.com/FWiner/cordova-plugin-android-background-mode

This is the code that Cordova use for open app for to foreground:

private void moveToForeground()
{
  Activity  app = getApp();
  Intent intent = getLaunchIntent();

  intent.addFlags(
  Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
     Intent.FLAG_ACTIVITY_SINGLE_TOP |
     Intent.FLAG_ACTIVITY_CLEAR_TOP);

  clearScreenAndKeyguardFlags();
  app.startActivity(intent);
}

Attached video of my problem with  moveToForeground():
https://drive.google.com/file/d/1SQJ-6FNQ2Nr0nZxw7JBYwhGkYt9D33R_/view

VIDEO SUMMARY:

I have the app open, then I exit.

when running postman a service is sent and the app is brought to the foreground (which is the correct way)

then I leave the app and enter facebook. I run postman and the app doesn't open in the foreground anymore (this is the bug I want to fix).

enter image description here

I am trying to open my application when it is in background mode, I have modified the moveToForeground() method and I have not had any results.


问:
Forcing orientation on a full screen modal doesn't work on parent controller
iOS 16 introduced a new API for forcing orientation changes, which implies using the requestGeometryUpdate(_:errorHandler:).

It seems that it's not working as expected when using a full screen modal.

For example, let's say we have an app that locks the orientation in portrait mode except for a modally presented controller, a parent controller A and a modal controller B :

A is displayed

We put the device in landscape mode - A stays in portrait mode

B is opened modally fullscreen from A

B is displayed in landscape

B has a button to go back to portrait mode using the requestGeometryUpdate(_:errorHandler:)

B is dismissed through a button

A ends up in landscape

In the app delegate, we used supportedInterfaceOrientationsFor to force the app in portait mode except for the controller B.

We tried to call setNeedsUpdateOfSupportedInterfaceOrientations every time we call requestGeometryUpdate(_:errorHandler:).
We also tried to call it on the viewWillAppear from the controller A.
We finally tried to call requestGeometryUpdate(_:errorHandler:) from the controller A's viewWillAppear, without any luck as well.

Is this a bug in iOS 16 or are we missing something ?
It seems to be working as expected when displaying the modal over the current context, but it's not what we want in this case.

I can provide an example project if needed.


问:
combine gaussian mixture models
I'd like to combine gaussian mixture models (GMMs) without using the underlying input values for the models (because I don't want to save all the values).

I had two ideas:

Get weights, means and covariances from both GMMs, combine them (and weight the weights according to the number of input data) and build the combined model based on these with the number of components as the sum of the number of components of the individual models.

Pseudo example for 2 GMMs:

```<code>data_1=[1,2,1,3,1,2,5,2,1,2,7,6]
data_2=[5,4,6,5,6,5,8,5,6,7,12,12,13,15,20]

data_1 = np.expand_dims(data_1, 1)
data_2 = np.expand_dims(data_2, 1)

n_comp_1=get_best_amount_Gaussians(data_1)
n_comp_2=get_best_amount_Gaussians(data_2)

gm1=GaussianMixture(n_components=n_comp_1)
gm1.fit(data_1)
gm2=GaussianMixture(n_components=n_comp_2)
gm2.fit(data_2)

n_comp_3=n_comp_1+n_comp_2

#get weights, means and covs

#weight the weights according to the number of input values:
gm1_weights=gm1_weights*len(data_1)
gm2_weights=gm2_weights*len(data_2)
gm3_weights=np.concatenate((gm1_weights,gm2_weights),axis=0)

#build gm3 based on these values:
GaussianMixture(n_components=n_comp_3)

loaded_gmm.weights_ = gm3_weights
loaded_gmm.means_ = gm3_means
loaded_gmm.covariances_ = gm3_cov
</code>```

Has the disadvantage that the emerging model might be to complex as components with same or similar means are not combined.

Sample 1000 (or a large number) * number_of_input_values per Gaussian model and fit the new model to the sampled data.

```<code>lst_gm3=[]
len_1=int(1000*len(data_1))
for i in range(len_1):
     lst_gm3.append(gm1.sample())
#get_best_amount_Gaussians(lst_gm3)
gm3=GaussianMixture(n_components=5)
gm3.fit(lst_gm3)

</code>```

...

Is computational demanding.

Is there another way to do so?

Thanks a lot in advance!

Title: combine gaussian mixture models

Body:
I'd like to combine gaussian mixture models (GMMs) without using the underlying input values for the models (because I don't want to save all the values).

I had two ideas:

Get weights, means and covariances from both GMMs, combine them (and weight the weights according to the number of input data) and build the combined model based on these with the number of components as the sum of the number of components of the individual models.

Pseudo example for 2 GMMs:

data_1=[1,2,1,3,1,2,5,2,1,2,7,6]
data_2=[5,4,6,5,6,5,8,5,6,7,12,12,13,15,20]

data_1 = np.expand_dims(data_1, 1)
data_2 = np.expand_dims(data_2, 1)

n_comp_1=get_best_amount_Gaussians(data_1)
n_comp_2=get_best_amount_Gaussians(data_2)

gm1=GaussianMixture(n_components=n_comp_1)
gm1.fit(data_1)
gm2=GaussianMixture(n_components=n_comp_2)
gm2.fit(data_2)

n_comp_3=n_comp_1+n_comp_2

#get weights, means and covs

#weight the weights according to the number of input values:
gm1_weights=gm1_weights*len(data_1)
gm2_weights=gm2_weights*len(data_2)
gm3_weights=np.concatenate((gm1_weights,gm2_weights),axis=0)

#build gm3 based on these values:
GaussianMixture(n_components=n_comp_3)

loaded_gmm.weights_ = gm3_weights
loaded_gmm.means_ = gm3_means
loaded_gmm.covariances_ = gm3_cov

Has the disadvantage that the emerging model might be to complex as components with same or similar means are not combined.

Sample 1000 (or a large number) * number_of_input_values per Gaussian model and fit the new model to the sampled data.

lst_gm3=[]
len_1=int(1000*len(data_1))
for i in range(len_1):
     lst_gm3.append(gm1.sample())
#get_best_amount_Gaussians(lst_gm3)
gm3=GaussianMixture(n_components=5)
gm3.fit(lst_gm3)

...

Is computational demanding.

Is there another way to do so?

Thanks a lot in advance!


问:
Pandaepl errors
I want to run Morrismaze game on Python. It needs Pandaepl. I imported Pandaepl, but I always face these errors and can't find a solution.

Errors:

```<code>File "morris_STmemory_itemANDspace_v6.py", line 1, in \<module\>
from pandaepl.common import \*
File "C:\\Python27\\lib\\site-packages\\pandaepl\\common.py", line 78, in \<module\>
base.cam = Camera.getDefaultCamera().retrNodePath()
File "C:\\Python27\\lib\\site-packages\\pandaepl\\Camera.py", line 105, in getDefaultCamera
Camera.defaultInstance = Camera("PandaEPL_defaultCamera", 0)
File "C:\\Python27\\lib\\site-packages\\pandaepl\\Camera.py", line 65, in \_\_ init \_\_
VrObject.\_\_ init_\_ (self, identifier, NodePath(camera))
File "C:\\Python27\\lib\\site-packages\\pandaepl\\VrObject.py", line 86, in \_\_ init \_\_
for np in self.nodePath.findAllMatches("\*\*").asList():
AttributeError: 'panda3d.core.NodePathCollection' object has no attribute 'asList'
</code>```

Can someone help me to find a solution?

Title: Pandaepl errors

Body:
I want to run Morrismaze game on Python. It needs Pandaepl. I imported Pandaepl, but I always face these errors and can't find a solution.

Errors:

File "morris_STmemory_itemANDspace_v6.py", line 1, in \<module\>
from pandaepl.common import \*
File "C:\\Python27\\lib\\site-packages\\pandaepl\\common.py", line 78, in \<module\>
base.cam = Camera.getDefaultCamera().retrNodePath()
File "C:\\Python27\\lib\\site-packages\\pandaepl\\Camera.py", line 105, in getDefaultCamera
Camera.defaultInstance = Camera("PandaEPL_defaultCamera", 0)
File "C:\\Python27\\lib\\site-packages\\pandaepl\\Camera.py", line 65, in \_\_ init \_\_
VrObject.\_\_ init_\_ (self, identifier, NodePath(camera))
File "C:\\Python27\\lib\\site-packages\\pandaepl\\VrObject.py", line 86, in \_\_ init \_\_
for np in self.nodePath.findAllMatches("\*\*").asList():
AttributeError: 'panda3d.core.NodePathCollection' object has no attribute 'asList'

Can someone help me to find a solution?


问:
Cannot get Docker to use pull-through cache
I am trying to cache images locally in a Docker registry using a pull through cache as described here: https://docs.docker.com/registry/recipes/mirror/. But when I do, Docker seems to ignore the pass-through cache and is instead pulling images directly from Docker Hub.

I have a Docker Compose file that I am using to run the registry:

```<code>version: '3.9'

services:
  registry:
    restart: always
    image: registry:2
    ports:
      - 5000:5000
    volumes:
      - ~/.docker/registry:/var/lib/registry
      - ./registry-config.yml:/etc/docker/registry/config.yml
</code>```

And I have configured Docker to use the registry via the --registry-mirror option, which I have confirmed is taking effect by checking the output of docker info:

```<code>$ docker info
...
 Registry Mirrors:
  https://localhost:5000/
...
</code>```

But when I try to pull an image, I see no activity in the registry's logs, as if Docker is ignoring the mirror option and just going straight to Docker Hub.

I have also confirmed the registry is working by pulling alpine:latest from Docker Hub, tagging it as localhost:5000/alpine:latest and pushing it to the registry, then pulling it back out again. Both of which work fine.

This is all being done on a Linux VM running Ubuntu.

Can someone please help me understand what I am doing wrong. and how I am supposed to get Docker to pull all images through the pull-through cache?

Thanks in advance for your help.

Body:
I am trying to cache images locally in a Docker registry using a pull through cache as described here: https://docs.docker.com/registry/recipes/mirror/. But when I do, Docker seems to ignore the pass-through cache and is instead pulling images directly from Docker Hub.

I have a Docker Compose file that I am using to run the registry:

version: '3.9'

services:
  registry:
    restart: always
    image: registry:2
    ports:
      - 5000:5000
    volumes:
      - ~/.docker/registry:/var/lib/registry
      - ./registry-config.yml:/etc/docker/registry/config.yml

And I have configured Docker to use the registry via the --registry-mirror option, which I have confirmed is taking effect by checking the output of docker info:

$ docker info
...
 Registry Mirrors:
  https://localhost:5000/
...

But when I try to pull an image, I see no activity in the registry's logs, as if Docker is ignoring the mirror option and just going straight to Docker Hub.

I have also confirmed the registry is working by pulling alpine:latest from Docker Hub, tagging it as localhost:5000/alpine:latest and pushing it to the registry, then pulling it back out again. Both of which work fine.

This is all being done on a Linux VM running Ubuntu.

Can someone please help me understand what I am doing wrong. and how I am supposed to get Docker to pull all images through the pull-through cache?

Thanks in advance for your help.


问:
Can I combine webbrowser and pyautogui on VSCode? I can access URLs on Chrome and I'd like to open a new tab, but pyautogui accesses VSCode hotkeys
I feel like it's an easy fix, but I haven't been able to figure it out via trial and error and no luck on here, so... it goes:

import webbrowser
import pyautogui

url = 'my link here'

chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s'

webbrowser.get(chrome_path).open(url)
pyautogui.hotkey('ctrl','t')
```

I can get to the link, but the next line opens a search box on the editor itself. What am I getting wrong? I suppose the pyautogui will use the hotkeys on the current screen, right? How do I make it so that it runs on the browser window I just opened?

I tried making the webbrowser.open(url) a variable and then running pyautogui on it. Didn't give me a new tab on chrome, but also didn't open the search bar on VSCode, so that may be something.

Body:
I feel like it's an easy fix, but I haven't been able to figure it out via trial and error and no luck on here, so... it goes:

import webbrowser
import pyautogui

url = 'my link here'

chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s'

webbrowser.get(chrome_path).open(url)
pyautogui.hotkey('ctrl','t')

I can get to the link, but the next line opens a search box on the editor itself. What am I getting wrong? I suppose the pyautogui will use the hotkeys on the current screen, right? How do I make it so that it runs on the browser window I just opened?

I tried making the webbrowser.open(url) a variable and then running pyautogui on it. Didn't give me a new tab on chrome, but also didn't open the search bar on VSCode, so that may be something.


问:
Pgsync synchronisation is not made with new data
I want to synchronize 3 tables from a postgresql database to a self hosted elasticsearch and to do so, I use PGSync.

To build this stack, I followed this tutorial.

When I start the docker containers everything works well (execpt some errors in pgsync but its normal, the tables don't exist yet), after that, I restore my database from a dump (each tables has 30 000, 9 000 000 and 13 000 000 lines approximately). After the dump pgsync detects the new lines in the database and sync them in elasticsearch.

My problem is that after that first synchronisation, PGSync detects new lines:

```<code>Polling db cardpricetrackerprod: 61 item(s)
Polling db cardpricetrackerprod: 61 item(s)
</code>```

but the synchronisation isn't made.

Here is what my schema looks like:

```<code>[
  {
    "database": "mydb",
    "index": "elastic-index-first-table",
    "nodes": {
      "table": "first_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  },
  {
    "database": "mydb",
    "index": "elastic-index-second-table",
    "nodes": {
      "table": "second_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  },
  {
    "database": "mydb",
    "index": "elastic-index-third-table",
    "nodes": {
      "table": "third_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  }
]
</code>```

Have I missed a configuration step?

Body:
I want to synchronize 3 tables from a postgresql database to a self hosted elasticsearch and to do so, I use PGSync.

To build this stack, I followed this tutorial.

When I start the docker containers everything works well (execpt some errors in pgsync but its normal, the tables don't exist yet), after that, I restore my database from a dump (each tables has 30 000, 9 000 000 and 13 000 000 lines approximately). After the dump pgsync detects the new lines in the database and sync them in elasticsearch.

My problem is that after that first synchronisation, PGSync detects new lines:

Polling db cardpricetrackerprod: 61 item(s)
Polling db cardpricetrackerprod: 61 item(s)

but the synchronisation isn't made.

Here is what my schema looks like:

[
  {
    "database": "mydb",
    "index": "elastic-index-first-table",
    "nodes": {
      "table": "first_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  },
  {
    "database": "mydb",
    "index": "elastic-index-second-table",
    "nodes": {
      "table": "second_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  },
  {
    "database": "mydb",
    "index": "elastic-index-third-table",
    "nodes": {
      "table": "third_table",
      "schema": "public",
      "columns": [
        "id",
        ...
      ]
    }
  }
]

Have I missed a configuration step?


问:
C++ Linux string.h invalid read reported in valgrind
The Linux program below builds a path by adding some strings to a filesystem path:

#include <filesystem>
int main(int, char**) {

    //
    std::cout << "Application STARTING\n";

    //
    fs::path path;

    // Add to path
    path /= "/media";
    path /= "aaa";
    path /= "bbb";
    // path /= "ccc";

    //
    std::cout << path.c_str() << std::endl;

    //
    std::cout << "Application STOPPED\n";

}
```
<p>If I run this file in valgrind, this is the output:</p>
<pre class="lang-none prettyprint-override"><code>Application STARTING
/media/aaa/bbb
Application STOPPED
</code>```

If I uncomment the line that adds "ccc" to the path, compile and run again in valgrind, I get this:

Application STARTING
==2231== Invalid read of size 1
==2231==    at 0x4860214: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==2231==  Address 0x4d25c17 is 0 bytes after a block of size 31 alloc'd
==2231==    at 0x4848744: operator new(unsigned int) (vg_replace_malloc.c:282)
==2231==    by 0x4A79CBB: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned int, unsigned int, char const*, unsigned int) (in /usr/lib/arm-linux-gnueabihf/libstdc++.so.6.0.28)
==2231==
/media/aaa/bbb/ccc
Application STOPPED
```
<p>I am compiling with these settings:</p>
<pre class="lang-none prettyprint-override"><code>/usr/bin/arm-linux-gnueabihf-g++  -I/usr/include/alsa  -pthread -Wall -Wextra -pedantic -g -DTMTP_DEBUG -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp
</code>```

Is this a valgrind error?  Am I using the fs::path correctly?

_ UPDATE _

I have reduced to the minimum compiler settings:

```<code>/usr/bin/arm-linux-gnueabihf-g++   -g -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp
</code>```

I am compiling in C++17 because this allows me to use the non-experimental version of filesystem.

Bad memory read is still reported.

_ ANOTHER UPDATE _

I can create the invalid read error without using filesystem.  The code below also reports an invalid read.  There are two lines marked in the code, commenting out either removes the invalid read.

```<code>#include <iostream>
#include <string.h>

class CPath
{

    public:
            inline const char* c_str() const { return m_strPath.c_str(); }
            inline void operator/=(const char* psz) { append(psz); }

    public:
        void append(const char* psz)
        {

            //
            m_strPath += '/'; // <--- REMOVE TO PREVENT INVALID READ
            m_strPath.append(psz);

        }

    private:
        std::string m_strPath;

};

int main(int, char**) {

    //
    std::cout << "Application STARTING\n";

    //
    CPath path;
    path /= "media";
    path /= "aaa";
    path /= "bbb";
    path /= "ccc"; // <--- REMOVE TO PREVENT INVALID READ

    //
    std::cout << path.c_str() << std::endl;

    //
    std::cout << "Application STOPPED\n";

}
</code>```

Body:
The Linux program below builds a path by adding some strings to a filesystem path:

#include <filesystem>
int main(int, char**) {

    //
    std::cout << "Application STARTING\n";

    //
    fs::path path;

    // Add to path
    path /= "/media";
    path /= "aaa";
    path /= "bbb";
    // path /= "ccc";

    //
    std::cout << path.c_str() << std::endl;

    //
    std::cout << "Application STOPPED\n";

}

If I run this file in valgrind, this is the output:

Application STARTING
/media/aaa/bbb
Application STOPPED

If I uncomment the line that adds "ccc" to the path, compile and run again in valgrind, I get this:

Application STARTING
==2231== Invalid read of size 1
==2231==    at 0x4860214: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==2231==  Address 0x4d25c17 is 0 bytes after a block of size 31 alloc'd
==2231==    at 0x4848744: operator new(unsigned int) (vg_replace_malloc.c:282)
==2231==    by 0x4A79CBB: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned int, unsigned int, char const*, unsigned int) (in /usr/lib/arm-linux-gnueabihf/libstdc++.so.6.0.28)
==2231==
/media/aaa/bbb/ccc
Application STOPPED

I am compiling with these settings:

/usr/bin/arm-linux-gnueabihf-g++  -I/usr/include/alsa  -pthread -Wall -Wextra -pedantic -g -DTMTP_DEBUG -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp

Is this a valgrind error?  Am I using the fs::path correctly?

_ UPDATE _

I have reduced to the minimum compiler settings:

/usr/bin/arm-linux-gnueabihf-g++   -g -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp

I am compiling in C++17 because this allows me to use the non-experimental version of filesystem.

Bad memory read is still reported.

_ ANOTHER UPDATE _

I can create the invalid read error without using filesystem.  The code below also reports an invalid read.  There are two lines marked in the code, commenting out either removes the invalid read.

#include <iostream>
#include <string.h>

class CPath
{

    public:
            inline const char* c_str() const { return m_strPath.c_str(); }
            inline void operator/=(const char* psz) { append(psz); }

    public:
        void append(const char* psz)
        {

            //
            m_strPath += '/'; // <--- REMOVE TO PREVENT INVALID READ
            m_strPath.append(psz);

        }

    private:
        std::string m_strPath;

};

int main(int, char**) {

    //
    std::cout << "Application STARTING\n";

    //
    CPath path;
    path /= "media";
    path /= "aaa";
    path /= "bbb";
    path /= "ccc"; // <--- REMOVE TO PREVENT INVALID READ

    //
    std::cout << path.c_str() << std::endl;

    //
    std::cout << "Application STOPPED\n";

}


问:
TensorFlow incompatible function arguments in making Elbo
Pardon me for being lazy about this, but I'm not getting the answer anywhere.
I'm trying to replicate the exercise here in my own computer: https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Structural_Time_Series_Modeling_Case_Studies_Atmospheric_CO2_and_Electricity_Demand.ipynb

However, I'm getting stuck at this part:

```<code># Build and optimize the variational loss function.
elbo_loss_curve = tfp.vi.fit_surrogate_posterior(
    target_log_prob_fn=co2_model.joint_distribution(
        observed_time_series=co2_by_month_training_data).log_prob,
    surrogate_posterior=variational_posteriors,
    optimizer=tf.optimizers.Adam(learning_rate=0.1),
    num_steps=num_variational_steps,
    jit_compile=True)

plt.plot(elbo_loss_curve)
plt.show()
</code>```

I get:

```<code>TypeError: TF_TryEvaluateConstant_wrapper(): incompatible function arguments. The following argument types are supported:
    1. (arg0: tensorflow.python.client._pywrap_tf_session.TF_Graph, arg1: tensorflow.python.client._pywrap_tf_session.TF_Output) -> object

Invoked with: <tensorflow.python.framework.c_api_util.ScopedTFGraph object at 0x0000024EDCF90C70>, <tensorflow.python.client._pywrap_tf_session.TF_Output object at 0x0000024EDD26DBB0>
</code>```

Anyone knows what the cause is? I get that there's a problem with my input but i'm looking for a fix.

Body:
Pardon me for being lazy about this, but I'm not getting the answer anywhere.
I'm trying to replicate the exercise here in my own computer: https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Structural_Time_Series_Modeling_Case_Studies_Atmospheric_CO2_and_Electricity_Demand.ipynb

However, I'm getting stuck at this part:

# Build and optimize the variational loss function.
elbo_loss_curve = tfp.vi.fit_surrogate_posterior(
    target_log_prob_fn=co2_model.joint_distribution(
        observed_time_series=co2_by_month_training_data).log_prob,
    surrogate_posterior=variational_posteriors,
    optimizer=tf.optimizers.Adam(learning_rate=0.1),
    num_steps=num_variational_steps,
    jit_compile=True)

plt.plot(elbo_loss_curve)
plt.show()

I get:

TypeError: TF_TryEvaluateConstant_wrapper(): incompatible function arguments. The following argument types are supported:
    1. (arg0: tensorflow.python.client._pywrap_tf_session.TF_Graph, arg1: tensorflow.python.client._pywrap_tf_session.TF_Output) -> object

Invoked with: <tensorflow.python.framework.c_api_util.ScopedTFGraph object at 0x0000024EDCF90C70>, <tensorflow.python.client._pywrap_tf_session.TF_Output object at 0x0000024EDD26DBB0>

Anyone knows what the cause is? I get that there's a problem with my input but i'm looking for a fix.


问:
Why X insert intention cause deadlock when using INSERT IGNORE to insert duplicate data(MySQL 8.0)?
To simulate the deadlock:

(0) MySQL 8.0.28, the isolation level is Repeatable Read

(1) Create a table with a unique key and test data:

```<code>CREATE TABLE `test_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `column_1` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_column_1` (`column_1`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```
```<code>INSERT INTO `test_table`
(`column_1`)
VALUES
('session_1_a'),
('session_1_b'),
('session_2_a'),
('session_2_b'),
('session_3_a'),
('session_3_b');
</code>```

(2) Insert duplicate data in Session 1:

```<code>BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_1_a'),
('session_1_b');
</code>```

(3) Insert duplicate data in Session 2:

```<code>BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_2_a'),
('session_2_b');
</code>```

(4) Insert duplicate data in Session 3:

```<code>BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_3_a'),
('session_3_b');
</code>```

(5) Commit the transaction in Session 1, then Session 3 will throw deadlock error:

```<code>COMMIT;
</code>```

Use SHOW ENGINE INNODB STATUS to check the deadlock details, it says both session 2 and 3 wait for the X insert intention lock:

```<code>------------------------
LATEST DETECTED DEADLOCK
------------------------
2023-01-11 00:04:08 140271878661888
*** (1) TRANSACTION:
TRANSACTION 136437, ACTIVE 5 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 6 lock struct(s), heap size 1128, 4 row lock(s)
MySQL thread id 77, OS thread handle 140271176066816, query id 5996 172.21.0.1 root update
INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_3_a'),
('session_3_b')

*** (1) HOLDS THE LOCK(S):
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136437 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136437 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) TRANSACTION:
TRANSACTION 136436, ACTIVE 9 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 7 lock struct(s), heap size 1128, 4 row lock(s)
MySQL thread id 68, OS thread handle 140271178176256, query id 5993 172.21.0.1 root update
INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_2_a'),
('session_2_b')

*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136436 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136436 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** WE ROLL BACK TRANSACTION (1)
</code>```

Why Session 2 and Session 3 have deadlock in this situation?

PS. If the insert unduplicated data, deadlock won't happen.
If change the transaction level to Read Committed from Repeatable Read, then insert duplicated data again, there's no deadlock.

Body:
To simulate the deadlock:

(0) MySQL 8.0.28, the isolation level is Repeatable Read

(1) Create a table with a unique key and test data:

CREATE TABLE `test_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `column_1` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_column_1` (`column_1`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `test_table`
(`column_1`)
VALUES
('session_1_a'),
('session_1_b'),
('session_2_a'),
('session_2_b'),
('session_3_a'),
('session_3_b');

(2) Insert duplicate data in Session 1:

BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_1_a'),
('session_1_b');

(3) Insert duplicate data in Session 2:

BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_2_a'),
('session_2_b');

(4) Insert duplicate data in Session 3:

BEGIN;

INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_3_a'),
('session_3_b');

(5) Commit the transaction in Session 1, then Session 3 will throw deadlock error:

COMMIT;

Use SHOW ENGINE INNODB STATUS to check the deadlock details, it says both session 2 and 3 wait for the X insert intention lock:

------------------------
LATEST DETECTED DEADLOCK
------------------------
2023-01-11 00:04:08 140271878661888
*** (1) TRANSACTION:
TRANSACTION 136437, ACTIVE 5 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 6 lock struct(s), heap size 1128, 4 row lock(s)
MySQL thread id 77, OS thread handle 140271176066816, query id 5996 172.21.0.1 root update
INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_3_a'),
('session_3_b')

*** (1) HOLDS THE LOCK(S):
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136437 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136437 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) TRANSACTION:
TRANSACTION 136436, ACTIVE 9 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 7 lock struct(s), heap size 1128, 4 row lock(s)
MySQL thread id 68, OS thread handle 140271178176256, query id 5993 172.21.0.1 root update
INSERT IGNORE `test_table`
(`column_1`)
VALUES
('session_2_a'),
('session_2_b')

*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136436 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 7852 page no 4 n bits 80 index PRIMARY of table `stock`.`test_table` trx id 136436 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** WE ROLL BACK TRANSACTION (1)

Why Session 2 and Session 3 have deadlock in this situation?

PS. If the insert unduplicated data, deadlock won't happen.
If change the transaction level to Read Committed from Repeatable Read, then insert duplicated data again, there's no deadlock.


问:
"String indices must be integers" error in pandas & yfinance - Python

Here is my code that I am using:

```<code>import warnings
import datetime
import numpy as np
import pandas as pd
import pandas_datareader.data as pdr
import matplotlib.pyplot as plt, mpld3
import matplotlib.ticker as mtick

date_from = datetime.date(2020, 1, 1)
date_to = datetime.date(2022, 12, 30)
tickerL = 'BTC-USD'
print("Comparing " + tickerL +" to...")
\#tickerL2 = \['AAPL'\]
tickerL2 = input('Now enter your comparison ticker:\\n')
tickerList = \[tickerL, tickerL2\]
print(tickerList)
\#tickerList = \['BTC-USD', 'AMZN', 'AAPL', 'CL=F', '^GSPC', '^DJI', 'GC=F'\]

\#fetch multiple asset data
def getMultiAssetData(tickerList, date_from, date_to):
def getData(ticker):
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
return data

    datas = map(getData, tickerList)
    return pd.concat(datas, keys=tickerList, names=['Ticker', 'Date'])

sort=False
multiData = getMultiAssetData(tickerList, date_from, date_to)
df = multiData.copy()
\#print(df)

df = df.loc\[tickerL, :\]
df.tail()
</code>```

Now I keep getting this error and I don't know how to move forward:

```<code>Traceback (most recent call last):
File "main.py", line 51, in \<module\>
multiData = getMultiAssetData(tickerList, date_from, date_to)
File "main.py", line 45, in getMultiAssetData
datas = list(map(getData, tickerList))
File "main.py", line 42, in getData
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/util/\_decorators.py", line 207, in wrapper
return func(\*args, \*\*kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/data.py", line 370, in DataReader
return YahooDailyReader(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/base.py", line 253, in read
df = self.\_read_one_data(self.url, params=self.\_get_params(self.symbols))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/yahoo/daily.py", line 153, in \_read_one_data
data = j\["context"\]\["dispatcher"\]\["stores"\]\["HistoricalPriceStore"\]
TypeError: string indices must be integers
</code>```

This script worked just fine a couple of months ago but I assume some of the packages got updated and now require different format.

Body:
Here is my code that I am using:

import warnings
import datetime
import numpy as np
import pandas as pd
import pandas_datareader.data as pdr
import matplotlib.pyplot as plt, mpld3
import matplotlib.ticker as mtick

date_from = datetime.date(2020, 1, 1)
date_to = datetime.date(2022, 12, 30)
tickerL = 'BTC-USD'
print("Comparing " + tickerL +" to...")
\#tickerL2 = \['AAPL'\]
tickerL2 = input('Now enter your comparison ticker:\\n')
tickerList = \[tickerL, tickerL2\]
print(tickerList)
\#tickerList = \['BTC-USD', 'AMZN', 'AAPL', 'CL=F', '^GSPC', '^DJI', 'GC=F'\]

\#fetch multiple asset data
def getMultiAssetData(tickerList, date_from, date_to):
def getData(ticker):
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
return data

    datas = map(getData, tickerList)
    return pd.concat(datas, keys=tickerList, names=['Ticker', 'Date'])

sort=False
multiData = getMultiAssetData(tickerList, date_from, date_to)
df = multiData.copy()
\#print(df)

df = df.loc\[tickerL, :\]
df.tail()

Now I keep getting this error and I don't know how to move forward:

Traceback (most recent call last):
File "main.py", line 51, in \<module\>
multiData = getMultiAssetData(tickerList, date_from, date_to)
File "main.py", line 45, in getMultiAssetData
datas = list(map(getData, tickerList))
File "main.py", line 42, in getData
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/util/\_decorators.py", line 207, in wrapper
return func(\*args, \*\*kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/data.py", line 370, in DataReader
return YahooDailyReader(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/base.py", line 253, in read
df = self.\_read_one_data(self.url, params=self.\_get_params(self.symbols))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/yahoo/daily.py", line 153, in \_read_one_data
data = j\["context"\]\["dispatcher"\]\["stores"\]\["HistoricalPriceStore"\]
TypeError: string indices must be integers

This script worked just fine a couple of months ago but I assume some of the packages got updated and now require different format.


问:
AntD css-in-js removing the original props of AntD component
I am trying to customize AntD using CSS-in-js. I am able to customize the component very successfully but run into an issue during instantiation. The props for the original AntD component are no longer available. This is a big issue. Does anyone have any workarounds to maintain the full props of the original AntD component?

I have used styled-components to style the AntD button, but am not able to retain the props.

const StyledButtonPrimary = styled(Button)`
  .ant-click-animating-node {
    display: none;
  }
  && {
    border-width: 1px;
    border-style: solid;
    border-color: ${red500};
    margin: 0;
    background-color: ${red500};
    border-radius: 4px;
    color: ${white};
    font-family: inherit;
    font-size: 14px;
    font-style: normal;
    font-weight: 600;
    line-height: 20px;
    text-align: center;
    transition: background-color 0.2s, color 0.2s, border-color 0.2s, box-shadow 0.2s;
    white-space: nowrap;
    &:hover {
      border-color: ${red700};
      background-color: ${red700};
      color: ${white};
    }
    &:active {
      border-color: ${red700};
      background-color: ${red500};
      box-shadow: inset 0 0 0 1px ${red700};
      animation-duration: 0s;
      animation: none;
      animation-fill-mode: none;
    }
  }
`;
```
<p>The code below is the styled button, but I can no longer access any of the original AntD Button props.</p>
<pre class="lang-jsx prettyprint-override"><code><StyledButtonPrimary>
  Primary Button
</StyledButtonPrimary>
</code>```

Body:
I am trying to customize AntD using CSS-in-js. I am able to customize the component very successfully but run into an issue during instantiation. The props for the original AntD component are no longer available. This is a big issue. Does anyone have any workarounds to maintain the full props of the original AntD component?

I have used styled-components to style the AntD button, but am not able to retain the props.

const StyledButtonPrimary = styled(Button)`
  .ant-click-animating-node {
    display: none;
  }
  && {
    border-width: 1px;
    border-style: solid;
    border-color: ${red500};
    margin: 0;
    background-color: ${red500};
    border-radius: 4px;
    color: ${white};
    font-family: inherit;
    font-size: 14px;
    font-style: normal;
    font-weight: 600;
    line-height: 20px;
    text-align: center;
    transition: background-color 0.2s, color 0.2s, border-color 0.2s, box-shadow 0.2s;
    white-space: nowrap;
    &:hover {
      border-color: ${red700};
      background-color: ${red700};
      color: ${white};
    }
    &:active {
      border-color: ${red700};
      background-color: ${red500};
      box-shadow: inset 0 0 0 1px ${red700};
      animation-duration: 0s;
      animation: none;
      animation-fill-mode: none;
    }
  }
`;

The code below is the styled button, but I can no longer access any of the original AntD Button props.


问:
How to average multiple Vlookup values together within one formula and ignore 0s?
I have an excel spreadsheet that has a tab for each day of the week and tab for a weekly summary. It is used to measure the productivity of our employees for a certain task. One of the values is an average amount of time they spend performing that task, and the rest of the values are just figures associated to how many they completed or how many hours they spent, etc. My issue is that, given our employees do not necessarily perform these tasks every day and that we consistently get new employees, we have to use vlookup formulas to pull the data from the daily to the weekly, because they won't be in the same place each day or week. So I created a formula that I had thought was going to work, but an issue arose when implementing the formula today.

See the formulas I tried below. The goal of these formulas was to add each agent's value from each day, Mon-Sun, average it together, and return an average handle time for the week.

I tried this one, but it appeared to return the sum of the values, instead of the average. For example, the employee had 6:22 on Wed, 6:58 on Fri, and 6:44 on Sat, 0s for the rest of the week. The formula below returned 20:04 as the value, which is the aforementioned values added together.

```<code>=IFERROR(AVERAGE(IFERROR(VLOOKUP(B82,Monday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Tuesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Wednesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Thursday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Friday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Saturday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Sunday!B:W,12,FALSE),0)),0)
</code>```

I also tried a different approach. The issue with this one is that there is no way that I could find to avoid the 0s factoring in. For the same values mentioned in the previous, this formula returned 2:52 as the value. Which not accurate because it is dividing by 7 days and there is no data on 4 of the 7 days.

```<code>=IFERROR(SUM(IFERROR(VLOOKUP(B82,Monday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Tuesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Wednesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Thursday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Friday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Saturday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Sunday!B:W,12,FALSE),0)),0)/7
</code>```

I also tried Averageif so I could add in "<>0" and have it ignore the 0s, but it appears it only works with a cell range, and doesn't work with vlookup values.

So in summary, I am looking for a way to average together these 7 vlookup values and have it ignore 0s or blanks. Apologies if there is a simple solution as I am still learning more of the intermediate and advanced excel techniques. Thank you in advance for any help!

Body:
I have an excel spreadsheet that has a tab for each day of the week and tab for a weekly summary. It is used to measure the productivity of our employees for a certain task. One of the values is an average amount of time they spend performing that task, and the rest of the values are just figures associated to how many they completed or how many hours they spent, etc. My issue is that, given our employees do not necessarily perform these tasks every day and that we consistently get new employees, we have to use vlookup formulas to pull the data from the daily to the weekly, because they won't be in the same place each day or week. So I created a formula that I had thought was going to work, but an issue arose when implementing the formula today.

See the formulas I tried below. The goal of these formulas was to add each agent's value from each day, Mon-Sun, average it together, and return an average handle time for the week.

I tried this one, but it appeared to return the sum of the values, instead of the average. For example, the employee had 6:22 on Wed, 6:58 on Fri, and 6:44 on Sat, 0s for the rest of the week. The formula below returned 20:04 as the value, which is the aforementioned values added together.

=IFERROR(AVERAGE(IFERROR(VLOOKUP(B82,Monday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Tuesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Wednesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Thursday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Friday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Saturday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Sunday!B:W,12,FALSE),0)),0)

I also tried a different approach. The issue with this one is that there is no way that I could find to avoid the 0s factoring in. For the same values mentioned in the previous, this formula returned 2:52 as the value. Which not accurate because it is dividing by 7 days and there is no data on 4 of the 7 days.

=IFERROR(SUM(IFERROR(VLOOKUP(B82,Monday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Tuesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Wednesday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Thursday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Friday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Saturday!B:W,12,FALSE),0)+IFERROR(VLOOKUP(B82,Sunday!B:W,12,FALSE),0)),0)/7

I also tried Averageif so I could add in "<>0" and have it ignore the 0s, but it appears it only works with a cell range, and doesn't work with vlookup values.

So in summary, I am looking for a way to average together these 7 vlookup values and have it ignore 0s or blanks. Apologies if there is a simple solution as I am still learning more of the intermediate and advanced excel techniques. Thank you in advance for any help!