问:
Is there any methods using HuggingFace Trainer API with torch.multiprocessing.spawn?
Sorry for my English skill and This is my first question on stackoverflow.

In my case, I tried to prefix-tuning on GPTNeoXForCausalLM (polyglot). And i using 2 GPUs (Tesla V100 32GB x 2).

This LM is over 16GB. When dataset is assigned on single GPU and then, it has problem with lack of memory. So i try DDP (Distributed Data Parallism) to scatter dataset on each GPUs.

First, i spawn multiple processes through torch.multiprocessing.spawn.
Second, for each process, there is transformers.Trainer with transformers.TrainingArguments.

And i want to use transformers.Trainer. (not torch.dataloader)

Here, i have some questions.

Is dataset scatter to each GPUs automatically?

Is it correct way that give local_rank parameter for transformers.TraingArguments?

```<code>import os
import torch
from args import Args
from preprocess import get_dataset
from prefix_gptneox_model import PrefixGPTNeoXLMHeadModel
from transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling

def get_trainer(model, ds_train, ds_valid, rank):
    # Train Params
    training_args = TrainingArguments(
        run_name = "prefix_gptneox_chatbot",

        ## Steps/Epochs
        num_train_epochs = 3,

        ## LR
        learning_rate = 5e-5,

        ## Batch
        per_device_train_batch_size = 2,
        per_device_eval_batch_size = 2,
        gradient_accumulation_steps = 1,

        ## ETC
        # label_smoothing_factor = config["label_smoothing_factor"],

        # Checkpointing, Saving
        output_dir = os.path.join("weights", "checkpoints"),
        save_strategy = "steps", # steps, epoch
        save_steps = 80,
        save_total_limit = 1,
        load_best_model_at_end = True,
        overwrite_output_dir=True,

        # Evaluating
        evaluation_strategy = "steps",
        metric_for_best_model = "eval_loss",

        # Logging
        logging_dir = "weights",
        logging_steps = 80,
        disable_tqdm = False,
        report_to = "none",
        # predict_with_generate = True,

        # System
        # seed = random_seed,
        fp16 = False,
        bf16 = False,
        local_rank=rank
    )

    return Trainer(
        model=model,
        args=training_args,
        data_collator=DataCollatorForLanguageModeling(model.tokenizer, mlm=False),
        train_dataset=ds_train,
        eval_dataset=ds_valid
    )

def train_ddp(rank, world_size, ds_train, ds_valid):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'
    os.environ["RANK"] = str(rank)
    os.environ["WORLD_SIZE"] = str(world_size)

    args = Args()
    model = PrefixGPTNeoXLMHeadModel(args)

    trainer = get_trainer(
        model=model,
        ds_train=ds_train,
        ds_valid=ds_valid,
        rank=rank
    )
    trainer.train()

if __name__ == "__main__":
    ds_train, ds_valid = get_dataset()
    world_size = 2
    torch.multiprocessing.spawn(
        train_ddp,
        args=(world_size, ds_train, ds_valid),
        nprocs=world_size,
        join=True
    )
</code>```

Thanks for read this question. T.T

I want to use DDP with HF Trainer API. (+ i want to be sure of this way is correct.)

Body:
Sorry for my English skill and This is my first question on stackoverflow.

In my case, I tried to prefix-tuning on GPTNeoXForCausalLM (polyglot). And i using 2 GPUs (Tesla V100 32GB x 2).

This LM is over 16GB. When dataset is assigned on single GPU and then, it has problem with lack of memory. So i try DDP (Distributed Data Parallism) to scatter dataset on each GPUs.

First, i spawn multiple processes through torch.multiprocessing.spawn.
Second, for each process, there is transformers.Trainer with transformers.TrainingArguments.

And i want to use transformers.Trainer. (not torch.dataloader)

Here, i have some questions.

Is dataset scatter to each GPUs automatically?

Is it correct way that give local_rank parameter for transformers.TraingArguments?

import os
import torch
from args import Args
from preprocess import get_dataset
from prefix_gptneox_model import PrefixGPTNeoXLMHeadModel
from transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling

def get_trainer(model, ds_train, ds_valid, rank):
    # Train Params
    training_args = TrainingArguments(
        run_name = "prefix_gptneox_chatbot",

        ## Steps/Epochs
        num_train_epochs = 3,

        ## LR
        learning_rate = 5e-5,

        ## Batch
        per_device_train_batch_size = 2,
        per_device_eval_batch_size = 2,
        gradient_accumulation_steps = 1,

        ## ETC
        # label_smoothing_factor = config["label_smoothing_factor"],

        # Checkpointing, Saving
        output_dir = os.path.join("weights", "checkpoints"),
        save_strategy = "steps", # steps, epoch
        save_steps = 80,
        save_total_limit = 1,
        load_best_model_at_end = True,
        overwrite_output_dir=True,

        # Evaluating
        evaluation_strategy = "steps",
        metric_for_best_model = "eval_loss",

        # Logging
        logging_dir = "weights",
        logging_steps = 80,
        disable_tqdm = False,
        report_to = "none",
        # predict_with_generate = True,

        # System
        # seed = random_seed,
        fp16 = False,
        bf16 = False,
        local_rank=rank
    )

    return Trainer(
        model=model,
        args=training_args,
        data_collator=DataCollatorForLanguageModeling(model.tokenizer, mlm=False),
        train_dataset=ds_train,
        eval_dataset=ds_valid
    )

def train_ddp(rank, world_size, ds_train, ds_valid):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'
    os.environ["RANK"] = str(rank)
    os.environ["WORLD_SIZE"] = str(world_size)

    args = Args()
    model = PrefixGPTNeoXLMHeadModel(args)

    trainer = get_trainer(
        model=model,
        ds_train=ds_train,
        ds_valid=ds_valid,
        rank=rank
    )
    trainer.train()

if __name__ == "__main__":
    ds_train, ds_valid = get_dataset()
    world_size = 2
    torch.multiprocessing.spawn(
        train_ddp,
        args=(world_size, ds_train, ds_valid),
        nprocs=world_size,
        join=True
    )

Thanks for read this question. T.T

I want to use DDP with HF Trainer API. (+ i want to be sure of this way is correct.)


来源: stackexchange

问:
Mysql Event schedule daily start at specific time and stop specific time
I wanted to schedule the event to do some task (insert is dummy). The process should run daily at morning 8:00 AM and should be run every 5 min. till 8:00 PM. As per my script it ran for one day but next day it did not trigger.

Looking for the work around on this.
Event is :-

```<code>Drop event if exists test;
CREATE EVENT test
  ON SCHEDULE EVERY 5 MINUTE
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 28800 SECOND )
    ENDS (TIMESTAMP(CURRENT_DATE) + INTERVAL 72000 SECOND )
  DO
     insert into temp (name) values (concat('event_name ', sysdate()));
</code>```

Note:- Global event scheduler is ON

ContentLicense: CC BY-SA 4.0

Body:
I wanted to schedule the event to do some task (insert is dummy). The process should run daily at morning 8:00 AM and should be run every 5 min. till 8:00 PM. As per my script it ran for one day but next day it did not trigger.

Looking for the work around on this.
Event is :-

Drop event if exists test;
CREATE EVENT test
  ON SCHEDULE EVERY 5 MINUTE
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 28800 SECOND )
    ENDS (TIMESTAMP(CURRENT_DATE) + INTERVAL 72000 SECOND )
  DO
     insert into temp (name) values (concat('event_name ', sysdate()));

Note:- Global event scheduler is ON


问:
How to create a pre-signed url to upload files to Google cloud storge?
Using the following dependencies, I can't find a way to generate a url with pre-signature.

```<code> <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-storage</artifactId>
            <version>2.16.0</version>
        </dependency>
</code>```

I looked at the javascript client, but did not find a similar approach in the java client

Body:
Using the following dependencies, I can't find a way to generate a url with pre-signature.

 <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-storage</artifactId>
            <version>2.16.0</version>
        </dependency>

I looked at the javascript client, but did not find a similar approach in the java client


问:
Copy the slides from existing presentation to new presentation - Slides (unknown number) : Integer out of the range, 0 is not valid
This is my first macro in PPT. I have code that can copy selected slides and paste into a new presentation, but I see an error while trying to execute. I was searching old topics but I could not find. Is anyone can help me to fix it?</p>
```<code>Sub copy_slides()

On Error GoTo errhandler

Dim objPresentation As Presentation
Dim i, nr_of_slides As Integer

k = ActivePresentation.Path
'open the target presentation

UsNam = UserForm1.TextBox4.Value

Set objPresentation = Presentations.Open 'there is whole path described

Sleep 1000
For i = 1 To objPresentation.Slides.Count
    objPresentation.Slides.Item(i).Copy
retry:
    Presentations.Item(1).Slides.Paste (i + slide_nr)    'in this line I have Run Time error

Next i

objPresentation.Close
additional_slides = additional_slides + i - 1

Exit Sub

errhandler:
Sleep 1000
GoTo retry

End Sub
</code>```

Body:
This is my first macro in PPT. I have code that can copy selected slides and paste into a new presentation, but I see an error while trying to execute. I was searching old topics but I could not find. Is anyone can help me to fix it?

Sub copy_slides()

On Error GoTo errhandler

Dim objPresentation As Presentation
Dim i, nr_of_slides As Integer

k = ActivePresentation.Path
'open the target presentation

UsNam = UserForm1.TextBox4.Value

Set objPresentation = Presentations.Open 'there is whole path described

Sleep 1000
For i = 1 To objPresentation.Slides.Count
    objPresentation.Slides.Item(i).Copy
retry:
    Presentations.Item(1).Slides.Paste (i + slide_nr)    'in this line I have Run Time error

Next i

objPresentation.Close
additional_slides = additional_slides + i - 1

Exit Sub

errhandler:
Sleep 1000
GoTo retry

End Sub


问:
Spatie MediaLibrary Public Property
I am using Spatie MediaLibrary to upload documents into the database and right now I face an issue. Spatie uses public property $mediaComponentNames where I have to assign the media name. For example:

public $mediaComponentNames = ['myUpload'];

The problem is I want the "myUpload" to be dynamic. So, I dont assign any value for $mediaComponentNames in public property, but assign the value in public function mount() instead. I got null value when try to upload document using Spatie, it does not return expected output which is the filename etc.

Is there any other way, or suggestions. Thank you so much.

I got null, the expected output should be a list of array with all the files upload using Spatie Medialibrary.

There are 3 files related to this problem, I just show the part of the code that I think necessary only. I already check that there is no issue to upload to temporary, just that it does not show the expected output that I need.

ApplicationData.php

<?php

namespace Leave\Concerns;

use Carbon\Carbon;
use Setting\Models\Document;

trait ApplicationData

{
    public $mediaComponentNames;

    public function initMount($code = null, $uuid = null)
    {
        $this->documents = $this->getDocuments($this->leave_type);

        /* Assign the array key(document item id) for the array of images uploaded in checklist document */
        foreach ($this->documents as $doc) {
            foreach ($doc->items->where('is_active', Status::Active()) as $item) {
                /* Get the id of document item */
                $this->mediaComponentNames[] = "document_items_" . $item->id;
            }
        }
    }
}

```
<pre class="lang-php prettyprint-override"><code>Application.php

<?php

namespace Leave\Concerns;

use Spatie\MediaLibraryPro\Http\Livewire\Concerns\WithMedia;
use Setting\Enums\Status as SettingStatus;

trait Application
{
    use WithMedia;
    use ApplicationData;

    abstract public function init();

    public function submit()
    {
        $this->documents = $this->getDocuments($this->leave_type);

        /* Assign the array key(document item id) for the array of images uploaded in checklist document */
        foreach ($this->documents as $doc) {
            foreach ($doc->items->where('is_active', SettingStatus::Active()) as $item) {
                $document_items[] = $this->{ 'document_items_' . $item->id };
            }
        }

        dd($document_items); // it return array of null, it should return array of document uploaded through Spatie MediaLibrary
    }
}
</code>```

create.blade.php

<x-uploaded-media
    :file="$file"
    name="document_items_{{ $item->id }}"
    collection="document_items.{{ $item->id }}"
    rules="mimes:pdf, svg"
    deleteFunctionName="removeFile"
/>
```
<p>The expected output is like below where I only upload 2 file for testing purpose, which is SVG file.The expected output I got it because, I assigned it in the public property like below</p>
<pre class="lang-php prettyprint-override"><code>public $mediaComponentNames = ["document_items_14","document_items_4","document_items_15","document_items_9","document_items_10"];
</code>```

Expected output

But instead, I got this

Current output

Title: Spatie MediaLibrary Public Property

Body:
I am using Spatie MediaLibrary to upload documents into the database and right now I face an issue. Spatie uses public property $mediaComponentNames where I have to assign the media name. For example:

public $mediaComponentNames = ['myUpload'];

The problem is I want the "myUpload" to be dynamic. So, I dont assign any value for $mediaComponentNames in public property, but assign the value in public function mount() instead. I got null value when try to upload document using Spatie, it does not return expected output which is the filename etc.

Is there any other way, or suggestions. Thank you so much.

I got null, the expected output should be a list of array with all the files upload using Spatie Medialibrary.

There are 3 files related to this problem, I just show the part of the code that I think necessary only. I already check that there is no issue to upload to temporary, just that it does not show the expected output that I need.

ApplicationData.php

<?php

namespace Leave\Concerns;

use Carbon\Carbon;
use Setting\Models\Document;

trait ApplicationData

{
    public $mediaComponentNames;

    public function initMount($code = null, $uuid = null)
    {
        $this->documents = $this->getDocuments($this->leave_type);

        /* Assign the array key(document item id) for the array of images uploaded in checklist document */
        foreach ($this->documents as $doc) {
            foreach ($doc->items->where('is_active', Status::Active()) as $item) {
                /* Get the id of document item */
                $this->mediaComponentNames[] = "document_items_" . $item->id;
            }
        }
    }
}

Application.php

<?php

namespace Leave\Concerns;

use Spatie\MediaLibraryPro\Http\Livewire\Concerns\WithMedia;
use Setting\Enums\Status as SettingStatus;

trait Application
{
    use WithMedia;
    use ApplicationData;

    abstract public function init();

    public function submit()
    {
        $this->documents = $this->getDocuments($this->leave_type);

        /* Assign the array key(document item id) for the array of images uploaded in checklist document */
        foreach ($this->documents as $doc) {
            foreach ($doc->items->where('is_active', SettingStatus::Active()) as $item) {
                $document_items[] = $this->{ 'document_items_' . $item->id };
            }
        }

        dd($document_items); // it return array of null, it should return array of document uploaded through Spatie MediaLibrary
    }
}

create.blade.php

<x-uploaded-media
    :file="$file"
    name="document_items_{{ $item->id }}"
    collection="document_items.{{ $item->id }}"
    rules="mimes:pdf, svg"
    deleteFunctionName="removeFile"
/>

The expected output is like below where I only upload 2 file for testing purpose, which is SVG file.The expected output I got it because, I assigned it in the public property like below

public $mediaComponentNames = ["document_items_14","document_items_4","document_items_15","document_items_9","document_items_10"];

Expected output

But instead, I got this

Current output


问:
What is the reason for this behaviour in my flexed div?
I'm currently working on a sign-up page for a website using Vue and Tailwind(I'm not looking for a tailwind based answer specifically, anything is fine).
This is what I currently have

This is the code for the page (I've removed v-model and props for easier read)

```<code><template>
    <div class="h-screen flex items-center justify-center">
        <form class="w-3/5 font-mono" action="">
            <InputFieldText1/>
            <InputFieldText1/>
            <button type="button" @click="toggleShow" class="absolute -translate-y-[3.125rem]  right-0 cursor-help showhide">
                <span v-if="passwordState === 'password'"><ShowIcon class="w-6 h-6"/></span>
                <span v-else><HideIcon class="w-6 h-6"/></span>
            </button>
            <InputFieldText1/>
            <button type="button" @click="toggleShowRepeat" class="absolute -translate-y-[3.125rem]  right-0 cursor-help showhide">
                <span v-if="passwordRepeatState === 'password'"><ShowIcon class="w-6 h-6"/></span>
                <span v-else><HideIcon class="w-6 h-6"/></span>
            </button>
            <button type="submit" class="font-normal text-base float-right btn">Sign-up<NextIcon class="w-4 h-4 inline ml-1 nexticon"/></button>
        </form>
    </div>
</template>
<style scoped>
.nexticon{
    transition: margin-right 250ms;
}
.btn:hover .nexticon{
    margin-right: -0.25rem;
}
</style>
</code>```

And this is the code for InputFieldText1 (Again removed the  functional bit for easier read)

```<code><template>
    <div class="relative w-full border-b-2 border-current mt-5 ml-auto mr-auto mb-5 field">

        <input class="outline-none border-none overflow-hidden m-0 w-full p-1 pl-0 bg-transparent input"
        "/>

        <label class="-z-10 absolute w-full -translate-x-full translate-y-1 text-lg label" :for="inputid"></label>
    </div>
</template>
<style scoped>
.field::after{
    content: "";
    position: relative;
    display: block;
    height: 2px;
    width: 100%;
    background: whitesmoke;
    transform: scaleX(0);
    transform-origin: 0%;
    transition: transform 500ms ease;
    top: 2px;
}
.field:focus-within{
    border-color: transparent;
}
.field:focus-within::after{
    transform: scaleX(1);
}
.label{
    transform-origin: 0%;
    transition: transform 400ms;
}
.field:focus-within .label, .input:not(:placeholder-shown) + .label{
    transform: scale(0.8) translateY(-1.5rem) translateX(-125%);
}
</style>
</code>```

This is working almost perfectly, that is exactly how I want those things to look, but now I want to add a 'Already a user? Login' link below the form.

However, when I try to put it below the form,

```<code><div class="h-screen flex items-center justify-center">
        <form class="w-3/5 font-mono" action="">

        </form>
        <a>Already a user? Login</a>
    </div>
</code>```

This happens.
Understandable because its flexing.

Then I tried to put the whole thing in a div,

```<code><div class="h-screen flex items-center justify-center">
        <div>
        <form class="w-3/5 font-mono" action="">

        </form>
        </div>
    </div>
</code>```

And this happens.

Giving the div width 100%,

```<code><div class="h-screen flex items-center justify-center">
        <div class="w-full">
        <form class="w-3/5 font-mono" action="">

        </form>
        </div>
    </div>
</code>```

Did not work either.

Flex basis 100% on the form and the Link in all combinations did not work either.

Any help on why this happens and how to fix it would be greatly appreciated. I am aware I can use absolute positioning, however I'm trying to see if there's another way because I'll need to put in stuff like "Signup with google" and It'll be a pain to position them all across viewports.

Thank you in advance!

Body:
I'm currently working on a sign-up page for a website using Vue and Tailwind(I'm not looking for a tailwind based answer specifically, anything is fine).
This is what I currently have

This is the code for the page (I've removed v-model and props for easier read)

<template>

        <form class="w-3/5 font-mono" action="">
            <InputFieldText1/>
            <InputFieldText1/>
            <button type="button" @click="toggleShow" class="absolute -translate-y-[3.125rem]  right-0 cursor-help showhide">
                <ShowIcon class="w-6 h-6"/>
                <HideIcon class="w-6 h-6"/>
            </button>
            <InputFieldText1/>
            <button type="button" @click="toggleShowRepeat" class="absolute -translate-y-[3.125rem]  right-0 cursor-help showhide">
                <ShowIcon class="w-6 h-6"/>
                <HideIcon class="w-6 h-6"/>
            </button>
            <button type="submit" class="font-normal text-base float-right btn">Sign-up<NextIcon class="w-4 h-4 inline ml-1 nexticon"/></button>
        </form>

</template>

And this is the code for InputFieldText1 (Again removed the  functional bit for easier read)

<template>

        <input class="outline-none border-none overflow-hidden m-0 w-full p-1 pl-0 bg-transparent input"
        "/>

</template>

This is working almost perfectly, that is exactly how I want those things to look, but now I want to add a 'Already a user? Login' link below the form.

However, when I try to put it below the form,

        <form class="w-3/5 font-mono" action="">

        </form>
        Already a user? Login

This happens.
Understandable because its flexing.

Then I tried to put the whole thing in a div,

        <form class="w-3/5 font-mono" action="">

        </form>

And this happens.

Giving the div width 100%,

        <form class="w-3/5 font-mono" action="">

        </form>

Did not work either.

Flex basis 100% on the form and the Link in all combinations did not work either.

Any help on why this happens and how to fix it would be greatly appreciated. I am aware I can use absolute positioning, however I'm trying to see if there's another way because I'll need to put in stuff like "Signup with google" and It'll be a pain to position them all across viewports.

Thank you in advance!


问:
Scrcpy-GUI v1.4.2 is not opening in windows 8
i have downloaded latest version of Scrcpy (andriod screen mirror and control open source tool)  based tool called Scrcpy-GUI v1.4.2. i am using windows 8.1 and also installed Latest version: "1.8.0_351"  of java. now problem is when i try to open "Scrcpy-GUI.64.Bit.exe" it always shows "This application requires a java runtime environment 1.4.0 19.0.1 pop up.

till now i try:

java runtime work with all other applications even old version of this tool is working on my pc.

i reinstalled java runtime both 32bit and 64bit.
please help me how to fix this error


问:
A dotnet core middleware for rewriting the request using HttpContext.SetEndpoint
I want to rewrite the request path to an action method of a controller though a middleware and I think SetEnpoint function would help in doing that, but I can't find a proper example for it.

I tried to follow this thread: Changing Request Path in .Net Core 3.1 but it didnot work and the request path didnot change


问:
"Number of rows must be a positive integer" error when ploting in Python
I am running code line by line as listed in this page, when I run

```<code>m.plot_posterior_predictive(figsize=(14, 10))
</code>```

python gives error message:

```<code>Traceback (most recent call last):
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-16-916850d95b91>", line 1, in <module>
    m.plot_posterior_predictive(figsize=(14, 10))
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\hddm-0.9.7-py3.7-win-amd64.egg\hddm\models\base.py", line 1487, in plot_posterior_predictive
    kabuki.analyze.plot_posterior_predictive(self, *args, **kwargs)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\kabuki\analyze.py", line 556, in plot_posterior_predictive
    ax = fig.add_subplot(np.ceil(nrows), columns, subj_i+1)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\figure.py", line 772, in add_subplot
    ax = subplot_class_factory(projection_class)(self, *args, **pkw)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\axes\_subplots.py", line 36, in __init__
    self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 597, in _from_subplot_args
    gs = GridSpec._check_gridspec_exists(figure, rows, cols)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 225, in _check_gridspec_exists
    return GridSpec(nrows, ncols, figure=figure)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 387, in __init__
    height_ratios=height_ratios)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 50, in __init__
    f"Number of rows must be a positive integer, not {nrows!r}")
ValueError: Number of rows must be a positive integer, not 5.0
</code>```

I am new to python, and has no idea about this error. Does anyone give any suggestion to run the code and output figures like this?

I am using Python 3.7 in Anaconda3, and the hddm version is 0.9.7.

These are codes I have written so far:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import hddm
data = hddm.load_csv('cavanagh_theta_nn.csv')
m = hddm.HDDM(data)
m.find_starting_values()
m.sample(2000, burn=20)
m.plot_posterior_predictive(figsize=(14, 10))
</code>```

Thank you for the reply, but when I trying to install the kabuki through

```<code>pip install git+https://github.com/hddm-devs/kabuki
</code>```

it output another error:

```<code>(py37) C:\Users\A1>pip install git+https://github.com/hddm-devs/kabuki
Collecting git+https://github.com/hddm-devs/kabuki
  Cloning https://github.com/hddm-devs/kabuki to c:\users\A1\appdata\local\temp\pip-req-build-vkftarxg
  Running command git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg'
  fatal: unable to access 'https://github.com/hddm-devs/kabuki/': Failed to connect to github.com port 443 after 21097 ms: Timed out
  error: subprocess-exited-with-error

  × git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg' did not run successfully.
  │ exit code: 128
  ╰─> See above for output.

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg' did not run successfully.
│ exit code: 128
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

</code>```

Body:
I am running code line by line as listed in this page, when I run

m.plot_posterior_predictive(figsize=(14, 10))

python gives error message:

Traceback (most recent call last):
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-16-916850d95b91>", line 1, in <module>
    m.plot_posterior_predictive(figsize=(14, 10))
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\hddm-0.9.7-py3.7-win-amd64.egg\hddm\models\base.py", line 1487, in plot_posterior_predictive
    kabuki.analyze.plot_posterior_predictive(self, *args, **kwargs)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\kabuki\analyze.py", line 556, in plot_posterior_predictive
    ax = fig.add_subplot(np.ceil(nrows), columns, subj_i+1)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\figure.py", line 772, in add_subplot
    ax = subplot_class_factory(projection_class)(self, *args, **pkw)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\axes\_subplots.py", line 36, in __init__
    self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 597, in _from_subplot_args
    gs = GridSpec._check_gridspec_exists(figure, rows, cols)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 225, in _check_gridspec_exists
    return GridSpec(nrows, ncols, figure=figure)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 387, in __init__
    height_ratios=height_ratios)
  File "C:\Users\A1\anaconda3\envs\py37\lib\site-packages\matplotlib\gridspec.py", line 50, in __init__
    f"Number of rows must be a positive integer, not {nrows!r}")
ValueError: Number of rows must be a positive integer, not 5.0

I am new to python, and has no idea about this error. Does anyone give any suggestion to run the code and output figures like this?

I am using Python 3.7 in Anaconda3, and the hddm version is 0.9.7.

These are codes I have written so far:

import pandas as pd
import matplotlib.pyplot as plt
import hddm
data = hddm.load_csv('cavanagh_theta_nn.csv')
m = hddm.HDDM(data)
m.find_starting_values()
m.sample(2000, burn=20)
m.plot_posterior_predictive(figsize=(14, 10))

Thank you for the reply, but when I trying to install the kabuki through

pip install git+https://github.com/hddm-devs/kabuki

it output another error:

(py37) C:\Users\A1>pip install git+https://github.com/hddm-devs/kabuki
Collecting git+https://github.com/hddm-devs/kabuki
  Cloning https://github.com/hddm-devs/kabuki to c:\users\A1\appdata\local\temp\pip-req-build-vkftarxg
  Running command git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg'
  fatal: unable to access 'https://github.com/hddm-devs/kabuki/': Failed to connect to github.com port 443 after 21097 ms: Timed out
  error: subprocess-exited-with-error

  × git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg' did not run successfully.
  │ exit code: 128
  ╰─> See above for output.

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× git clone --filter=blob:none --quiet https://github.com/hddm-devs/kabuki 'C:\Users\A1\AppData\Local\Temp\pip-req-build-vkftarxg' did not run successfully.
│ exit code: 128
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.


问:
Usage lightbox Woocommerce for standard images and gallery Wordpress
Interested in the possibility of using a lightbox Woocommerce (with zoom and slider) not only inside the store, but also for standard images Wordpress (in posts and pages).

I really like the lightbox Woocommerce, it would be great to use it throughout the site. Are there any ways to do this? Many thanks in advance.


Title: Adding Data sequences as unique data on dataset for regression model

Body:
I want to predict a force plate using plantar pressure. The shape of the force plate data is a 15000x6 array, and the shape of the plantar pressure data is a 15000x89 array. I will use a regression model to predict the force plate data. when collecting data to synchronize the force plate data and plantar pressure, I will do time synchronization between the force plate and plantar pressure app. force plate and plantar pressure data will capture 50 data in 1 seconds.

Force Plate Data:

Data shape : (15000,6)

array([[     4.46733  ,      4.39629  ,    -34.2351   ,  -4077.23     ,
         -6206.81     ,   -874.539    ],
       [     7.65166  ,      2.61174  ,    -49.7356   ,  -4846.76     ,
         -9060.05     ,  -1291.39     ],
       [    11.285    ,     -2.91447  ,    -87.9661   ,  -5412.32     ,
        -16345.2      ,   -213.72     ],
       [    12.7313   ,     -6.48048  ,   -123.094    ,  -5939.48     ,
        -23005.6      ,    443.115    ],
       [    11.6425   ,      0.0259204,   -131.717    ,  -6972.53     ,
        -24651.9      ,  -1112.73     ],
       [    12.3602   ,     10.1988   ,   -139.597    ,  -8544.17     ,
        -26118.8      ,  -3260.79     ],
       [    16.0733   ,     12.1455   ,   -165.01     , -10371.5      ,
        -30873.5      ,  -3643.65     ],
       [    21.1933   ,      8.86926  ,   -210.599    , -12673.2      ,
        -39447.9      ,  -2785.69     ],
       [    24.3619   ,      7.59683  ,   -267.449    , -16170.6      ,
        -50300.9      ,  -2823.35     ]])

Plantar Pressure Data :

Data shape : (15000,89)

array([[0.0, 0.0, 91.0, 100.0, 74.0, 7.0, 0.0, 0.0, 0.0, 0.0, 45.0, 123.0, 126.0, 3.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 95.0, 104.0, 75.0, 33.0, 0.0, 0.0, 0.0, 0.0, 57.0, 117.0, 123.0, 113.0, 66.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 58.0, 67.0, 46.0, 16.0, 0.0, 8.0, 0.0, 15.0, 51.0, 122.0, 122.0, 111.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 25.0, 31.0, 64.0, 82.0, 125.0, 124.0, 114.0, 18.0, 0.0, 0.0, 0.0, 24.0, 56.0, 105.0, 116.0, 124.0, 77.0, 0.0, 0.0, 0.0, 71.0, 61.0, 0.0, 0.0, 3.0, 0.0],
[0.0, 0.0, 91.0, 100.0, 74.0, 7.0, 0.0, 0.0, 0.0, 0.0, 45.0, 123.0, 126.0, 3.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 95.0, 104.0, 75.0, 33.0, 0.0, 0.0, 0.0, 0.0, 57.0, 117.0, 123.0, 113.0, 66.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 62.0, 68.0, 46.0, 12.0, 0.0, 3.0, 0.0, 15.0, 53.0, 124.0, 125.0, 115.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 25.0, 31.0, 64.0, 82.0, 125.0, 124.0, 114.0, 18.0, 0.0, 0.0, 0.0, 24.0, 56.0, 105.0, 116.0, 124.0, 77.0, 0.0, 0.0, 0.0, 71.0, 61.0, 0.0, 0.0, 3.0, 0.0],
[0.0, 0.0, 91.0, 100.0, 68.0, 6.0, 0.0, 0.0, 0.0, 0.0, 29.0, 118.0, 120.0, 2.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 89.0, 100.0, 72.0, 32.0, 0.0, 0.0, 0.0, 0.0, 51.0, 113.0, 118.0, 109.0, 61.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 58.0, 67.0, 46.0, 16.0, 0.0, 8.0, 0.0, 15.0, 51.0, 122.0, 122.0, 111.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 25.0, 31.0, 64.0, 82.0, 125.0, 124.0, 114.0, 18.0, 0.0, 0.0, 0.0, 24.0, 56.0, 105.0, 116.0, 124.0, 77.0, 0.0, 0.0, 0.0, 71.0, 61.0, 0.0, 0.0, 3.0, 0.0]])

Method 1:
Input Data : (15000,89)
Output Data : (15000,6)

I will get good results on training, but when I try  using new data to predict it the results will be bad. then I thought maybe because the plantar pressure data are so similar, it would be hard for the model to recognize it. then I tried to add data sequences to each plantar pressure data. the data sequences that I added are 1-50, the reason I added these data sequences is so that the data on plantar pressure are slightly different from one another so that the model is easier to recognize when I test using new data and I enter 1-50 because every second plantar pressure will capture 50 data. after I added the data sequence to the plantar pressure, the shape of the plantar pressure data is (15000,90)

Plantar Pressure data after adding data sequence:
the shape of plantar pressure data before adding data sequence is (15000,89), the shape of plantar pressure data after adding data sequence is (15000,90)

Method 2:
Input Data : (15000,90)
Output Data : (15000,6)

so after I added the sequence data to the plantar pressure data, the prediction results from the training data and testing data will be good. my question is whether this method is allowed in data science? If yes, what method I use is called and is there a reference that is the same as the method I used in existing research


问:
Flutter module in native ios app is not completely closing the module
I'm facing issue after integrating flutter module into a native ios app.  After closing the flutter module either by using SystemNavigator.pop(animated:true), when trying to open it again from native ios app, the flutter module lands on the recently closed screen.  I have even tried by invoking a method from flutter module and closed the flutterViewController from native ios app, which again closes the app but opens the same screen that was exited before. Also, destroying the flutterEngine also didnt work.

Could anyone please share your knowledge regarding this.  It will be really helpful.

```<code>FlutterEngine *flutterEngine = ((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"com.sara.app/myAppChannel" binaryMessenger:flutterViewController.binaryMessenger];

//exitUpiModule triggered from flutter module
[channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
    if([call.method isEqualToString:@"exitUpiModule"]){

        //CLOSES THE FLUTTER MODULE BUT WHEN OPENED IT LANDS ON THE SAME SCREEN
        [flutterViewController dismissViewControllerAnimated:YES completion:nil];

      }
}];
</code>```

Tried dismissing the flutterViewController, detroyContext but didnt work.

Body:
I'm facing issue after integrating flutter module into a native ios app.  After closing the flutter module either by using SystemNavigator.pop(animated:true), when trying to open it again from native ios app, the flutter module lands on the recently closed screen.  I have even tried by invoking a method from flutter module and closed the flutterViewController from native ios app, which again closes the app but opens the same screen that was exited before. Also, destroying the flutterEngine also didnt work.

Could anyone please share your knowledge regarding this.  It will be really helpful.

FlutterEngine *flutterEngine = ((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"com.sara.app/myAppChannel" binaryMessenger:flutterViewController.binaryMessenger];

//exitUpiModule triggered from flutter module
[channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
    if([call.method isEqualToString:@"exitUpiModule"]){

        //CLOSES THE FLUTTER MODULE BUT WHEN OPENED IT LANDS ON THE SAME SCREEN
        [flutterViewController dismissViewControllerAnimated:YES completion:nil];

      }
}];

Tried dismissing the flutterViewController, detroyContext but didnt work.


问:
how to use protected route in nextjs? i have multiple login page for different purpose
I have multiple login page and register page in nextjs app. I have checked the token in _app.js and component will not be render as the token will not be set. Token only get set after the form is submitted or login. how to fix this in nextjs.

```<code>import { React, useEffect, useState } from "react";
import "../styles/globals.css";
import "primereact/resources/themes/lara-light-indigo/theme.css"; //theme
import "primereact/resources/primereact.min.css"; //core css
import "primeicons/primeicons.css";
import "primeflex/primeflex.css";
import store from "../redux/store";
import { Provider } from "react-redux";
import "react-toastify/dist/ReactToastify.css";
// import "bootstrap/dist/css/bootstrap.min.css";
import "../styles/Nav.css";
import "../styles/temp.css";
import MainLayout from "../component/Layouts/MainLayout";
import { setAuthorizationToken } from "../redux/incomeTax/d03/action";
import IndexLayout from "../component/Layouts/IndexLayout";

import { useRouter } from 'next/router';
function MyApp({ Component, ...pageProps }) {

    const { asPath, pathname } = useRouter();
   // const router = useRouter();
    console.log({asPath}); // '/blog/xyz'
    console.log({pathname}); // '/blog/[slug]'
    const [tokens, setTokens] = useState("");

    useEffect(() => {
        if(typeof window !== "undefined")
        {
            require("bootstrap/dist/css/bootstrap.min.css");
        }
      }, [])

    useEffect(() => {
        const token = localStorage.token1 ? localStorage.token1 : "";
console.log({token});
        if (tokens !== token) {
            setTokens(token);
            setAuthorizationToken(token);

        }
    });

    return (
        <>
            <Provider store={store}>
                { tokens !==''?
                (
                <MainLayout>
                    <Component {...pageProps} />
                </MainLayout>
                ):
                (
                //    RouteFunction()
                   <IndexLayout>

                   </IndexLayout>
                )

               }

            </Provider>
        </>
    );
}

export default MyApp;

</code>```

the above page is of _app.js which resides in pages folder.

Body:
I have multiple login page and register page in nextjs app. I have checked the token in _app.js and component will not be render as the token will not be set. Token only get set after the form is submitted or login. how to fix this in nextjs.

import { React, useEffect, useState } from "react";
import "../styles/globals.css";
import "primereact/resources/themes/lara-light-indigo/theme.css"; //theme
import "primereact/resources/primereact.min.css"; //core css
import "primeicons/primeicons.css";
import "primeflex/primeflex.css";
import store from "../redux/store";
import { Provider } from "react-redux";
import "react-toastify/dist/ReactToastify.css";
// import "bootstrap/dist/css/bootstrap.min.css";
import "../styles/Nav.css";
import "../styles/temp.css";
import MainLayout from "../component/Layouts/MainLayout";
import { setAuthorizationToken } from "../redux/incomeTax/d03/action";
import IndexLayout from "../component/Layouts/IndexLayout";

import { useRouter } from 'next/router';
function MyApp({ Component, ...pageProps }) {

    const { asPath, pathname } = useRouter();
   // const router = useRouter();
    console.log({asPath}); // '/blog/xyz'
    console.log({pathname}); // '/blog/[slug]'
    const [tokens, setTokens] = useState("");

    useEffect(() => {
        if(typeof window !== "undefined")
        {
            require("bootstrap/dist/css/bootstrap.min.css");
        }
      }, [])

    useEffect(() => {
        const token = localStorage.token1 ? localStorage.token1 : "";
console.log({token});
        if (tokens !== token) {
            setTokens(token);
            setAuthorizationToken(token);

        }
    });

    return (
        <>
            <Provider store={store}>
                { tokens !==''?
                (
                <MainLayout>
                    <Component {...pageProps} />
                </MainLayout>
                ):
                (
                //    RouteFunction()
                   <IndexLayout>

                   </IndexLayout>
                )

               }

            </Provider>
        </>
    );
}

export default MyApp;

the above page is of _app.js which resides in pages folder.


问:
How to replace WooCommerce My Account registration form with a Gravity User Registration Form
I would appreciate it if anyone could advise how to replace WooCommerce My Account registration form with a form created by the Gravity Forms User Registration plugin.

Thank you,

I tried the Enable Custom Registration Page option, but it changed only the WordPress default registration form, not the WooCommerce's.


问:
Why are identical SQL calls behaving differently?
I'm working on a web app in Rust.  I'm using Tokio Postgres, Rocket and Tera (this may be relevant).

I'm using the following to connect to my DB which doesn't fail in either case.

```<code> (sql_cli, connection) = match tokio_postgres::connect("postgresql://postgres:*my_password*@localhost:8127/*AppName*", NoTls).await{
        Ok((sql_cli, connection)) => (sql_cli, connection),
        Err(e) => return Err(Redirect::to(uri!(error_display(MyError::new("Failed to make SQLClient").details)))),
    };
</code>```

My query is as follows.  I keep my queries in a separate file (I'm self taught and find that easier).

```<code>let query= sql_cli.query(mycharactersquery::get_characters(user_id).as_str(), &[]).await.unwrap();
</code>```

The get characters is as follows.  It takes a user ID and should return the characters that they have made in the past.

```<code>pub fn get_characters(user_id: i16) -> String {
    format!("SELECT * FROM player_characters WHERE user_id = {} ORDER BY char_id ASC;", user_id)
}
</code>```

In my main file, I have one GET which is /mycharacters/<user_id> which works.  This GET returns an HTML file.  I have another GET which is /<user_id> which returns a Tera template.  The first works fine and loads the characters, the second doesn't: it just loads indefinitely.  I initially thought this was to do my lack of familiarity with Tera.

After some troubleshooting, I put some printouts in my code, the one before and after the SQL call work in /mycharacters/<user_id>, but only the one before writes to the terminal in /<user_id>.  This makes me think that Tera isn't the issue as it isn't making it past the SQL call.

I've found exactly where it is going wrong, but I don't know why as it isn't giving an error.

Could someone please let me know if there is something obvious that I am missing or provide some assistance?

P.S. The database only has 3 columns, so an actual timeout isn't the cause.

I expected both of these SQL calls to function as I am connected to my database properly and the call is copied from the working call.

Body:
I'm working on a web app in Rust.  I'm using Tokio Postgres, Rocket and Tera (this may be relevant).

I'm using the following to connect to my DB which doesn't fail in either case.

 (sql_cli, connection) = match tokio_postgres::connect("postgresql://postgres:*my_password*@localhost:8127/*AppName*", NoTls).await{
        Ok((sql_cli, connection)) => (sql_cli, connection),
        Err(e) => return Err(Redirect::to(uri!(error_display(MyError::new("Failed to make SQLClient").details)))),
    };

My query is as follows.  I keep my queries in a separate file (I'm self taught and find that easier).

let query= sql_cli.query(mycharactersquery::get_characters(user_id).as_str(), &[]).await.unwrap();

The get characters is as follows.  It takes a user ID and should return the characters that they have made in the past.

pub fn get_characters(user_id: i16) -> String {
    format!("SELECT * FROM player_characters WHERE user_id = {} ORDER BY char_id ASC;", user_id)
}

In my main file, I have one GET which is /mycharacters/<user_id> which works.  This GET returns an HTML file.  I have another GET which is /<user_id> which returns a Tera template.  The first works fine and loads the characters, the second doesn't: it just loads indefinitely.  I initially thought this was to do my lack of familiarity with Tera.

After some troubleshooting, I put some printouts in my code, the one before and after the SQL call work in /mycharacters/<user_id>, but only the one before writes to the terminal in /<user_id>.  This makes me think that Tera isn't the issue as it isn't making it past the SQL call.

I've found exactly where it is going wrong, but I don't know why as it isn't giving an error.

Could someone please let me know if there is something obvious that I am missing or provide some assistance?

P.S. The database only has 3 columns, so an actual timeout isn't the cause.

I expected both of these SQL calls to function as I am connected to my database properly and the call is copied from the working call.


问:
cannot send e-mails with txt file attachments
I wrote the following code to send an email with a text file attached through putextra, but the file is not attached with a toast message saying that the file cannot be attached. I don't know what went wrong.

mainActivity.kt

```<code>class MainActivity : AppCompatActivity() {

    private val vBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

        vBinding.button.setOnClickListener {
            try{
                val file = File("${getExternalFilesDir(null)}", "test.txt")
                val fw = FileWriter(file)
                fw.write("this is text TextFile")
                fw.close()

                val shareIntent = Intent(Intent.ACTION_SEND)
                shareIntent.type = "text/plain"
                shareIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("myEmail@gmail.com"))
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "testTitle")
                shareIntent.putExtra(Intent.EXTRA_TEXT,"test contents")
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("${getExternalFilesDir(null)}/test.txt"))
                startActivity(Intent.createChooser(shareIntent, "test Send Email"))

            }catch(err:Exception){
                Log.d("test", err.toString())
                Log.d("test", err.stackTraceToString())
            }
        }
    }
}
</code>```

manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <application

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="text/plain"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>
</code>```

I googled and tried modifying the manifest file, but failed.

Body:
I wrote the following code to send an email with a text file attached through putextra, but the file is not attached with a toast message saying that the file cannot be attached. I don't know what went wrong.

mainActivity.kt

class MainActivity : AppCompatActivity() {

    private val vBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

        vBinding.button.setOnClickListener {
            try{
                val file = File("${getExternalFilesDir(null)}", "test.txt")
                val fw = FileWriter(file)
                fw.write("this is text TextFile")
                fw.close()

                val shareIntent = Intent(Intent.ACTION_SEND)
                shareIntent.type = "text/plain"
                shareIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("myEmail@gmail.com"))
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "testTitle")
                shareIntent.putExtra(Intent.EXTRA_TEXT,"test contents")
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("${getExternalFilesDir(null)}/test.txt"))
                startActivity(Intent.createChooser(shareIntent, "test Send Email"))

            }catch(err:Exception){
                Log.d("test", err.toString())
                Log.d("test", err.stackTraceToString())
            }
        }
    }
}

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <application

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="text/plain"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

I googled and tried modifying the manifest file, but failed.


问:
Karate UI tests are Failing in Jenkins Pipeline
There are 2 issues:

Default Chrome Browser is NOT working in LOCAL for karate UI tests (Safari is working fine)

Karate UI tests are failing with the below errors:

SEVERE: command error: [/usr/bin/google-chrome, --remote-debugging-port=9222, --no-first-run, --user-data-dir=/home/jenkins/agent/workspace/_myproject_PR-001/app/target/chrome_1672115894098, --disable-popup-blocking] - Cannot run program "/usr/bin/google-chrome" (in directory "target/chrome_1672115894098"): error=2, No such file or directory

org.apache.http.conn.HttpHostConnectException: Connect to localhost:9222 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused), options: {type=chrome, target=null}

Please let me know if you know any resolution on the above issue


问:
Is deleting a hash faster than deleting keys individually? or does deleting a hash just iterate over the keys in the hash?
Currently trying to build a caching system that's efficient to update. I will need to delete my hashes here and there. Would it be faster to delete a whole hash at once or are there no performance differences in deleting a whole hash?

I'm wondering this as the redis documentation states the DEL command has a time complexity of O(M) for hashes which I'm unsure means it's referring to single key deletion within the hash (amount of keys in the hash i choose to delete) or the hash overall.

I'm expecting it to be O(1) for deletion of an entire hash but I could be wrong.


问:
Two "dataplotclick" event triggered on react fusion multi level piechart chart
I am using fusion multi level chart. But when I am click in second layer or center most layer, chartClickEvent function is triggering twice</p>
```<code>  <ReactFC
        type="multilevelpie"
        width="100%"
        height="300"
        dataFormat="JSON"
        dataSource={{
          chart: {
            ...chartConfig,
            showValues: '0',
            plotToolText: '$label, $dataValue <br> $percentValue of total',
            "showPlotBorder": "1",
            "pieborderthickness": "2",
            "hoverfillcolor": "#CCCCCC",
            "piebordercolor": "#FFFFFF",
            "labelPosition": "inside",
            "baseFontSize": "12",
          },
          "category": [{
            label: title,
            color: '#fff',
            category: data
        }}
        fcEvent-dataplotClick={(el, d) => chartClickEvent(el, d)}
      />

 const chartClickEvent = (eventObj, dataObj, groupBy) => {
    console.log('eventObj', eventObj)

  };
</code>```

Body:
I am using fusion multi level chart. But when I am click in second layer or center most layer, chartClickEvent function is triggering twice

  <ReactFC
        type="multilevelpie"
        width="100%"
        height="300"
        dataFormat="JSON"
        dataSource={{
          chart: {
            ...chartConfig,
            showValues: '0',
            plotToolText: '$label, $dataValue
 $percentValue of total',
            "showPlotBorder": "1",
            "pieborderthickness": "2",
            "hoverfillcolor": "#CCCCCC",
            "piebordercolor": "#FFFFFF",
            "labelPosition": "inside",
            "baseFontSize": "12",
          },
          "category": [{
            label: title,
            color: '#fff',
            category: data
        }}
        fcEvent-dataplotClick={(el, d) => chartClickEvent(el, d)}
      />

 const chartClickEvent = (eventObj, dataObj, groupBy) => {
    console.log('eventObj', eventObj)

  };


问:
'Net' object has no attribute 'Sigmoid'
I have been following the textbook, but there is an error in the imported contents and I don't know what to do.

this is the Net class

```<code>import torch
import torch.nn as nn

class Net(nn.Module):
  def __init__(self, n_input, n_output):
    super().__init__()
    self.l1 = nn.Linear(n_input,n_output)
    self.sigmoid = nn.Sigmoid()
    self.l1.weight.data.fill_(1.0)
    self.l1.bias.data.fill_(1.0)

  def forward(self,x):
    x1 = self.l1(x)
    x2 = self.Sigmoid(x1)
    return x2
</code>```

and the optimizer and loss functions and data

```<code>from torch import optim

criterion = nn.BCELoss()

lr = 0.01

optimizer = optim.SGD(net.parameters(),lr = lr)
</code>```

I have been following the textbook, but there is an error in the imported contents and I don't know what to do.

Title: 'Net' object has no attribute 'Sigmoid'

Body:
I have been following the textbook, but there is an error in the imported contents and I don't know what to do.

this is the Net class

import torch
import torch.nn as nn

class Net(nn.Module):
  def __init__(self, n_input, n_output):
    super().__init__()
    self.l1 = nn.Linear(n_input,n_output)
    self.sigmoid = nn.Sigmoid()
    self.l1.weight.data.fill_(1.0)
    self.l1.bias.data.fill_(1.0)

  def forward(self,x):
    x1 = self.l1(x)
    x2 = self.Sigmoid(x1)
    return x2

and the optimizer and loss functions and data

from torch import optim

criterion = nn.BCELoss()

lr = 0.01

optimizer = optim.SGD(net.parameters(),lr = lr)

I have been following the textbook, but there is an error in the imported contents and I don't know what to do.


问:
Remove bytes/characters from vector and move later characters to fill the gap. (Left-pack 32 bytes based on a 32-bit mask with AVX2)
I have a __m256i vector:

```<code>static char __attribute__((aligned(32))) str[32] = "Hello@@, This is my text !!!";
    __m256i vec_str=_mm256_load_si256((const __m256i*) str);
</code>```

Now, based on a 32-bit integer bit-maks, I want to remove some characters from this str (vec_str) and move the later characters backward to fill the gap. For example, i want to remove @@, and !!! and this is my bit-mask (bit 1 => keep | bit 0 => remove)

```<code>int mask=0b11110001111111111111111100011111;
</code>```

In fact, I want to delete the bytes where their bits (in bit-mask) are unset (0), copying later bytes to close the gap.
What I expected:

```<code>vec_str="Hello This is my text";
</code>```

I thought about indirect ways like separating the bit-mask into 2 16-bit masks and creating a table with 65536x16 elements for vpshufb (_mm256_shuffle_epi8) then using the table 2 times with memory-copy .... but I think this way is too heavy (too long). Is there any better direct way or a way without a copy in memory?

Body:
I have a __m256i vector:

static char __attribute__((aligned(32))) str[32] = "Hello@@, This is my text !!!";
    __m256i vec_str=_mm256_load_si256((const __m256i*) str);

Now, based on a 32-bit integer bit-maks, I want to remove some characters from this str (vec_str) and move the later characters backward to fill the gap. For example, i want to remove @@, and !!! and this is my bit-mask (bit 1 => keep | bit 0 => remove)

int mask=0b11110001111111111111111100011111;

In fact, I want to delete the bytes where their bits (in bit-mask) are unset (0), copying later bytes to close the gap.
What I expected:

vec_str="Hello This is my text";

I thought about indirect ways like separating the bit-mask into 2 16-bit masks and creating a table with 65536x16 elements for vpshufb (_mm256_shuffle_epi8) then using the table 2 times with memory-copy .... but I think this way is too heavy (too long). Is there any better direct way or a way without a copy in memory?


问:
Multiple Page Titles for a Page URL in GA4
We are seeing GA4 recording multiple Page titles for a page. I understand that for different languages we can have different Titles recorded but we are seeing multiple Titles in English itself.

enter image description here

We verified the GA4 settings and all looks good, but we are getting multiple English version Page titles for a same page.


问:
graphqlError.stack?.split is not a function
I have a response coming from a subgraph:

{
  errors: [
    {
      errcode: '23505',
      extensions: [Object],
      message: 'duplicate key value violates unique constraint "company_name_idx"',
      locations: [Array],
      path: [Array],
      stack: [Array]
    },
    {
      detail: 'Key (company_id)=(2eef1fbe-e2c5-4180-a6ba-2d7dd75a7613) is not present in table "company".',
      errcode: '23503',
      extensions: [Object],
      message: 'insert or update on table "companies_persons" violates foreign key constraint "companies_persons_company_id_fkey"',
      locations: [Array],
      path: [Array],
      stack: [Array]
    }
  ],
  data: { createCompany: null, createCompaniesPerson: null },
  http: Response {
    size: 0,
    timeout: 0,
    [Symbol(Body internals)]: { body: [Minipass], disturbed: true, error: null },
    [Symbol(Response internals)]: {
      url: 'http://host.docker.internal:8086/graphql',
      status: 200,
      statusText: 'OK',
      headers: [Headers],
      counter: 0,
      trailer: [Promise]
    }
  }
}
```
<p>I checked this via:</p>
<pre class="lang-js prettyprint-override"><code>didReceiveResponse: ({ response }) => {
  console.log("RESPONSE");
  console.log(response);
  return response;
},
</code>```

But the response that is being passed from the supergraph (latest versions of js ApolloGateway / ApolloServer) is:

{
  "errors": [
    {
      "message": "graphqlError.stack?.split is not a function",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "TypeError: graphqlError.stack?.split is not a function",
          "    at enrichError (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:42:57)",
          "    at file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:12:36",
          "    at Array.map (<anonymous>)",
          "    at normalizeAndFormatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:10:33)",
          "    at formatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:288:16)",
          "    at processGraphQLRequest (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:175:19)",
          "    at processTicksAndRejections (node:internal/process/task_queues:96:5)",
          "    at async internalExecuteOperation (file:///usr/src/app/node_modules/@apollo/server/dist/esm/ApolloServer.js:573:16)",
          "    at async runHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/runHttpQuery.js:115:29)",
          "    at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/httpBatching.js:34:16)"
        ]
      }
    },
    {
      "message": "graphqlError.stack?.split is not a function",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "TypeError: graphqlError.stack?.split is not a function",
          "    at enrichError (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:42:57)",
          "    at file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:12:36",
          "    at Array.map (<anonymous>)",
          "    at normalizeAndFormatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:10:33)",
          "    at formatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:288:16)",
          "    at processGraphQLRequest (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:175:19)",
          "    at processTicksAndRejections (node:internal/process/task_queues:96:5)",
          "    at async internalExecuteOperation (file:///usr/src/app/node_modules/@apollo/server/dist/esm/ApolloServer.js:573:16)",
          "    at async runHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/runHttpQuery.js:115:29)",
          "    at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/httpBatching.js:34:16)"
        ]
      }
    }
  ],
  "data": {
    "createCompany": null,
    "createCompaniesPerson": null
  }
}
```

Checking the code... seems as though I can thwart this error by setting includeStacktraceInErrorResponses to false, but I want the stacktrace in development.

Body:
I have a response coming from a subgraph:

{
  errors: [
    {
      errcode: '23505',
      extensions: [Object],
      message: 'duplicate key value violates unique constraint "company_name_idx"',
      locations: [Array],
      path: [Array],
      stack: [Array]
    },
    {
      detail: 'Key (company_id)=(2eef1fbe-e2c5-4180-a6ba-2d7dd75a7613) is not present in table "company".',
      errcode: '23503',
      extensions: [Object],
      message: 'insert or update on table "companies_persons" violates foreign key constraint "companies_persons_company_id_fkey"',
      locations: [Array],
      path: [Array],
      stack: [Array]
    }
  ],
  data: { createCompany: null, createCompaniesPerson: null },
  http: Response {
    size: 0,
    timeout: 0,
    [Symbol(Body internals)]: { body: [Minipass], disturbed: true, error: null },
    [Symbol(Response internals)]: {
      url: 'http://host.docker.internal:8086/graphql',
      status: 200,
      statusText: 'OK',
      headers: [Headers],
      counter: 0,
      trailer: [Promise]
    }
  }
}

I checked this via:

didReceiveResponse: ({ response }) => {
  console.log("RESPONSE");
  console.log(response);
  return response;
},

But the response that is being passed from the supergraph (latest versions of js ApolloGateway / ApolloServer) is:

{
  "errors": [
    {
      "message": "graphqlError.stack?.split is not a function",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "TypeError: graphqlError.stack?.split is not a function",
          "    at enrichError (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:42:57)",
          "    at file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:12:36",
          "    at Array.map (<anonymous>)",
          "    at normalizeAndFormatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:10:33)",
          "    at formatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:288:16)",
          "    at processGraphQLRequest (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:175:19)",
          "    at processTicksAndRejections (node:internal/process/task_queues:96:5)",
          "    at async internalExecuteOperation (file:///usr/src/app/node_modules/@apollo/server/dist/esm/ApolloServer.js:573:16)",
          "    at async runHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/runHttpQuery.js:115:29)",
          "    at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/httpBatching.js:34:16)"
        ]
      }
    },
    {
      "message": "graphqlError.stack?.split is not a function",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "TypeError: graphqlError.stack?.split is not a function",
          "    at enrichError (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:42:57)",
          "    at file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:12:36",
          "    at Array.map (<anonymous>)",
          "    at normalizeAndFormatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/errorNormalize.js:10:33)",
          "    at formatErrors (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:288:16)",
          "    at processGraphQLRequest (file:///usr/src/app/node_modules/@apollo/server/dist/esm/requestPipeline.js:175:19)",
          "    at processTicksAndRejections (node:internal/process/task_queues:96:5)",
          "    at async internalExecuteOperation (file:///usr/src/app/node_modules/@apollo/server/dist/esm/ApolloServer.js:573:16)",
          "    at async runHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/runHttpQuery.js:115:29)",
          "    at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/@apollo/server/dist/esm/httpBatching.js:34:16)"
        ]
      }
    }
  ],
  "data": {
    "createCompany": null,
    "createCompaniesPerson": null
  }
}

Checking the code... seems as though I can thwart this error by setting includeStacktraceInErrorResponses to false, but I want the stacktrace in development.


问:
Mulpiprocessing.Pool runs slow
I'm trying to get advantages of multi-processing in python, so did some tests and found multi-processing code runs much slower than plain one. What I do wrong???

Here is the test script:

```<code>import numpy as np
from datetime import datetime
from multiprocessing import Pool

def some_func(argv):
    x = argv[0]
    y = argv[1]
    return np.sum(x * y)

def other_func(argv):
    x = argv[0]
    y = argv[1]

    f1 = np.fft.rfft(x)
    f2 = np.fft.rfft(y)
    CC = np.fft.irfft(f1 * np.conj(f2))
    return CC

N = 20000
X = np.random.randint(0, 10, size=(N, N))
Y = np.random.randint(0, 10, size=(N, N))

output_check = np.zeros(N)
D1 = datetime.now()
for k in range(len(X)):
    output_check[k] = np.max(some_func((X[k], Y[k])))
print('Plain: ', datetime.now()-D1)

output = np.zeros(N)
D1 = datetime.now()
with Pool(10) as pool:  # CPUs
    for ind, res in enumerate(pool.imap(some_func, zip(X, Y), chunksize=1)):
        output[ind] = np.max(res)
    pool.close()
    pool.join()
print('Pool: ', datetime.now()-D1)
</code>```

Output:

Plain:  0:00:00.904062

Pool:  0:00:15.386251

Why so big difference? What consumes the time???

Have 80 CPUs available, tried different pool size and chunksize...

The actual function is more complex (like other_func), with it I get almost the same time for plain and parallel code, but still no speed-up :(

The input is a BIG 3D numpy array, and I need a pairwise convolution of its elements

Title: Mulpiprocessing.Pool runs slow

Body:
I'm trying to get advantages of multi-processing in python, so did some tests and found multi-processing code runs much slower than plain one. What I do wrong???

Here is the test script:

import numpy as np
from datetime import datetime
from multiprocessing import Pool

def some_func(argv):
    x = argv[0]
    y = argv[1]
    return np.sum(x * y)

def other_func(argv):
    x = argv[0]
    y = argv[1]

    f1 = np.fft.rfft(x)
    f2 = np.fft.rfft(y)
    CC = np.fft.irfft(f1 * np.conj(f2))
    return CC

N = 20000
X = np.random.randint(0, 10, size=(N, N))
Y = np.random.randint(0, 10, size=(N, N))

output_check = np.zeros(N)
D1 = datetime.now()
for k in range(len(X)):
    output_check[k] = np.max(some_func((X[k], Y[k])))
print('Plain: ', datetime.now()-D1)

output = np.zeros(N)
D1 = datetime.now()
with Pool(10) as pool:  # CPUs
    for ind, res in enumerate(pool.imap(some_func, zip(X, Y), chunksize=1)):
        output[ind] = np.max(res)
    pool.close()
    pool.join()
print('Pool: ', datetime.now()-D1)

Output:

Plain:  0:00:00.904062

Pool:  0:00:15.386251

Why so big difference? What consumes the time???

Have 80 CPUs available, tried different pool size and chunksize...

The actual function is more complex (like other_func), with it I get almost the same time for plain and parallel code, but still no speed-up :(

The input is a BIG 3D numpy array, and I need a pairwise convolution of its elements


问:
Notification for client connection establishment in server
I am using nghttp2 C++ library (version 1.30) to implement a web server using nghttp2::asio_http2::server. In the deployment many HTTP client connects to the sever and invokes several REST API over time before diconnect. The nghttp2 C++ library provides on_connect which helps to know when the connection is established in the client application.

Is there any simialr way to execute any call back or get notification in the server when the client connects? It is required to get the notification before the REST API is invoked. For example if a client connects and invokes two REST API, the server should be notified once. If I provided handler to server.handle, thats get invoked for each REST API call.

Notification/callback in server code


问:
Retriving RSA public key from hex string generated from x509certificate getpublickeystring method
I've been developing a project involving digital signatures. I'm given a publickey generated through getpublickeystring method of x509Certificate2.

This is the given publickey

```<code>3082010A0282010100D8F165280738A827AA1D2960D09ECA7EA3928BC3B6BA4CF034BEFE6E00DB434793B96C2FD2411BE086B6CE4B30441D18DFF377497F99F043E74B2C30555D2157C2838C9E7BDD566F0633CC0BE6F2649278BB8FE15EB2D4020C087B2252D8ED024DD260A3AA07F399D90EBDA722BEFECAD6D7A011A30F9013C4AFE3E15BA5E5B9028DE51079CDE125555B82E4269699E662D8BF182DF173FCC90135FC117B8254BF7036FE0A9B0667C0266E8EF94F9EE630CA0CF611FF0BB2BBFD99A7B9D9CC6C93D272A7DC87FE59D35C34D9487F1038179C6576114994C942F826168BDF112DD17FC5725684AE74359FED8C753D1D7F01AB8F5A070E93DD89CA0C9BC2520C850203010001
</code>```

But I'm unable to construct a correct pem certificate from this.

This the code I have used to generate pem from the hex string.

```<code>byte[] certBytes = Enumerable.Range(0, certHex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(certHex.Substring(x, 2), 16))
                     .ToArray();
string certPem = "-----BEGIN RSA PUBLIC KEY-----\n" +
    Convert.ToBase64String(certBytes, Base64FormattingOptions.InsertLineBreaks)
    .TrimEnd() + "\n-----END RSA PUBLIC KEY-----\n";
</code>```

Generated certPem

```<code>-----BEGIN CERTIFICATE-----
MIIBCgKCAQEA2PFlKAc4qCeqHSlg0J7KfqOSi8O2ukzwNL7+bgDbQ0eTuWwv0kEb4Ia2zkswRB0Y
3/N3SX+Z8EPnSywwVV0hV8KDjJ573VZvBjPMC+byZJJ4u4/hXrLUAgwIeyJS2O0CTdJgo6oH85nZ
Dr2nIr7+ytbXoBGjD5ATxK/j4Vul5bkCjeUQec3hJVVbguQmlpnmYti/GC3xc/zJATX8EXuCVL9w
Nv4KmwZnwCZujvlPnuYwygz2Ef8Lsrv9mae52cxsk9Jyp9yH/lnTXDTZSH8QOBecZXYRSZTJQvgm
FovfES3Rf8VyVoSudDWf7Yx1PR1/AauPWgcOk92JygybwlIMhQIDAQAB
-----END CERTIFICATE-----
</code>```

But the result is failing when I use

```<code>X509Certificate2 cert = new X509Certificate2(Encoding.ASCII.GetBytes(certPem));
</code>```

Going through some past questions I saw that rsa exponent and modulus values are separated using the, delimiter, but here, it is not present.

Kindly provide some insights to solve this issue.

Edit

Decryption Logic

```<code>csp = RSA.Create();
csp.ImportFromPem(certPem.ToCharArray());
var decryptedBytes = csp.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);
</code>```

Exception occurs during csp.Decrypt

```<code>Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Key does not exist.'
</code>```

Body:
I've been developing a project involving digital signatures. I'm given a publickey generated through getpublickeystring method of x509Certificate2.

This is the given publickey

3082010A0282010100D8F165280738A827AA1D2960D09ECA7EA3928BC3B6BA4CF034BEFE6E00DB434793B96C2FD2411BE086B6CE4B30441D18DFF377497F99F043E74B2C30555D2157C2838C9E7BDD566F0633CC0BE6F2649278BB8FE15EB2D4020C087B2252D8ED024DD260A3AA07F399D90EBDA722BEFECAD6D7A011A30F9013C4AFE3E15BA5E5B9028DE51079CDE125555B82E4269699E662D8BF182DF173FCC90135FC117B8254BF7036FE0A9B0667C0266E8EF94F9EE630CA0CF611FF0BB2BBFD99A7B9D9CC6C93D272A7DC87FE59D35C34D9487F1038179C6576114994C942F826168BDF112DD17FC5725684AE74359FED8C753D1D7F01AB8F5A070E93DD89CA0C9BC2520C850203010001

But I'm unable to construct a correct pem certificate from this.

This the code I have used to generate pem from the hex string.

byte[] certBytes = Enumerable.Range(0, certHex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(certHex.Substring(x, 2), 16))
                     .ToArray();
string certPem = "-----BEGIN RSA PUBLIC KEY-----\n" +
    Convert.ToBase64String(certBytes, Base64FormattingOptions.InsertLineBreaks)
    .TrimEnd() + "\n-----END RSA PUBLIC KEY-----\n";

Generated certPem

-----BEGIN CERTIFICATE-----
MIIBCgKCAQEA2PFlKAc4qCeqHSlg0J7KfqOSi8O2ukzwNL7+bgDbQ0eTuWwv0kEb4Ia2zkswRB0Y
3/N3SX+Z8EPnSywwVV0hV8KDjJ573VZvBjPMC+byZJJ4u4/hXrLUAgwIeyJS2O0CTdJgo6oH85nZ
Dr2nIr7+ytbXoBGjD5ATxK/j4Vul5bkCjeUQec3hJVVbguQmlpnmYti/GC3xc/zJATX8EXuCVL9w
Nv4KmwZnwCZujvlPnuYwygz2Ef8Lsrv9mae52cxsk9Jyp9yH/lnTXDTZSH8QOBecZXYRSZTJQvgm
FovfES3Rf8VyVoSudDWf7Yx1PR1/AauPWgcOk92JygybwlIMhQIDAQAB
-----END CERTIFICATE-----

But the result is failing when I use

X509Certificate2 cert = new X509Certificate2(Encoding.ASCII.GetBytes(certPem));

Going through some past questions I saw that rsa exponent and modulus values are separated using the, delimiter, but here, it is not present.

Kindly provide some insights to solve this issue.

Edit

Decryption Logic

csp = RSA.Create();
csp.ImportFromPem(certPem.ToCharArray());
var decryptedBytes = csp.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);

Exception occurs during csp.Decrypt

Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Key does not exist.'


问:
How to export the views to csv using BCP with carriage- return/line-feed delimiting rows
I wanted to export the data from the views to the CSV using the BCP Command, with carriage-
return/line-feed delimiting rows. For that, I have specified that in the XML format as below:

```<code><?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" LENGTH="9"  xsi:type="CharFixed" />
<FIELD ID="2" LENGTH="3"  xsi:type="CharFixed" />
<FIELD ID="3" xsi:type="CharTerm" TERMINATOR="\r\n" COLLATION="SQL_Latin1_General_CP1_CI_AS" />
</RECORD>
  <ROW>
    <COLUMN SOURCE="1" NAME="Id_ein_empr" xsi:type="SQLNVARCHAR" LENGTH="9" />
    <COLUMN SOURCE="2" NAME="Emp_Loc_nbr" xsi:type="SQLNVARCHAR" LENGTH="3" />
   </ROW>
</BCPFORMAT>

</code>```

And I am using this XML format in BCP query as:

For that, I have written the following query.

```<code>DECLARE
@DATACmd VARCHAR(500),
@FileLocation varchar(255),
@FileName varchar(255),
@StateCode varchar(2),
@v_Out_file_path varchar(255),
@v_Data_path varchar(255),
@header_format_path varchar(255),
@v_Header_path varchar(255),
@HeaderFileName varchar(255);

SET @FileLocation ='c:\csv\output'
SET @FileName = 'Araddis_'+FORMAT(Getdate(), 'MMddyyyy') + '.txt'
SET @v_Out_file_path = 'c:\csv\' + @StateCode + '\output\' + 'Output_' + @FileName
SET @v_Data_path = @FileLocation + '\' + @FileName

SELECT  @DATACmd = 'bcp '
                        + '"select * from Db_1.dbo.[Forms]"'
                        + ' queryout ' + @FileLocation
                        + '\' + @FileName
                        + ' -f "C:\csv\Format_FL.xml" -T -S' + @@servername;
SELECT  @DATACmd AS 'Command to execute';
EXECUTE master..xp_cmdshell @DATACmd;
</code>```

But this always give me an error as:

```<code>NULL
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Host-file columns may be skipped only when copying into the Server
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed
NULL
</code>```

when I didn't specify the TERMINATOR="\r\n" the query runs successfully but all the data will be in one line. So, how would I add the carraige-return with new line?

Body:
I wanted to export the data from the views to the CSV using the BCP Command, with carriage-
return/line-feed delimiting rows. For that, I have specified that in the XML format as below:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" LENGTH="9"  xsi:type="CharFixed" />
<FIELD ID="2" LENGTH="3"  xsi:type="CharFixed" />
<FIELD ID="3" xsi:type="CharTerm" TERMINATOR="\r\n" COLLATION="SQL_Latin1_General_CP1_CI_AS" />
</RECORD>
  <ROW>
    <COLUMN SOURCE="1" NAME="Id_ein_empr" xsi:type="SQLNVARCHAR" LENGTH="9" />
    <COLUMN SOURCE="2" NAME="Emp_Loc_nbr" xsi:type="SQLNVARCHAR" LENGTH="3" />
   </ROW>
</BCPFORMAT>

And I am using this XML format in BCP query as:

For that, I have written the following query.

DECLARE
@DATACmd VARCHAR(500),
@FileLocation varchar(255),
@FileName varchar(255),
@StateCode varchar(2),
@v_Out_file_path varchar(255),
@v_Data_path varchar(255),
@header_format_path varchar(255),
@v_Header_path varchar(255),
@HeaderFileName varchar(255);

SET @FileLocation ='c:\csv\output'
SET @FileName = 'Araddis_'+FORMAT(Getdate(), 'MMddyyyy') + '.txt'
SET @v_Out_file_path = 'c:\csv\' + @StateCode + '\output\' + 'Output_' + @FileName
SET @v_Data_path = @FileLocation + '\' + @FileName

SELECT  @DATACmd = 'bcp '
                        + '"select * from Db_1.dbo.[Forms]"'
                        + ' queryout ' + @FileLocation
                        + '\' + @FileName
                        + ' -f "C:\csv\Format_FL.xml" -T -S' + @@servername;
SELECT  @DATACmd AS 'Command to execute';
EXECUTE master..xp_cmdshell @DATACmd;

But this always give me an error as:

NULL
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Host-file columns may be skipped only when copying into the Server
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed
NULL

when I didn't specify the TERMINATOR="\r\n" the query runs successfully but all the data will be in one line. So, how would I add the carraige-return with new line?


问:
Files from nuget package used in .Net core Web Api not accessed from Debug folder, instead accessed from project location
I have created a .netstandard nuget package which I am using in Asp.NetCoreWebApi. When I install the nuget packages, some fonts and images that are present in a folder named 'Resources' are downloaded into the .net core project. This is not physically available in the project root, but available as a shortcut link which is denoted by small arrow icon in the solution explorer.

When I build the project, this 'Resources' folder is available in the bin\Debug folder.

Now, when I run the WebApi project, and debug, I am getting an exception which says,

"Cannot find the path \Resources\Fonts."

Why isnt my WebApi searching in the Debug folder?

How to change this ?


问:
Telegram Bot callBackQuery php,laravel
I want to implement a pagination for telegram bot with inlinekeyboard with nutgram in laravel but when I use inlineKeyboard tow times I get this error:

Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message

This is my code :

```<code>public function start(Nutgram $bot)
{

    $message = $this->getRecords();
    //$bot->sendMessage(implode(PHP_EOL,$message));
    $this->menuText($message)
        ->addButtonRow(
            InlineKeyboardButton::make('◀', callback_data: 'pre@handlePage'),
            InlineKeyboardButton::make('▶', callback_data: 'next@handlePage')
        )
        ->orNext('none')
        ->showMenu();
}

public function handlePage(Nutgram $bot)
{
    $bot->answerCallbackQuery(['recived',true]);
    $page = $bot->callbackQuery()->data;

    if($page === 'next')
    {
        self::$page = (self::$page)+1;
        $posts = $this->getRecords();

        try {
            $this->menuText($posts )
            ->orNext('none')
            ->showMenu();
        } catch (\Throwable $th) {
            Storage::put('public/error.txt',$th->getMessage());
        }

        return;
    }

    self::$page = (self::$page == 0) ? (self::$page)+1 : (self::$page)-1;
    $posts = $this->getRecords();

    try {

        $this->menuText($posts)
        ->orNext('none')
        ->showMenu();

    } catch (\Throwable $th) {

        Storage::put('public/error.txt',$th->getMessage());

    }
}
</code>```

How can I use inlineKeyboard with callBackQuery for many times?

Title: Telegram Bot callBackQuery php,laravel

Body:
I want to implement a pagination for telegram bot with inlinekeyboard with nutgram in laravel but when I use inlineKeyboard tow times I get this error:

Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message

This is my code :

public function start(Nutgram $bot)
{

    $message = $this->getRecords();
    //$bot->sendMessage(implode(PHP_EOL,$message));
    $this->menuText($message)
        ->addButtonRow(
            InlineKeyboardButton::make('◀', callback_data: 'pre@handlePage'),
            InlineKeyboardButton::make('▶', callback_data: 'next@handlePage')
        )
        ->orNext('none')
        ->showMenu();
}

public function handlePage(Nutgram $bot)
{
    $bot->answerCallbackQuery(['recived',true]);
    $page = $bot->callbackQuery()->data;

    if($page === 'next')
    {
        self::$page = (self::$page)+1;
        $posts = $this->getRecords();

        try {
            $this->menuText($posts )
            ->orNext('none')
            ->showMenu();
        } catch (\Throwable $th) {
            Storage::put('public/error.txt',$th->getMessage());
        }

        return;
    }

    self::$page = (self::$page == 0) ? (self::$page)+1 : (self::$page)-1;
    $posts = $this->getRecords();

    try {

        $this->menuText($posts)
        ->orNext('none')
        ->showMenu();

    } catch (\Throwable $th) {

        Storage::put('public/error.txt',$th->getMessage());

    }
}

How can I use inlineKeyboard with callBackQuery for many times?


问:
Delete django models object with duplicate field
I want delete django models object with duplicate field.
for example:

ProgrammingQuestionAnswer.objects.filter(accept=True, programming_question=programming_question)
```
<p>here, maybe a user has 2 accept in the question. I want to count those duplicates once</p>
<p>this is my model:</p>
<pre class="lang-py prettyprint-override"><code>class ProgrammingQuestionAnswer(models.Model):
    languages = (
        ('python', 'Python'),
        ('cpp', 'C++'),
    )
    programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True)
    language = models.CharField(max_length=100, choices=languages, default="python")
    time = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True)
    accept = models.BooleanField(default=False)
</code>```

Body:
I want delete django models object with duplicate field.
for example:

ProgrammingQuestionAnswer.objects.filter(accept=True, programming_question=programming_question)

here, maybe a user has 2 accept in the question. I want to count those duplicates once

this is my model:

class ProgrammingQuestionAnswer(models.Model):
    languages = (
        ('python', 'Python'),
        ('cpp', 'C++'),
    )
    programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True)
    language = models.CharField(max_length=100, choices=languages, default="python")
    time = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True)
    accept = models.BooleanField(default=False)


问:
I got an error while using Scss in my Reactjs project
enter image description here[[enter image description here](https://i.stack.imgur.com/gemsk.png)](https://i.stack.imgur.com/zhqUC.png)

can someone help me fix the error to be able to use scss in my project


问:
xamarin forms android, Font asset not found sans-serif-medium when switching to AppShell
I am attempting to code an App in Xamarin Forms.

Upon startup, if the app is logged in the the user will be taken to the main shell with flyouts etc. If they are not logged in, then they will be taken to the signup/login page.

I have the following code in my App.xaml.cs

```<code>    public App()
    {
        Instance = this;
        InitializeComponent();

        AssessStartupPage();
    }

    public void AssessStartupPage()
    {
        if (App.LoggedInUser == null)
        {
            SwitchToSignupPage_OTP();
            return;
        }
        SwitchToShell();
    }

    public void SwitchToSignupPage_OTP() => SwitchMainView(new SignupPage_OTP());
    public void SwitchToShell() => SwitchMainView(new AppShell());
</code>```

When I attempt to switch to the shell from another Page (by calling App.Instance.SwitchToShell) the following exception is thrown:

Java.Lang.RuntimeException
Font asset not found sans-serif-medium

However if I change the AssessStartupPage() function which is called on startup to this:

```<code>    public void AssessStartupPage()
    {
        SwitchToShell();
        return;
    }
</code>```

The shell loads correctly at startup. However I need to be able to have the Signup page load at start if the user is not signed in and therefore need to be able to switch to the shell once signup is complete.

I have updated all the xamarin forms and xamarin essential libraries to the latest stable version but nothing seems to help.

The problem doesn't occur when I debug the app in UWP mode.

Body:
I am attempting to code an App in Xamarin Forms.

Upon startup, if the app is logged in the the user will be taken to the main shell with flyouts etc. If they are not logged in, then they will be taken to the signup/login page.

I have the following code in my App.xaml.cs

    public App()
    {
        Instance = this;
        InitializeComponent();

        AssessStartupPage();
    }

    public void AssessStartupPage()
    {
        if (App.LoggedInUser == null)
        {
            SwitchToSignupPage_OTP();
            return;
        }
        SwitchToShell();
    }

    public void SwitchToSignupPage_OTP() => SwitchMainView(new SignupPage_OTP());
    public void SwitchToShell() => SwitchMainView(new AppShell());

When I attempt to switch to the shell from another Page (by calling App.Instance.SwitchToShell) the following exception is thrown:

Java.Lang.RuntimeException
Font asset not found sans-serif-medium

However if I change the AssessStartupPage() function which is called on startup to this:

    public void AssessStartupPage()
    {
        SwitchToShell();
        return;
    }

The shell loads correctly at startup. However I need to be able to have the Signup page load at start if the user is not signed in and therefore need to be able to switch to the shell once signup is complete.

I have updated all the xamarin forms and xamarin essential libraries to the latest stable version but nothing seems to help.

The problem doesn't occur when I debug the app in UWP mode.


问:
Firebase - Get last 100 response onValue trigger?
I need to get the last 100 response whenever onValue triggers, however I am not sure if using callback method will anyway query for all the results as shown below:

```<code>onValue(chatRef, (snapshot) => {
            if (snapshot.exists()) {
                console.log('Added child = ', snapshot.val());
            } else console.log('Uhum');
        });
</code>```

In the above snippet, my understanding is that snapshot.val being a synchronous method would have already fetched all the response which can be troublesome for me. However how I want it to be is:

```<code>onValue(query(chatRef, limitToLast(100)), async (snapshot) => {
            if (snapshot.exists()) {
                console.log('Added child 01 = ', snapshot.val());
            } else console.log('Uhum');
        });
</code>```

My question is will the second call make a difference or performance and resource consumption wise both are the same? And also will the second call ensure that although I am taking last 100 entries but it will be watching all the records that get updated or added?

Body:
I need to get the last 100 response whenever onValue triggers, however I am not sure if using callback method will anyway query for all the results as shown below:

onValue(chatRef, (snapshot) => {
            if (snapshot.exists()) {
                console.log('Added child = ', snapshot.val());
            } else console.log('Uhum');
        });

In the above snippet, my understanding is that snapshot.val being a synchronous method would have already fetched all the response which can be troublesome for me. However how I want it to be is:

onValue(query(chatRef, limitToLast(100)), async (snapshot) => {
            if (snapshot.exists()) {
                console.log('Added child 01 = ', snapshot.val());
            } else console.log('Uhum');
        });

My question is will the second call make a difference or performance and resource consumption wise both are the same? And also will the second call ensure that although I am taking last 100 entries but it will be watching all the records that get updated or added?


问:
How can I use single pre-resgistered ip for outbounding request to specific host
I need to use external 3-rd party API, and it's vendor requires us to register IP address for the request source.

But with elastic beanstalk along with application load balancer and auto scaling group,
all public IPs assigned to each ec2 instances are auto-generated in random manner.

Cases are below,

every instances inside load balancer can request to 3-rd party vendor server for data.

Vendor only send response to pre-registered IP address. If request source address is not in list, it reject to send response.

The instances reside in default VPC.

How can I use single IP for outbounding request?


问:
Unable to refer an object/variable dynamically during runtime using eval
I'm trying to import an image in NextJS:

import linkedin from "../public/images/linkedin.webp";
```
<p>While referencing this variable dynamically during runtime:</p>
<pre class="lang-js prettyprint-override"><code>const socialButtons = [];

for (let i = 0; i < Object.keys(data.socials).length; i++) {
  socialButtons.push(
    <Image
      src={eval(Object.keys(data.socials)[i])}  //this line gives error
      width={48}
      height={48}
      alt="linkedin"
    />
  );
}
</code>```

I'm getting this error:

```<code>Unhandled Runtime Error

ReferenceError: linkedin is not defined
</code>```

Body:
I'm trying to import an image in NextJS:

import linkedin from "../public/images/linkedin.webp";

While referencing this variable dynamically during runtime:

const socialButtons = [];

for (let i = 0; i < Object.keys(data.socials).length; i++) {
  socialButtons.push(
    <Image
      src={eval(Object.keys(data.socials)[i])}  //this line gives error
      width={48}
      height={48}
      alt="linkedin"
    />
  );
}

I'm getting this error:

Unhandled Runtime Error

ReferenceError: linkedin is not defined