问:
Retrieve all data from query
I keep struggling with Django Model, Managers' relations.

I have a Profile model, Product Model, and Holding model.

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True, through='Holding')

    def __str__(self):
        return str(self.user)

class Product(models.Model):

    product_name = models.CharField(max_length=255, blank=False, unique=True)
    product_slug = models.CharField(max_length=50, blank=True,null=True)
    product_symbol = models.CharField(max_length=50, blank=True,null=True)
    product_price = models.FloatField(blank=True,null=True)

    def __str__(self):
        return str(self.product_name)

class Holding(models.Model):

    product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)
</code>```

I'm trying to retrieve the data from a user (Profile) for a Product within Holding Basically I want to show the amount of a product a user is currently holding.

I'm doing this in my view

```<code>def show_product_details(request, product_name):
    product = product.objects.get(Product_name=product_name)
    ...

    profile = Profile.objects.get(user = request.user)
    product_holding = profile.holding_set.get(product_name__product_name = product_name)

     return render(request, 'productdetails.html', {'product_holding':product_holding ...}
</code>```

But this isn't returning all the data, but instead just the product_name.

What am i doing wrong.? :(

答:
In line

```<code>product_holding = profile.holding_set.get(product_name__product_name = product_name)
</code>```

You are accessing Product model (product_name field in Holding model) and then from this model you are accessing field "product_name" which correspond to

```<code>product_name = models.CharField(max_length=255, blank=False, unique=True)
</code>```

in Product model. So you are getting just the name of it.

If you want to get the whole model data then use just:

```<code>product_holding = profile.holding_set.get(product_name = product_name)
</code>```

And the you can access each field by using

```<code>{{product_name.product_name}}
{{product_name.product_price}}
</code>```

Title: Retrieve all data from query

Body:
I keep struggling with Django Model, Managers' relations.

I have a Profile model, Product Model, and Holding model.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True, through='Holding')

    def __str__(self):
        return str(self.user)

class Product(models.Model):

    product_name = models.CharField(max_length=255, blank=False, unique=True)
    product_slug = models.CharField(max_length=50, blank=True,null=True)
    product_symbol = models.CharField(max_length=50, blank=True,null=True)
    product_price = models.FloatField(blank=True,null=True)

    def __str__(self):
        return str(self.product_name)

class Holding(models.Model):

    product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)

I'm trying to retrieve the data from a user (Profile) for a Product within Holding Basically I want to show the amount of a product a user is currently holding.

I'm doing this in my view

def show_product_details(request, product_name):
    product = product.objects.get(Product_name=product_name)
    ...

    profile = Profile.objects.get(user = request.user)
    product_holding = profile.holding_set.get(product_name__product_name = product_name)

     return render(request, 'productdetails.html', {'product_holding':product_holding ...}

But this isn't returning all the data, but instead just the product_name.

What am i doing wrong.? :(

Body:
In line

product_holding = profile.holding_set.get(product_name__product_name = product_name)

You are accessing Product model (product_name field in Holding model) and then from this model you are accessing field "product_name" which correspond to

product_name = models.CharField(max_length=255, blank=False, unique=True)

in Product model. So you are getting just the name of it.

If you want to get the whole model data then use just:

product_holding = profile.holding_set.get(product_name = product_name)

And the you can access each field by using

{{product_name.product_name}}
{{product_name.product_price}}


来源: stackexchange

问:
Authlogic: generates "Email has already been taken" error twice
I'm using authlogic with my user model, with the login field set to use email, thus:

```<code>acts_as_authentic do |c|
  c.login_field = :email
end
</code>```

If i try to make a new user, and the email is already in use, it adds a duplicate email error twice: (from the console)

```<code>user = User.new(:first_name => "fred", :last_name => "Smith", :email => User.last.email);user.valid?;errors = user.errors
=> {:email=>["has already been taken", "has already been taken"]}
</code>```

I'm guessing this is something to do with using the email as the login, maybe?  I don't have any other validations on email apart from validates_format_of, and i experimented with removing that validation (doesn't make any difference).

It's a pain as it's messing up my the errors i show on the form when validation fails.

Before i go trying to hack authlogic, does anyone know why this might be happening?  thanks, max

答:
I just ran into the same issue. Try calling config.validate_email_field = false in the acts_as_authentic block. It'll still validate the login field, which in our case in the email field, but only once.

```<code>acts_as_authentic do |config|
  config.login_field :email
  config.validate_email_field = false
    ...
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using authlogic with my user model, with the login field set to use email, thus:

acts_as_authentic do |c|
  c.login_field = :email
end

If i try to make a new user, and the email is already in use, it adds a duplicate email error twice: (from the console)

user = User.new(:first_name => "fred", :last_name => "Smith", :email => User.last.email);user.valid?;errors = user.errors
=> {:email=>["has already been taken", "has already been taken"]}

I'm guessing this is something to do with using the email as the login, maybe?  I don't have any other validations on email apart from validates_format_of, and i experimented with removing that validation (doesn't make any difference).

It's a pain as it's messing up my the errors i show on the form when validation fails.

Before i go trying to hack authlogic, does anyone know why this might be happening?  thanks, max

Body:
I just ran into the same issue. Try calling config.validate_email_field = false in the acts_as_authentic block. It'll still validate the login field, which in our case in the email field, but only once.

acts_as_authentic do |config|
  config.login_field :email
  config.validate_email_field = false
    ...
end


问:
R and Rstudio Docker vs Binder
My problem is that I can't use R-studio at my work place as the IT does not support it  . I want to use R and R-studio that installed on my personnel laptop on my company laptop ( using a modern browser which is behind firewall ) . Some of the options   I am thinking of two two things

should I need to  build  a docker for R and R-studio (I see base images are already available) , I am mostly interested in basic  R , Dplyr  (haven ,xporter, and Reticulate ) packages .

Should I have to use a binder .  I am not technical person and my programming skills are very limited can any one suggest me way .

What exactly are the difference between using Docker option vs Binder ?
I know I can use R-Studio online and get my work done but with the new paid account I am running out of project hours and very slow sometimes . Thanks in advance

答:
If you are using Jupyter notebooks extensively then it may make sense to use Binder

But if you simply want to use R and Rstudio, then all you need is docker. A good resource is

https://github.com/rocker-org/rocker

ContentLicense: CC BY-SA 4.0

Title: R and Rstudio Docker vs Binder


问:
Input 1D array with float datatype in C++
I would like to input row = [0.160625, 0.967468297, 3.520480583, 0.862454481, -0.341933766] as entry which is float type and pass it to forward module. I used python trying to translate to C++,
I got syntax error. Support needed. Thanks!

```<code>    // run not okay
    // Create a vector of inputs.
    std::vector<torch::jit::IValue> inputs;
    row = [0.190625, 0.957468297, 4.520480583, 0.962454481, -0.241933766]
    inputs.push_back(torch::tensor(row));

    // Execute the model and turn its output into a tensor.
    at::Tensor output = module.forward(inputs).toTensor();
    std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/4) << '\n';
</code>```

I would like to use row as instance and get the output.
When I use dummy values such as torch::one({1, 5}), the app run ok.
However, when I passed the real value as row - the float array, the app is aborted.

```<code>    // run ok for this case
    // Create a vector of inputs.
    std::vector<torch::jit::IValue> inputs;
    inputs.push_back(torch::ones({ 1, 5}));

    // Execute the model and turn its output into a tensor.
    at::Tensor output = module.forward(inputs).toTensor();
    std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/4) << '\n';
</code>```

Body:
I would like to input row = [0.160625, 0.967468297, 3.520480583, 0.862454481, -0.341933766] as entry which is float type and pass it to forward module. I used python trying to translate to C++,
I got syntax error. Support needed. Thanks!

    // run not okay
    // Create a vector of inputs.
    std::vector<torch::jit::IValue> inputs;
    row = [0.190625, 0.957468297, 4.520480583, 0.962454481, -0.241933766]
    inputs.push_back(torch::tensor(row));

    // Execute the model and turn its output into a tensor.
    at::Tensor output = module.forward(inputs).toTensor();
    std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/4) << '\n';

I would like to use row as instance and get the output.
When I use dummy values such as torch::one({1, 5}), the app run ok.
However, when I passed the real value as row - the float array, the app is aborted.

    // run ok for this case
    // Create a vector of inputs.
    std::vector<torch::jit::IValue> inputs;
    inputs.push_back(torch::ones({ 1, 5}));

    // Execute the model and turn its output into a tensor.
    at::Tensor output = module.forward(inputs).toTensor();
    std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/4) << '\n';

Body:
Did you try replacing [] with {} as mentioned before?

float row[] = { 0.190625, 0.957468297, 4.520480583, 0.962454481, -0.241933766 };


问:
Integrating numerical data with scipy
Basically I have 2 arrays obtained from a set of data points one array for the x values and one for the y values. I need to numerically integrate the y values with respect to the x values - i.e. an element from the y integrated with respect to the corresponding element in x. This should then generate a new array of elements. I have tried simpson's rule but I get one value back instead of an array. A general idea or approach is all I'm looking for. Any help, however, will be much appreciated.

Thanks.

答:
```<code># check out this:
def integration_by_simpsons_3_8_th_rule(i,X,Y,Fd):
   h = X[i]-X[i-1]
   y_n = Y[i]
   y_n_1 = signal[i-1]
   y_n_2 = signal[i-2]
   y_n_3 = signal[i-3]
   Area = (3/8)*h*( y_n_3 + 3*(y_n_2 + y_n_1) + y_n )
   return (X[i-1],Area)

def rolling_integration(X,Y,Fd):
    Y_int = []
    corres_X = []
    for i in range(3,len(signal),1):
        x,y = integration_by_simpsons_3_8_th_rule(i,X,Y,Fd)
        Y_int.append(float(y))
        corres_X.append(float(x))
    return (np.array(corres_X)+(np.array(1/(4*float(Fd)))),np.array(Y_int))

#Fd : for phase correction
</code>```

Title: Integrating numerical data with scipy


问:
Automatically not insert created_at and updated_at in laravel not working
Automatically not insert created_at and updated_at in laravel not working.

```<code>DB::table('commundityvendordata')->insert($commdata);
</code>```

I am using this above statement passing an array for inserting multiple record $commdataworking fine but when check my created_at and updated_at column in database not getting timestamp.

Model:

```<code><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class commundityvendordata extends Model
{
    use HasFactory;
    protected $table ='commundityvendordata';
}
</code>```

Migration:

```<code>public function up()
    {
        Schema::create('commundityvendordata', function (Blueprint $table) {
            $table->bigIncrements('vender_id')->unsignedBigInteger();
            $table->date('new_date');
            $table->unsignedBigInteger('cd_id');
            $table->foreign('cd_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('cn_id');
            $table->foreign('cn_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('unit_id');
            $table->foreign('unit_id')->references('unit_id')->on('units')->onDelete('cascade');
            $table->unsignedInteger('vender1');
            $table->unsignedInteger('vender2');
            $table->unsignedInteger('vender3');
            $table->unsignedInteger('vender4');
            $table->timestamps();
        });
    }
</code>```

Controller:

```<code>function commundityvendordata(Request $request){
                $collection = count(collect($request));
                $cvendordata = new commundityvendordata;
                for ($i=0; $i < $collection; $i++) {
                $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
                $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
                $cd_id = $CCode['cd_id'];
                $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
                $cn_id = $CName['cd_id'];
                $CUnit=units::where('unit','=',$request->cunit[$i])->first();
                $unit_id = $CUnit['unit_id'];
                $vender1 = $request->vendor1[$i];
                $vender2 = $request->vendor2[$i];
                $vender3 = $request->vendor3[$i];
                $vender4 = $request->vendor4[$i];
                   $commdata = [
                    'new_date'  => $new_date,
                    'cd_id'     => $cd_id,
                    'cn_id'     => $cn_id,
                    'unit_id'   => $unit_id,
                    'vender1'   => $vender1,
                    'vender2'   => $vender2,
                    'vender3'   => $vender3,
                    'vender4'   => $vender4
                ];
                if($cd_id != ''){
                         DB::table('commundityvendordata')->insert($commdata);
                    }else{
                        return back()->with('success','Data Saved...');
                    }
            }
    }
</code>```

database table screen shot:

答:
created_at and updated_at are only automatically inserted if you are using Eloquent.

If you are using the DB facade you will have to manually insert them:

```<code>      $commdata = [
                    'new_date'  => $new_date,
                    'cd_id'     => $cd_id,
                    'cn_id'     => $cn_id,
                    'unit_id'   => $unit_id,
                    'vender1'   => $vender1,
                    'vender2'   => $vender2,
                    'vender3'   => $vender3,
                    'vender4'   => $vender4,
                    "created_at" =>  \Carbon\Carbon::now(), # new \Datetime()
                    "updated_at" => \Carbon\Carbon::now(),  # new \Datetime()
                ];
</code>```

If you want to use Laravel at the fullest and don't have advanced/complex queries, I recommend to you using Models and Eloquent.

Body:
Automatically not insert created_at and updated_at in laravel not working.

DB::table('commundityvendordata')->insert($commdata);

I am using this above statement passing an array for inserting multiple record $commdataworking fine but when check my created_at and updated_at column in database not getting timestamp.

Model:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class commundityvendordata extends Model
{
    use HasFactory;
    protected $table ='commundityvendordata';
}

Migration:

public function up()
    {
        Schema::create('commundityvendordata', function (Blueprint $table) {
            $table->bigIncrements('vender_id')->unsignedBigInteger();
            $table->date('new_date');
            $table->unsignedBigInteger('cd_id');
            $table->foreign('cd_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('cn_id');
            $table->foreign('cn_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('unit_id');
            $table->foreign('unit_id')->references('unit_id')->on('units')->onDelete('cascade');
            $table->unsignedInteger('vender1');
            $table->unsignedInteger('vender2');
            $table->unsignedInteger('vender3');
            $table->unsignedInteger('vender4');
            $table->timestamps();
        });
    }

Controller:

function commundityvendordata(Request $request){
                $collection = count(collect($request));
                $cvendordata = new commundityvendordata;
                for ($i=0; $i < $collection; $i++) {
                $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
                $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
                $cd_id = $CCode['cd_id'];
                $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
                $cn_id = $CName['cd_id'];
                $CUnit=units::where('unit','=',$request->cunit[$i])->first();
                $unit_id = $CUnit['unit_id'];
                $vender1 = $request->vendor1[$i];
                $vender2 = $request->vendor2[$i];
                $vender3 = $request->vendor3[$i];
                $vender4 = $request->vendor4[$i];
                   $commdata = [
                    'new_date'  => $new_date,
                    'cd_id'     => $cd_id,
                    'cn_id'     => $cn_id,
                    'unit_id'   => $unit_id,
                    'vender1'   => $vender1,
                    'vender2'   => $vender2,
                    'vender3'   => $vender3,
                    'vender4'   => $vender4
                ];
                if($cd_id != ''){
                         DB::table('commundityvendordata')->insert($commdata);
                    }else{
                        return back()->with('success','Data Saved...');
                    }
            }
    }

database table screen shot:

Body:
created_at and updated_at are only automatically inserted if you are using Eloquent.

If you are using the DB facade you will have to manually insert them:

      $commdata = [
                    'new_date'  => $new_date,
                    'cd_id'     => $cd_id,
                    'cn_id'     => $cn_id,
                    'unit_id'   => $unit_id,
                    'vender1'   => $vender1,
                    'vender2'   => $vender2,
                    'vender3'   => $vender3,
                    'vender4'   => $vender4,
                    "created_at" =>  \Carbon\Carbon::now(), # new \Datetime()
                    "updated_at" => \Carbon\Carbon::now(),  # new \Datetime()
                ];

If you want to use Laravel at the fullest and don't have advanced/complex queries, I recommend to you using Models and Eloquent.


问:
How do you write an IsPressed (a function that should only return true on first press)?
I need a function in a game loop that should only return true on first press.

I don't know which game I can give an example from which game is currently on the market, but I will explain this request in detail (I haven't played/can't play any of the modern games because I'm blind).

For example, there is an event you are listening to in the loop. When the user presses the S key, a text showing the last status of the character appears on the screen: Stamina, energy etc.
This loop can run thousands of times per second, as the loops depend on the speed of the hardware and the code you write.
We only need to detect the first press of the user. It should return false when the key is hold pressed. Otherwise, the last status of the user is shown thousands of times on the screen.

I am trying to provide this functionality using win32api. GetAsyncKeyState seems like the right option for this scenario but I don't understand how this can be done.

bool IsPressed(int key) {
return GetAsyncKeyState(key) & 1 != 0;
}
```

The function I wrote acts like a char event.

How can I write this?

I tried using other answers on StackOwerflow. However, I could not find an answer to the question I asked. Still, these answers helped me with some issues:
What is the fastest way to determine a key press and key holding in Win32?

答:
I do not know about C ++, but it certainly follows the same process in all languages, so you can set that pressure method to "if" and define a number that, by pressing its value, becomes one, And write. In "If" if the value of the number is equal to 1, do not do this again

In java, for example, it says:

```<code>int x = 0;
Button back = findViewById(R.id.button);
if(x == 0){
    back.setOnClickListener(v -> {
        //your code to do;
        x = 1;
    });
}else{}
</code>```

that work in C++ too,

Body:
I need a function in a game loop that should only return true on first press.

I don't know which game I can give an example from which game is currently on the market, but I will explain this request in detail (I haven't played/can't play any of the modern games because I'm blind).

For example, there is an event you are listening to in the loop. When the user presses the S key, a text showing the last status of the character appears on the screen: Stamina, energy etc.
This loop can run thousands of times per second, as the loops depend on the speed of the hardware and the code you write.
We only need to detect the first press of the user. It should return false when the key is hold pressed. Otherwise, the last status of the user is shown thousands of times on the screen.

I am trying to provide this functionality using win32api. GetAsyncKeyState seems like the right option for this scenario but I don't understand how this can be done.

bool IsPressed(int key) {
return GetAsyncKeyState(key) & 1 != 0;
}

The function I wrote acts like a char event.

How can I write this?

I tried using other answers on StackOwerflow. However, I could not find an answer to the question I asked. Still, these answers helped me with some issues:
What is the fastest way to determine a key press and key holding in Win32?

Body:
I do not know about C ++, but it certainly follows the same process in all languages, so you can set that pressure method to "if" and define a number that, by pressing its value, becomes one, And write. In "If" if the value of the number is equal to 1, do not do this again

In java, for example, it says:

int x = 0;
Button back = findViewById(R.id.button);
if(x == 0){
    back.setOnClickListener(v -> {
        //your code to do;
        x = 1;
    });
}else{}

that work in C++ too,


问:
Blazor WASM Load Data before Render Page
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

```<code>protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }
</code>```

Has someone an idea why this converting issues happen?

答:
Has someone an idea why this converting issues happen?

In your code CatagiesInit1 is a Task, it's not a List<CategorieDTO>.  You only get the List<CategorieDTO> when the task completes which you have no control over as you don't await the completion of the Task.  In all likelyhood, your sync code will run to completion before that happens.

If your CategoryService returns a Task then the code that handles it must be async code. You can't escape from the async world back into the sync world without consequencies.  If you want to live in the sync world then all the data  pipeline code also needs to be blocking sync code.

If I understand your comments correctly, you want nothing to render until a certain set of conditions are met.  If so add some standard Loading... component code to the page if it's page specific or App.razor if it's on initial load, or say MainLayout if it's application wide.

Here's a quick an dirty example:

```<code><Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        @if (Loaded)
        {
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        }
        else
        {
            <div class="m-2 p-5 bg-secondary text-white">
                <h3>Loading.....</h3>
            </div>
        }
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    private bool Loaded;

    protected override async Task OnInitializedAsync()
    {
        Loaded = false;
        // simulate getting the data first
        await Task.Delay(5000);
        Loaded = true;
    }
}
</code>```

Body:
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }

Has someone an idea why this converting issues happen?

Body:
Has someone an idea why this converting issues happen?

In your code CatagiesInit1 is a Task, it's not a List<CategorieDTO>.  You only get the List<CategorieDTO> when the task completes which you have no control over as you don't await the completion of the Task.  In all likelyhood, your sync code will run to completion before that happens.

If your CategoryService returns a Task then the code that handles it must be async code. You can't escape from the async world back into the sync world without consequencies.  If you want to live in the sync world then all the data  pipeline code also needs to be blocking sync code.

If I understand your comments correctly, you want nothing to render until a certain set of conditions are met.  If so add some standard Loading... component code to the page if it's page specific or App.razor if it's on initial load, or say MainLayout if it's application wide.

Here's a quick an dirty example:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        @if (Loaded)
        {
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        }
        else
        {
            <div class="m-2 p-5 bg-secondary text-white">
                <h3>Loading.....</h3>
            </div>
        }
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    private bool Loaded;

    protected override async Task OnInitializedAsync()
    {
        Loaded = false;
        // simulate getting the data first
        await Task.Delay(5000);
        Loaded = true;
    }
}


问:
Extract Image from PDF using Java
I need to extract bar-code from PDF only (using rectangle), not converting the whole PDF into image.

The image format can be jpg/png.

答:
PDFDecoder API from JPedal will help you extract the words.

```<code>// Decode the page
decodePdf.decodePage(page);

// Create the grouping object to apply grouping to the data
PdfGroupingAlgorithms currentGrouping = decodePdf.getGroupingObject();

// Bounding box for the whole page
PdfPageData currentPageData = decodePdf.getPdfPageData();
int x1 = currentPageData.getMediaBoxX(page);
int x2 = currentPageData.getMediaBoxWidth(page)+x1;
int y2 = currentPageData.getMediaBoxX(page);
int y1 = currentPageData.getMediaBoxHeight(page)-y2;

// Extract words
List words = currentGrouping.extractTextAsWordlist(x1, y1, x2, y2, page, true, "&:=()!;.,\\/\"\"\'\'");
</code>```

Now, iterate through the list for the words in PDF. Hope it works. Thanks!

Title: Extract Image from PDF using Java

Body:
PDFDecoder API from JPedal will help you extract the words.

// Decode the page
decodePdf.decodePage(page);

// Create the grouping object to apply grouping to the data
PdfGroupingAlgorithms currentGrouping = decodePdf.getGroupingObject();

// Bounding box for the whole page
PdfPageData currentPageData = decodePdf.getPdfPageData();
int x1 = currentPageData.getMediaBoxX(page);
int x2 = currentPageData.getMediaBoxWidth(page)+x1;
int y2 = currentPageData.getMediaBoxX(page);
int y1 = currentPageData.getMediaBoxHeight(page)-y2;

// Extract words
List words = currentGrouping.extractTextAsWordlist(x1, y1, x2, y2, page, true, "&:=()!;.,\\/\"\"\'\'");

Now, iterate through the list for the words in PDF. Hope it works. Thanks!


问:
Send an artifact (zip file) to source stage on AWS CodePipeline through Jenkins
is there any way of sending a zip file made on a Jenkins job to an AWS CodePipeline Source Stage, so the build gets triggered and passed to CodeBuild with the artifact made on the Jenkins job?</p>

答: In your CodePipeline, create a source action (Action Provider->Source->Amazon S3) pointing to a s3 bucket (and prefix?) and place your zip file in the configured S3 location.</p>


问:
How to solve this: TypeError: Cannot destructure property 'title' of 'collections' as it is undefined
This is the data that I fetched from firestore and I want to use it in my application to show the product details but I can't retrieve it into my application. Example, I want the data from shop->collections->bags->items to show the specific product details.

And here is my code in product-details.component.jsx:

```<code>import React, { useEffect, useState } from "react";
import { connect } from "react-redux";

import { fetchCollectionsStart } from '../../redux/shop/shop.actions'

const ProductDetailsPage = ({ fetchCollectionsStart, match, collections }) => {

    const {title, items} = collections;

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

    console.log(match);

    const ShowProduct = () => {
        return (
            <div>
                {title}
            </div>
        )
    }

    return (
        <div className='product-details'>
            <div className="row">
                <ShowProduct />
            </div>
        </div>
    );

};

const mapDispatchToProps = dispatch => ({
    fetchCollectionsStart: () => dispatch(fetchCollectionsStart())
});

export default connect(null, mapDispatchToProps)(ProductDetailsPage);
</code>```

The error pop up is shown as the image below:

I don't know why I can't destructure the data from collections. I thought I already successfully fetched it into my application?
Thanks a lot for helping me!!

答:
You need to destructure bags and then get the title from bags.

```<code>const { bags } = collections;
console.log(bags.title)
</code>```

If you dont know whats in collections - you can use Object.keys() to get the different object keys- bags, boys, girls, hats etc.

Body:
This is the data that I fetched from firestore and I want to use it in my application to show the product details but I can't retrieve it into my application. Example, I want the data from shop->collections->bags->items to show the specific product details.

And here is my code in product-details.component.jsx:

import React, { useEffect, useState } from "react";
import { connect } from "react-redux";

import { fetchCollectionsStart } from '../../redux/shop/shop.actions'

const ProductDetailsPage = ({ fetchCollectionsStart, match, collections }) => {

    const {title, items} = collections;

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

    console.log(match);

    const ShowProduct = () => {
        return (

                {title}

        )
    }

    return (

                <ShowProduct />

    );

};

const mapDispatchToProps = dispatch => ({
    fetchCollectionsStart: () => dispatch(fetchCollectionsStart())
});

export default connect(null, mapDispatchToProps)(ProductDetailsPage);

The error pop up is shown as the image below:

I don't know why I can't destructure the data from collections. I thought I already successfully fetched it into my application?
Thanks a lot for helping me!!

Body:
You need to destructure bags and then get the title from bags.

const { bags } = collections;
console.log(bags.title)

If you dont know whats in collections - you can use Object.keys() to get the different object keys- bags, boys, girls, hats etc.


问:
Sub-query works but would a join or other alternative be better?
I am trying to select rows from one table where the id referenced in those rows matches the unique id from another table that relates to it like so:

SELECT *
FROM booklet_tickets
WHERE bookletId = (SELECT id
                   FROM booklets
                   WHERE bookletNum = 2000
                     AND seasonId = 9
                     AND bookletTypeId = 3)
```

With the bookletNum/seasonId/bookletTypeId being filled in by a user form and inserted into the query.

This works and returns what I want but seems messy. Is a join better to use in this type of scenario?

答:
If there is even a possibility for your subquery to return multiple value you should use in instead:

```<code>SELECT *
FROM booklet_tickets
WHERE bookletId in (SELECT id
                    FROM booklets
                    WHERE bookletNum = 2000
                      AND seasonId = 9
                      AND bookletTypeId = 3)
</code>```

But I would prefer exists over in :

```<code>SELECT *
FROM booklet_tickets bt
WHERE EXISTS (SELECT 1
              FROM booklets b
              WHERE bookletNum = 2000
                AND seasonId = 9
                AND bookletTypeId = 3
                AND b.id = bt.bookletId)
</code>```

Body:
I am trying to select rows from one table where the id referenced in those rows matches the unique id from another table that relates to it like so:

SELECT *
FROM booklet_tickets
WHERE bookletId = (SELECT id
                   FROM booklets
                   WHERE bookletNum = 2000
                     AND seasonId = 9
                     AND bookletTypeId = 3)

With the bookletNum/seasonId/bookletTypeId being filled in by a user form and inserted into the query.

This works and returns what I want but seems messy. Is a join better to use in this type of scenario?

Body:
If there is even a possibility for your subquery to return multiple value you should use in instead:

SELECT *
FROM booklet_tickets
WHERE bookletId in (SELECT id
                    FROM booklets
                    WHERE bookletNum = 2000
                      AND seasonId = 9
                      AND bookletTypeId = 3)

But I would prefer exists over in :

SELECT *
FROM booklet_tickets bt
WHERE EXISTS (SELECT 1
              FROM booklets b
              WHERE bookletNum = 2000
                AND seasonId = 9
                AND bookletTypeId = 3
                AND b.id = bt.bookletId)


问:
Node async await function execution not in order
I'm confused. I'm new to async so I know I'm missing something fundamental but I'm scratching my head. From the examples I've seen, I thought I had this right but...

The below code works fine when mocked. However, when I fetch the real dashboard object from mongo I can see execution is not in order. Therefore the code that relies on there being a dashboard object fails due to it being 'undefined'.

Relevant code

```<code>router.get('/:id?', (req, res) => {
  getDashboardData(req)
})

async function getDashboardData(req) {
  const dashboardId = await getDashboardId(req)
  const dashboard = await loadDashboard(dashboardId)
  const results = await showResults(dashboardId, dashboard)
}

async function getDashboardId(req) {
  dashboardId = req.params.id.trim()
  // Some other things happen here but ultimately we return a UUID
  return(dashboardId)
}

async function loadDashboardFromId (dashboardId) {
  Dashboard.findOne({dashboardId: dashboardId}).then((dashboard) => {
    if (dashboard == null || dashboard.dashboardId == null) {
      throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
    } else {
      console.log('dashboard within loadDashboardFromId: ' + dashboard)
      return dashboard
    }
  })
}

async function showResults(dashboardId, dashboard) {
  console.log("dashboardId: " + dashboardId)
  console.log("dashboard within showResults: " + dashboard)
}
</code>```

Console output below. You can see showResults() executes before loadDashboard() returns:

```<code>connected to mongo server.
open connection to mongo server.
dashboardId: dbc7e954-c6a7-490f-8d9b-4dd11f11d262
dashboard within showResults: undefined
dashboard within loadDashboardFromId: {
  _id: new ObjectId("6208f552a442468c65987e62"),
  dashboardId: 'dbc7e954-c6a7-490f-8d9b-4dd11f11d262',
  createdDate: 2022-02-13T00:00:00.000Z,
  surveyId: 'b55a58d6-63f1-473e-9a3c-34f5d63af499',
  participantId: '9b274cfe-68ea-4206-9f3c-f2ee309ec4de',
  personalityTotal: new Decimal128("69"),
 // etc }```
```

答:
Don't mix up then/catch and await. Use either one or another. I'd prefer await:

async function loadDashboardFromId (dashboardId) {
  const dashboard = await Dashboard.findOne({dashboardId: dashboardId})
  if (dashboard == null || dashboard.dashboardId == null) {
    throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
  } else {
    console.log('dashboard within loadDashboardFromId: ' + dashboard)
    return dashboard
  }
}
```

Body:
I'm confused. I'm new to async so I know I'm missing something fundamental but I'm scratching my head. From the examples I've seen, I thought I had this right but...

The below code works fine when mocked. However, when I fetch the real dashboard object from mongo I can see execution is not in order. Therefore the code that relies on there being a dashboard object fails due to it being 'undefined'.

Relevant code

router.get('/:id?', (req, res) => {
  getDashboardData(req)
})

async function getDashboardData(req) {
  const dashboardId = await getDashboardId(req)
  const dashboard = await loadDashboard(dashboardId)
  const results = await showResults(dashboardId, dashboard)
}

async function getDashboardId(req) {
  dashboardId = req.params.id.trim()
  // Some other things happen here but ultimately we return a UUID
  return(dashboardId)
}

async function loadDashboardFromId (dashboardId) {
  Dashboard.findOne({dashboardId: dashboardId}).then((dashboard) => {
    if (dashboard == null || dashboard.dashboardId == null) {
      throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
    } else {
      console.log('dashboard within loadDashboardFromId: ' + dashboard)
      return dashboard
    }
  })
}

async function showResults(dashboardId, dashboard) {
  console.log("dashboardId: " + dashboardId)
  console.log("dashboard within showResults: " + dashboard)
}

Console output below. You can see showResults() executes before loadDashboard() returns:

connected to mongo server.
open connection to mongo server.
dashboardId: dbc7e954-c6a7-490f-8d9b-4dd11f11d262
dashboard within showResults: undefined
dashboard within loadDashboardFromId: {
  _id: new ObjectId("6208f552a442468c65987e62"),
  dashboardId: 'dbc7e954-c6a7-490f-8d9b-4dd11f11d262',
  createdDate: 2022-02-13T00:00:00.000Z,
  surveyId: 'b55a58d6-63f1-473e-9a3c-34f5d63af499',
  participantId: '9b274cfe-68ea-4206-9f3c-f2ee309ec4de',
  personalityTotal: new Decimal128("69"),
 // etc }```


问:
Microsoft Graph example snippets for JavaScript not working
I've been following this tutorial with this library, but the code snippets provided are producing errors. I have registered the app with Azure and followed the instructions, but when I run the code, it says SyntaxError: await is only valid in async functions and the top level bodies of modules at /script.js:74:20

Here's a relevant snippet of code, but if you have Replit, I would really appreciate it if you could collaborate with me on my Repl instead.

Replit link: https://replit.com/join/rgqcqfcohh-5pengoo

Code:

const msal = require('@azure/msal-node');

// Create msal application object
const cca = new msal.ConfidentialClientApplication(config);

const REDIRECT_URI = "http://localhost:3000/redirect";

const config = {
    auth: {
        clientId: "ebcb2e8c-4675-411f-a76e-25aafe0c026d",
        authority: "https://login.microsoftonline.com/98ca2106-858a-413a-b7d5-31301dcf9869/",
        // I wasn't sure if this meant the key value or the secret ID
        clientSecret: "ee10b5ce-f9c4-460a-a402-064030841f86"
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};

// 1st leg of auth code flow: acquire a code
app.get('/', (req, res) => {
    const authCodeUrlParameters = {
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    // get url to sign user in and consent to scopes needed for application
    pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
        res.redirect(response);
    }).catch((error) => console.log(JSON.stringify(error)));
});

// 2nd leg of auth code flow: exchange code for token
app.get('/redirect', (req, res) => {
    const tokenRequest = {
        code: req.query.code,
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    pca.acquireTokenByCode(tokenRequest).then((response) => {
        console.log("\nResponse: \n:", response);
        res.sendStatus(200);
    }).catch((error) => {
        console.log(error);
        res.status(500).send(error);
    });
});

try {
    let userDetails = await client.api("/me").get();
    console.log(userDetails);
} catch (error) {
    throw error;
}```

答:
MohammedMehtabSiddiqueMINDTREELIMI-9821 on the Microsoft Docs informed me that...

"You can use "await" only inside a function which is "async".

Here you can try remove 'await' from the code and try to run it"

and it worked!


问:
help with event click
I'm developing a html with this structure

```<code>div id="menuContainer">
    <div class = "menu ui-accordion-header ui-state-default ui-corner-all">
        <label class="formatText">Cliente</label><span class="ui-icon ui-icon-triangle-1-e menuIcon" style="float: right"></span>
            <div class = "subMenu ui-accordion-header ui-state-default ui-corner-all">
                <ul class="options">
                    <li>
                        <label class="formatText">Ver Cliente</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                <ul class="options">
                                    <li>
                                        <label class="formatText">Por Nombre</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                                <ul class="options">
                                                    <li><label class="formatText">sub sub menu</label></li>
                                                    <li><label class="formatText">prueba</label></li>
                                                </ul>
                                            </div>
                                    </li>
                                    <li>
                                        <label class="formatText">Por Campana</label>
                                    </li>
                                </ul>
                            </div>
                    </li>
                    <li>
                        <label class="formatText">Reportes para Cliente</label>
                    </li>
                </ul>
            </div>
    </div>
</div>
</code>```

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

```<code>$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});
</code>```

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

答:
You should definitely look here for an outline of different options.

false basically calls preventDefault and stopPropagation which will be treated on below.

preventDefault stops the default behavior of the event -- in this case, it could stop an anchor from firing. You won't be terribly concerned with this behavior in your current example as you aren't actually

event.stopPropagation Prevents parent nodes from "hearing" the event. It will, however, allow anchor tags to continue working. Unless you want a parent of .menu to listen to the event, this will do what you are looking for. It is technically the most correct in this case.

event.stopImmediatePropagation calls stopPropagation and then makes sure that all listeners which have been added after the listener which calls that event will not fire.

Title: help with event click

Body:
I'm developing a html with this structure

div id="menuContainer">

        Cliente

                        Ver Cliente

                                        Por Nombre

sub sub menu

prueba

                                        Por Campana

                        Reportes para Cliente

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??


问:
AnimatedContainer onTap animate once forward and back
https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html

The example flutter.dev takes one tap to animate to a different look, and one tap to animate back to the original.
I was wondering, what if I want it to animate once forward, hold one second, and then backwards on one tap. Can I use a Timer to achieve this or should I be using AnimationController instead?

答: The best choice would be using the AnimationController since it gives you more control over the object. One more important thing about using an AnimationController instead of a Timer is that the controller uses TickerProvider class for a more smooth start and ending animation.


问:
Python if...in.. statement. Check for vowel in word
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but  not all.

```<code>vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")
</code>```

This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]

any ideas how to check for e i o u at the same time?

答:
One way to keep track is also to have an existence list that keeps all vowels that exist in a word.

```<code>existence = []
vowels = ["a","e","i","o","u"]
test_word = "hello" # You can change this to receive input from user

for char in  test_word:
    if char in vowels:
        existence.append(char)
if existence and len(existence) > 0:
    for char in existence:
        print(f"These vowels exist in your input {test_word} - {char}")
else:
     print(f"There are no vowels existing in your input {test_word}")
</code>```

Output:

```<code>These vowels exist in your input hello - e
These vowels exist in your input hello - o
</code>```

Body:
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but  not all.

vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")

This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]

any ideas how to check for e i o u at the same time?

Body:
One way to keep track is also to have an existence list that keeps all vowels that exist in a word.

existence = []
vowels = ["a","e","i","o","u"]
test_word = "hello" # You can change this to receive input from user

for char in  test_word:
    if char in vowels:
        existence.append(char)
if existence and len(existence) > 0:
    for char in existence:
        print(f"These vowels exist in your input {test_word} - {char}")
else:
     print(f"There are no vowels existing in your input {test_word}")

Output:

These vowels exist in your input hello - e
These vowels exist in your input hello - o


问:
Excel formula, calculate product of values in each column of dynamic array
I'm working on a formula for a "result" column in a table that looks up data in another table based on some criteria in the main one, then displays it.  Of the point where I'm getting stumped at, it is returning a dynamic 2D array (row returns are variable dependent on an FILTER/MATCH lookup).  Example (4 columns x 3 rows) return value: {1,2,3,4;1,2,3,4;1,2,3,4}

I want to get the product of the values in each column such that the output from the formula using the example return value above would be this: {1,8,27,64}

(Which is the equivalent of doing this: {1,2,3,4} * {1,2,3,4} * {1,2,3,4})

How do I accomplish this using only formula functions?

All of my google searches have been coming back with methods that assume static table size, multiply the columns against each other, and/or the table "existing" within a sheet somewhere (and still don't give the result I'm looking for).

I've already figured this out via VBA, but due to the nature of how I'm using the sheet, waiting for the updates to run via VBA are too slow.  It's not that it takes forever - it's only about 3-4 seconds for ~60 rows - but rather that I make a change to my lookup table, wait for the update to the result column in the main table, check the results, make another change, rinse & repeat 50 some odd times while I fine tune things to look the way I want them to, and the delays are wearing on me.

I'm also unsure that I can use helper rows/columns as the results would need to be packed too close together and would just display #SPILL, which results in the formulas referencing it just showing the same thing.  So it looks like this needs to be self contained.

Plugins are an absolute no.

(Other little edit: Whoops, I put INDEX/MATCH above when I meant FILTER/MATCH.)

EDIT: Hopefully this will help clarify?

Here's the structure of my main table where this formula resides:

My Formula takes the words from ColA and ColB and uses FILTER/MATCH to do a lookup that 1) returns multiple results, 2) the return results are entire rows, and 3) is an exact match (it returns nothing for words in ColA and ColB that don't exist in the lookup table).

This means that, as of the current state of the formula, I'm getting 2D arrays back for most of the rows in the main table.  AFAICT, I'm not going to be able to stick these into a helper column somewhere as they'll overlap and just cause #SPILL which then won't evaluate in whatever formulas then reference them.

I need to turn these into 1D arrays that are 1 row x same-#-as-source columns where the result in each column is the product of only that column's contents.  I'm then going to continue building off from this formula with more formula to achieve my final result that will fit nicely in the single cell.  (I already have that piece solved.  It's just going from the 2D -> 1D product array I need help with.)

答:
=LET(z,MyArray,a,INDEX(z,,1),b,INDEX(z,,2),c,INDEX(z,,3),d,INDEX(z,,4),CHOOSE({1,2,3,4},PRODUCT(a),PRODUCT(b),PRODUCT(c),PRODUCT(d)))

where MyArray is the construction which returns your 2D array, e.g.

{1,2,3,4;1,2,3,4;1,2,3,4}

The above assumes that MyArray returns an array comprising 4 columns. For each additional column beyond that number, an additional name and calculation parameter will be required within the LET function. What's more, the array passed to CHOOSE should be adjusted such that it comprises an array of integers from 1 up to the number of columns returned by MyArray.

For example, if MyArray returned instead:

{1,2,3,4,5;1,2,3,4,5;1,2,3,4,5}

the required construction would be:

=LET(z,MyArray,a,INDEX(z,,1),b,INDEX(z,,2),c,INDEX(z,,3),d,INDEX(z,,4),e,INDEX(z,,5),CHOOSE({1,2,3,4,5},PRODUCT(a),PRODUCT(b),PRODUCT(c),PRODUCT(d),PRODUCT(e)))

Edit: better is to replace the static array passed to CHOOSE with a SEQUENCE construction:

=LET(z,MyArray,a,INDEX(z,,1),b,INDEX(z,,2),c,INDEX(z,,3),d,INDEX(z,,4),e,INDEX(z,,5),CHOOSE(SEQUENCE(,COLUMNS(z)),PRODUCT(a),PRODUCT(b),PRODUCT(c),PRODUCT(d),PRODUCT(e)))


问:
R adding a new column in a data frame by recursivly filling 1:3 value based on another column
I have a dataframe, e.g.:

```<code>df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C
</code>```

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

```<code>> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3
</code>```

I don't know how to achieve this. Thanks a lot for your help

答:
A base R approach:

df$Type <- ave(df$Group, df$Group, FUN = \(x) rep_len(1:3, length(x)))

df

#>    Group Type
#> 1      A    1
#> 2      A    2
#> 3      A    3
#> 4      A    1
#> 5      B    1
#> 6      B    2
#> 7      B    3
#> 8      B    1
#> 9      C    1
#> 10     C    2
#> 11     C    3
#> 12     C    1
#> 13     C    2
#> 14     C    3
```
<hr />
<p>Or using <code>dplyr</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)

df %>%
  mutate(Type = ave(Group, Group, FUN = \(x) rep_len(1:3, length(x))))

#>    Group Type
#> 1      A    1
#> 2      A    2
#> 3      A    3
#> 4      A    1
#> 5      B    1
#> 6      B    2
#> 7      B    3
#> 8      B    1
#> 9      C    1
#> 10     C    2
#> 11     C    3
#> 12     C    1
#> 13     C    2
#> 14     C    3
</code>```

Body:
I have a dataframe, e.g.:

df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3

I don't know how to achieve this. Thanks a lot for your help

Body:
A base R approach:

df$Type <- ave(df$Group, df$Group, FUN = \(x) rep_len(1:3, length(x)))

df

#>    Group Type
#> 1      A    1
#> 2      A    2
#> 3      A    3
#> 4      A    1
#> 5      B    1
#> 6      B    2
#> 7      B    3
#> 8      B    1
#> 9      C    1
#> 10     C    2
#> 11     C    3
#> 12     C    1
#> 13     C    2
#> 14     C    3

Or using dplyr:

library(dplyr)

df %>%
  mutate(Type = ave(Group, Group, FUN = \(x) rep_len(1:3, length(x))))

#>    Group Type
#> 1      A    1
#> 2      A    2
#> 3      A    3
#> 4      A    1
#> 5      B    1
#> 6      B    2
#> 7      B    3
#> 8      B    1
#> 9      C    1
#> 10     C    2
#> 11     C    3
#> 12     C    1
#> 13     C    2
#> 14     C    3


问:
How to create a dynamic calculation based off more than 1 State
I am brand new to Swift (and coding in general). I am working on an app that will output a calculation based off the tracking of two states. The two states are brewModel and waterAmount. I am able to successfully create a function that will return one calculation based on the two states. However, now I am trying to create a Picker that will toggle the calculation between two measurements - grams and tablespoons. This is where I am having trouble.

I tried to write a series of conditionals in different ways such as if and else if as well as switch cases, but it doesn't work. When I build the simulator, Xcode will just think for a long time until I stop it. Sometimes I get error messages after I manually stop it and sometimes I don't. Today I got "Command CompileSwiftSources failed with a nonzero exit code."

Does anyone have any suggestions?

Also, I apologize if my code is messy, I have a bunch of things commented out that I am playing with. The func computeGrinds does work but just for the one calculation. Thank you!

```<code>import SwiftUI

struct Water: View {
    //    @EnvironmentObject var favorites: Favorites
    @State var animationInProgress = true
    @State var brewModel: BrewModel
    @State var waterAmount: Int = 1

    @State var grindsSelection = "tbsp"
    var grindOptions = ["tbsp", "grams"]

    //    var resultGrindCalc: Double {
    //
    //        var value = Double(0)
    //    }
    //    switch grindsSelection {
    //    case "tbsp" || brewModel.frenchPress:
    //        value = Double(waterAmount) * 2.5
    //
    //    }
    //

//    func computeGrinds () -> Double {
//        switch brewModel {
//        case .frenchPress, .chemex:
//            return (2.5 * Double(waterAmount))
//        case .drip :
//            return Double(2 * Double(waterAmount))
//        case .mokaPot:
//            return Double(1 * Double(waterAmount))
//        case .aeroPress:
//            return Double(1.6 * Double(waterAmount))
//            //        default:
//            //            return(1 * Double(waterAmount))
//        }
//    }
    var body: some View {
        VStack (spacing: 5) {
            Spacer()
            HStack {
                //                Text("").padding(20)
                Text("How many cups do you want to brew?")

                Picker("", selection: $waterAmount) {
                    ForEach(1...15, id: \.self){
                        Text("\($0)")
                    }
                }
                //                Spacer()
            }.padding()
                .overlay (
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(Color("Custom Color"), lineWidth: 8)
                )

            //            gif/image conditionals
            if (brewModel == .frenchPress) {
                LottieView(name: "frenchpress", loopMode: .loop)
            } else if brewModel == .chemex {
                LottieView(name: "pourover", loopMode: .loop)
            } else if brewModel == .aeroPress {
                LottieView(name: "aeropress", loopMode: .loop)
            } else if brewModel == .mokaPot {
                LottieView(name: "mokapot", loopMode: .loop)
            } else if brewModel == .drip {
                Image("Drip")
                    .resizable()
                    .scaledToFit()
            }
            // I would have more conditionals but testing with just these two for now
            var testingCalcCond = Double
            if (brewModel == .frenchPress)||(grindsSelection=="tbsp") {
                testingCalcCond = (2.5 * Double(waterAmount))
            } else if (brewModel == .frenchPress)||(grindsSelection=="grams") {
                testingCalcCond = (16 * Double(waterAmount))
            }

            let formatted = String(format: "%.2f", testingCalcCond)
//            let formatted = String(format: "%.2f", computeGrinds())

            HStack {
                Text("**\(formatted)**")
                Picker("Select Grinds Units: ", selection: $grindsSelection, content: {
                    ForEach(grindOptions, id: \.self) {
                        Text($0)
                    }
                }).onChange(of: grindsSelection) { _ in    computeGrinds()  }
                Text("of coffee grinds needed")

            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color("Custom Color"), lineWidth: 8)
            )

        }
        Spacer()
    }
}

struct Water_Previews: PreviewProvider {
    static var previews: some View {
           Water(brewModel: .drip)
        }
    }
}
</code>```

*I'm using Xcode 13.2.1
*I'm using swiftUI

答:
There are 2 aspects you want to think over:

1. How to update the result value based on the inputs.

Your result value is based on two inputs: brewModel and waterAmount. Both are @State vars and changed by a picker.
I changed your computeGrinds func to a computed property, because this will be automatically called when one of the two base values changes. Then there is no need for .onchange anymore, you can just use the var value – it will always be up to date.

2. recalculating from tbsp to grams.

This is more of a math thing: As I understand, for .frenchPress you need either 2.5 tbsp – or 16 grams per cup. So 1 tbsp = 16 / 2.5 = 6.4 grams. Once you know that you just have to go through the switch case once, and use the unitValue to recalculate. I integrated that too ;)

Here is my simplified code:

```<code>enum BrewModel {
    case frenchPress
    case chemex
    case drip
    case mokaPot
    case aeroPress
}

struct ContentView: View {

    @State var animationInProgress = true
    @State var brewModel: BrewModel = .frenchPress
    @State var waterAmount: Int = 1

    @State var grindsSelection = "tbsp"
    let grindOptions = ["tbsp", "grams"]

    // computed var instead of func, does the same
    var computeGrinds: Double {

        // transforms tbsp = 1 to grams (= 6.4 ?)
        var unitValue: Double = 1.0
        if grindsSelection == "grams" {
            unitValue = 6.4
        }

        switch brewModel {
        case .frenchPress, .chemex:
            return (2.5 * unitValue * Double(waterAmount))
        case .drip :
            return Double(2 * unitValue * Double(waterAmount))
        case .mokaPot:
            return Double(1 * unitValue * Double(waterAmount))
        case .aeroPress:
            return Double(1.6 * unitValue * Double(waterAmount))
        }
    }

    var body: some View {
        VStack (spacing: 5) {
            HStack {
                Text("How many cups do you want to brew?")

                Picker("", selection: $waterAmount) {
                    ForEach(1...15, id: \.self){
                        Text("\($0)")
                    }
                }
            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color.brown, lineWidth: 8)
            )
            .padding(.bottom)

            let formatted = String(format: "%.2f", computeGrinds)

            HStack {
                Text("**\(formatted)**")
                Picker("Select Grinds Units: ", selection: $grindsSelection, content: {
                    ForEach(grindOptions, id: \.self) {
                        Text($0)
                    }
                })

                Text("of coffee grinds needed")

            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color.brown, lineWidth: 8)
            )
        }
    }
}
</code>```

Body:
I am brand new to Swift (and coding in general). I am working on an app that will output a calculation based off the tracking of two states. The two states are brewModel and waterAmount. I am able to successfully create a function that will return one calculation based on the two states. However, now I am trying to create a Picker that will toggle the calculation between two measurements - grams and tablespoons. This is where I am having trouble.

I tried to write a series of conditionals in different ways such as if and else if as well as switch cases, but it doesn't work. When I build the simulator, Xcode will just think for a long time until I stop it. Sometimes I get error messages after I manually stop it and sometimes I don't. Today I got "Command CompileSwiftSources failed with a nonzero exit code."

Does anyone have any suggestions?

Also, I apologize if my code is messy, I have a bunch of things commented out that I am playing with. The func computeGrinds does work but just for the one calculation. Thank you!

import SwiftUI

struct Water: View {
    //    @EnvironmentObject var favorites: Favorites
    @State var animationInProgress = true
    @State var brewModel: BrewModel
    @State var waterAmount: Int = 1

    @State var grindsSelection = "tbsp"
    var grindOptions = ["tbsp", "grams"]

    //    var resultGrindCalc: Double {
    //
    //        var value = Double(0)
    //    }
    //    switch grindsSelection {
    //    case "tbsp" || brewModel.frenchPress:
    //        value = Double(waterAmount) * 2.5
    //
    //    }
    //

//    func computeGrinds () -> Double {
//        switch brewModel {
//        case .frenchPress, .chemex:
//            return (2.5 * Double(waterAmount))
//        case .drip :
//            return Double(2 * Double(waterAmount))
//        case .mokaPot:
//            return Double(1 * Double(waterAmount))
//        case .aeroPress:
//            return Double(1.6 * Double(waterAmount))
//            //        default:
//            //            return(1 * Double(waterAmount))
//        }
//    }
    var body: some View {
        VStack (spacing: 5) {
            Spacer()
            HStack {
                //                Text("").padding(20)
                Text("How many cups do you want to brew?")

                Picker("", selection: $waterAmount) {
                    ForEach(1...15, id: \.self){
                        Text("\($0)")
                    }
                }
                //                Spacer()
            }.padding()
                .overlay (
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(Color("Custom Color"), lineWidth: 8)
                )

            //            gif/image conditionals
            if (brewModel == .frenchPress) {
                LottieView(name: "frenchpress", loopMode: .loop)
            } else if brewModel == .chemex {
                LottieView(name: "pourover", loopMode: .loop)
            } else if brewModel == .aeroPress {
                LottieView(name: "aeropress", loopMode: .loop)
            } else if brewModel == .mokaPot {
                LottieView(name: "mokapot", loopMode: .loop)
            } else if brewModel == .drip {
                Image("Drip")
                    .resizable()
                    .scaledToFit()
            }
            // I would have more conditionals but testing with just these two for now
            var testingCalcCond = Double
            if (brewModel == .frenchPress)||(grindsSelection=="tbsp") {
                testingCalcCond = (2.5 * Double(waterAmount))
            } else if (brewModel == .frenchPress)||(grindsSelection=="grams") {
                testingCalcCond = (16 * Double(waterAmount))
            }

            let formatted = String(format: "%.2f", testingCalcCond)
//            let formatted = String(format: "%.2f", computeGrinds())

            HStack {
                Text("**\(formatted)**")
                Picker("Select Grinds Units: ", selection: $grindsSelection, content: {
                    ForEach(grindOptions, id: \.self) {
                        Text($0)
                    }
                }).onChange(of: grindsSelection) { _ in    computeGrinds()  }
                Text("of coffee grinds needed")

            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color("Custom Color"), lineWidth: 8)
            )

        }
        Spacer()
    }
}

struct Water_Previews: PreviewProvider {
    static var previews: some View {
           Water(brewModel: .drip)
        }
    }
}

*I'm using Xcode 13.2.1
*I'm using swiftUI

Body:
There are 2 aspects you want to think over:

1. How to update the result value based on the inputs.

Your result value is based on two inputs: brewModel and waterAmount. Both are @State vars and changed by a picker.
I changed your computeGrinds func to a computed property, because this will be automatically called when one of the two base values changes. Then there is no need for .onchange anymore, you can just use the var value – it will always be up to date.

2. recalculating from tbsp to grams.

This is more of a math thing: As I understand, for .frenchPress you need either 2.5 tbsp – or 16 grams per cup. So 1 tbsp = 16 / 2.5 = 6.4 grams. Once you know that you just have to go through the switch case once, and use the unitValue to recalculate. I integrated that too ;)

Here is my simplified code:

enum BrewModel {
    case frenchPress
    case chemex
    case drip
    case mokaPot
    case aeroPress
}

struct ContentView: View {

    @State var animationInProgress = true
    @State var brewModel: BrewModel = .frenchPress
    @State var waterAmount: Int = 1

    @State var grindsSelection = "tbsp"
    let grindOptions = ["tbsp", "grams"]

    // computed var instead of func, does the same
    var computeGrinds: Double {

        // transforms tbsp = 1 to grams (= 6.4 ?)
        var unitValue: Double = 1.0
        if grindsSelection == "grams" {
            unitValue = 6.4
        }

        switch brewModel {
        case .frenchPress, .chemex:
            return (2.5 * unitValue * Double(waterAmount))
        case .drip :
            return Double(2 * unitValue * Double(waterAmount))
        case .mokaPot:
            return Double(1 * unitValue * Double(waterAmount))
        case .aeroPress:
            return Double(1.6 * unitValue * Double(waterAmount))
        }
    }

    var body: some View {
        VStack (spacing: 5) {
            HStack {
                Text("How many cups do you want to brew?")

                Picker("", selection: $waterAmount) {
                    ForEach(1...15, id: \.self){
                        Text("\($0)")
                    }
                }
            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color.brown, lineWidth: 8)
            )
            .padding(.bottom)

            let formatted = String(format: "%.2f", computeGrinds)

            HStack {
                Text("**\(formatted)**")
                Picker("Select Grinds Units: ", selection: $grindsSelection, content: {
                    ForEach(grindOptions, id: \.self) {
                        Text($0)
                    }
                })

                Text("of coffee grinds needed")

            }
            .padding()
            .overlay (
                RoundedRectangle(cornerRadius: 16)
                    .stroke(Color.brown, lineWidth: 8)
            )
        }
    }
}


问:
How to hide the Join the beta message from my store listing in Google Play?
So far I've tried pausing the only Open testing track I have and unsyncing all countries. Couldn't find any information on the topic in the official documentation. Does anyone know how to do it?

Many thanks for your time.

答: Two weeks after pausing the Open testing track and unsyncing all countries the message is not there anymore, so, if anyone is having the same issue I'd advise to do the same. Thanks and good luck with your apps!</p>


问:
fitting on X_train and y_train
For somebody super beginner how can one remember what to pass into model.fit?
I have to keep on looking up that we are supposed to pass X_train, y_train.
But I guess I don't fully understand why we don't pass in something else such as:
X_train, y_test.

Thank you!
Josh

答: Passing X_train and y_test will result in a data mismatch: once you have splitted your data in training and test set (here's why you do it and some ways to do that), you will have the output/label of your X_train in your y_train, and that goes the same for your test set.</p>

Title: fitting on X_train and y_train


答:
A regular expression can tell you not only if there's a vowel in a string, but which vowels and their order.</p>
```<code>>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']
</code>```

Title: Python if...in.. statement. Check for vowel in word

Body:
A regular expression can tell you not only if there's a vowel in a string, but which vowels and their order.

>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']


问:
Adding number to beginning of integer
I know that this may be a dumb question, but I am still learning C so I don't know all the nuances.

Basically the gist of my question is that say I have the separate integers 1, 3 and 2. I want to add 2 to 1 that makes it 21. I know I could do 2*10, then add 1. Then add 3 to the beginning making it 321. Basically I need to add one number to the beginning of another number multiple times. Sadly, I cannot use the pow function for this.

Let me know if you need me to explain it anymore.

答:
There is many ways you can do this.

If you can't use the pow function why not make your own?

Here is one way I thought of doing this. I hope this can inspire you to come up with your own way.

If you need more then 10 digits you would have to use long instead of int.

```<code>#include <stdio.h>

int notpow(int y) {
    int ans = 10;
    if (y == 0) {
        return 1;
    }
    for (int i = 1; i < y; i++) {
        ans *= 10;
    }
    return ans;
}

int main() {
    // //Basic idea
    int num1 = 1;
    int num2 = 3;
    int num3 = 2;
    int ans = 0;
    ans = num1*notpow(2) + num2 *notpow(1) + num3*notpow(0);
    printf("ans = %i\n", ans);
    //For n numbers
    int howMany, howManyCount = 1;
    printf("How many digits?: ");
    scanf("%d",&howMany);
    int temp = 0;
    int countDown = howMany-1;
    ans = 0;
    printf("\n");
    for (int i = 0; i < howMany; i++) {
        printf("Enter digit %i: ", (i+1));
        scanf("%d",&temp);
        printf("\n");
        ans = ans + temp*notpow(countDown--);
        printf("ans = %i\n", ans);
    }
    printf("Final ans = %i\n", ans);
    return 0;
}
</code>```

Title: Adding number to beginning of integer

Body:
There is many ways you can do this.

If you can't use the pow function why not make your own?

Here is one way I thought of doing this. I hope this can inspire you to come up with your own way.

If you need more then 10 digits you would have to use long instead of int.

#include <stdio.h>

int notpow(int y) {
    int ans = 10;
    if (y == 0) {
        return 1;
    }
    for (int i = 1; i < y; i++) {
        ans *= 10;
    }
    return ans;
}

int main() {
    // //Basic idea
    int num1 = 1;
    int num2 = 3;
    int num3 = 2;
    int ans = 0;
    ans = num1*notpow(2) + num2 *notpow(1) + num3*notpow(0);
    printf("ans = %i\n", ans);
    //For n numbers
    int howMany, howManyCount = 1;
    printf("How many digits?: ");
    scanf("%d",&howMany);
    int temp = 0;
    int countDown = howMany-1;
    ans = 0;
    printf("\n");
    for (int i = 0; i < howMany; i++) {
        printf("Enter digit %i: ", (i+1));
        scanf("%d",&temp);
        printf("\n");
        ans = ans + temp*notpow(countDown--);
        printf("ans = %i\n", ans);
    }
    printf("Final ans = %i\n", ans);
    return 0;
}


问:
port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p]
I try to run the azure function app (Http Triggerd API) from my local (using VS code). But I'm getting an error "port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p]." I checked the list of ports used using cmd prompt.But 7071 is not in used list. Also tried to run with different port using "func host start --port [p1]", but it throws the same error as above. For all ports it throws the same error. How to resolve this problem?</p>

答:
This happened to me in linux environment, while trying to run a azure function locally from inside eclipse. turns out that terminating the process from inside the eclipse console DOES NOT kill the process, hence the port being used (7071) is not released till the machine is restarted.
Here the detective work needed to figure out if this is the case (linux only):

Run the following command to find out if the port is indeed occupied

sudo lsof -i -P -n | grep LISTEN

In my case, the output looked like this:

```<code>func      11421 s-----v  261u  IPv4 105109      0t0  TCP 127.0.0.1:44367 (LISTEN)
func      11421 s-----v  293u  IPv4 103143      0t0  TCP *:7071 (LISTEN)
</code>```

If you see this, it means the process holding 7071 needs to be killed. For doing so, first find the process id for the process that is holding up the ports, like so:

ps -ef | grep func | grep -v grep

This will give you the process id to be killed, the output may look something like this:

```<code>s-----v  14517     1  6 12:36 ?        00:00:05 func host start
s-----v  14832 14517 11 12:38 ?        00:00:00 /usr/lib/jvm/jdk-17/bin/java -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -noverify -Djava.net.preferIPv4Stack=true -jar /usr/lib/azure-functions-core-tools-4/workers/java/azure-functions-java-worker.jar --host 127.0.0.1 --port 34867 --workerId 1298e58c-8104-4c98-b440-f617b8f6943d --requestId c01f56cd-a29c-4ba6-b147-f2a15ea7c4d6 --grpcMaxMessageLength 2147483647
</code>```

next, issue kill on the two process IDs, like so:

kill -9 14517 14832

that should do it!

Body:
This happened to me in linux environment, while trying to run a azure function locally from inside eclipse. turns out that terminating the process from inside the eclipse console DOES NOT kill the process, hence the port being used (7071) is not released till the machine is restarted.
Here the detective work needed to figure out if this is the case (linux only):

Run the following command to find out if the port is indeed occupied

sudo lsof -i -P -n | grep LISTEN

In my case, the output looked like this:

func      11421 s-----v  261u  IPv4 105109      0t0  TCP 127.0.0.1:44367 (LISTEN)
func      11421 s-----v  293u  IPv4 103143      0t0  TCP *:7071 (LISTEN)

If you see this, it means the process holding 7071 needs to be killed. For doing so, first find the process id for the process that is holding up the ports, like so:

ps -ef | grep func | grep -v grep

This will give you the process id to be killed, the output may look something like this:

s-----v  14517     1  6 12:36 ?        00:00:05 func host start
s-----v  14832 14517 11 12:38 ?        00:00:00 /usr/lib/jvm/jdk-17/bin/java -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -noverify -Djava.net.preferIPv4Stack=true -jar /usr/lib/azure-functions-core-tools-4/workers/java/azure-functions-java-worker.jar --host 127.0.0.1 --port 34867 --workerId 1298e58c-8104-4c98-b440-f617b8f6943d --requestId c01f56cd-a29c-4ba6-b147-f2a15ea7c4d6 --grpcMaxMessageLength 2147483647

next, issue kill on the two process IDs, like so:

kill -9 14517 14832

that should do it!


问:
NSInvalidArgumentException: nil is not a valid object ID
My app currently uses a NavigationLink to open a view like this:

```<code>LazyVGrid(columns: gridLayout, spacing: 10) {
   ForEach(Array(person.project! as! Set<Project>).sorted { $0.date! > $1.date! }, id: \.self) { (project: Project) in
      NavigationLink(destination: ProjectDetailView(project: project, rootIsActive: self.$isActive)) {
         Image(uiImage: UIImage(data: project.image1 ?? self.projectImage1)! )
    ...
</code>```

However to improve the flow of the UI, I'd like to use a Sheet instead of NavigationLink to show ProjectDetailView

So I changed it like this:

```<code>LazyVGrid(columns: gridLayout, spacing: 10) {
   ForEach(Array(person.project! as! Set<Project>).sorted { $0.date! > $1.date! }, id: \.self) { (project: Project) in
      Image(uiImage: UIImage(data: project.image1 ?? self.projectImage1)! )
         .onTapGesture(count: 1) { sheet = .imageTap(project) }
}
</code>```

where imageTap is added to my sheet enum at the top:

```<code>enum Sheet { case imageTap(Project) }
@State var sheet: Sheet? = nil
</code>```

and my sheet modifier passes the objectID of project to the view:

```<code>.sheet(using: $sheet) { sheet in
   switch sheet {
      case .imageTap:
         ProjectDetailView(id: project.objectID, in: viewContext)
</code>```

In my ProjectDetailView I've defined my @ObservedObject and initialized like this:

```<code>    @Environment(\.managedObjectContext) private var viewContext
    @ObservedObject var project: Project
    init(id objectID: NSManagedObjectID, in context: NSManagedObjectContext) {
        if let project = try? context.existingObject(with: objectID) as? Project {
            self.project = project
            self._image1 = State(wrappedValue: project.image1!)
            self._image2 = State(wrappedValue: project.image2 ?? self.image2)
            self._image3 = State(wrappedValue: project.image3 ?? self.image3)
            self._image4 = State(wrappedValue: project.image4 ?? self.image4)
            self._fav = State(wrappedValue: project.favorite)
        } else {
            self.project = Project(context: context)
            try? context.save()
        }
    }
</code>```

I'm expecting the objectID to be passed into this view when I invoke the onTapGesture on the image. However Xcode errors at this point with
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'nil is not a valid object ID'

I'm using this same method of passing objectID to edit a Person entity (my app has two core data entities: Person and Project), though it doesn't use a ForEach. It's just a .toolbar button and it works as expected. So I had it print the person.ObjectID and it looked like this:
0x8ae3a33c4ba2adf9 <x-coredata://468DD15D-71D2-4990-BD8B-01CAA9786420/Person/p5>

So I went and had it print the project.ObjectID upon tapping the image, and it prints a similar string that looks valid to me:
0x8ae3a33c49e2add9 <x-coredata://468DD15D-71D2-4990-BD8B-01CAA9786420/Project/p23>

So I'm pretty confused as to why ProjectDetailView is receiving a nil value when printing the objectID upon invoking imageTap produces a valid looking objectID

Any ideas? Thanks!!

答:
(As discussed in the comments above)

I'm not sure which instance of project you're referencing on the line ProjectDetailView(id: project.objectID, in: viewContext) or in what scope it exists, but instead, you should be using the associated value in the enum that you set when you do sheet = .imageTap(project).

In that case, the prior line should be: case let .imageTap(project): instead of case .imageTap.

Body:
My app currently uses a NavigationLink to open a view like this:

LazyVGrid(columns: gridLayout, spacing: 10) {
   ForEach(Array(person.project! as! Set<Project>).sorted { $0.date! > $1.date! }, id: \.self) { (project: Project) in
      NavigationLink(destination: ProjectDetailView(project: project, rootIsActive: self.$isActive)) {
         Image(uiImage: UIImage(data: project.image1 ?? self.projectImage1)! )
    ...

However to improve the flow of the UI, I'd like to use a Sheet instead of NavigationLink to show ProjectDetailView

So I changed it like this:

LazyVGrid(columns: gridLayout, spacing: 10) {
   ForEach(Array(person.project! as! Set<Project>).sorted { $0.date! > $1.date! }, id: \.self) { (project: Project) in
      Image(uiImage: UIImage(data: project.image1 ?? self.projectImage1)! )
         .onTapGesture(count: 1) { sheet = .imageTap(project) }
}

where imageTap is added to my sheet enum at the top:

enum Sheet { case imageTap(Project) }
@State var sheet: Sheet? = nil

and my sheet modifier passes the objectID of project to the view:

.sheet(using: $sheet) { sheet in
   switch sheet {
      case .imageTap:
         ProjectDetailView(id: project.objectID, in: viewContext)

In my ProjectDetailView I've defined my @ObservedObject and initialized like this:

    @Environment(\.managedObjectContext) private var viewContext
    @ObservedObject var project: Project
    init(id objectID: NSManagedObjectID, in context: NSManagedObjectContext) {
        if let project = try? context.existingObject(with: objectID) as? Project {
            self.project = project
            self._image1 = State(wrappedValue: project.image1!)
            self._image2 = State(wrappedValue: project.image2 ?? self.image2)
            self._image3 = State(wrappedValue: project.image3 ?? self.image3)
            self._image4 = State(wrappedValue: project.image4 ?? self.image4)
            self._fav = State(wrappedValue: project.favorite)
        } else {
            self.project = Project(context: context)
            try? context.save()
        }
    }

I'm expecting the objectID to be passed into this view when I invoke the onTapGesture on the image. However Xcode errors at this point with
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'nil is not a valid object ID'

I'm using this same method of passing objectID to edit a Person entity (my app has two core data entities: Person and Project), though it doesn't use a ForEach. It's just a .toolbar button and it works as expected. So I had it print the person.ObjectID and it looked like this:
0x8ae3a33c4ba2adf9 <x-coredata://468DD15D-71D2-4990-BD8B-01CAA9786420/Person/p5>

So I went and had it print the project.ObjectID upon tapping the image, and it prints a similar string that looks valid to me:
0x8ae3a33c49e2add9 <x-coredata://468DD15D-71D2-4990-BD8B-01CAA9786420/Project/p23>

So I'm pretty confused as to why ProjectDetailView is receiving a nil value when printing the objectID upon invoking imageTap produces a valid looking objectID

Any ideas? Thanks!!


问:
How do I combine 2 SELECT statements where the result
How do I combine 2 SELECT statements where the result of the first select is used in the WHERE of the second SELECT

Below is the code I am using right now:

```<code>$order_id = 7655;

$first  = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM wp_postmeta WHERE meta_key = '_ticket_order' AND meta_value = %d", $order_id ) );

if ( $first ) {
  $second = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_ticket_event' AND post_id = %d", $first ) );
}

echo $second;
</code>```

答:
You could try using a join between the two queries</p>
```<code>$second = $wpdb->get_var( $wpdb->prepare("SELECT b.meta_value
FROM wp_postmeta a
INNER JOIN wp_postmeta b ON a.post_id = b.post_id
WHERE a.meta_key = '_ticket_order' AND a.meta_value = %d", $order_id ) );
</code>```

Body:
How do I combine 2 SELECT statements where the result of the first select is used in the WHERE of the second SELECT

Below is the code I am using right now:

$order_id = 7655;

$first  = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM wp_postmeta WHERE meta_key = '_ticket_order' AND meta_value = %d", $order_id ) );

if ( $first ) {
  $second = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_ticket_event' AND post_id = %d", $first ) );
}

echo $second;

Body:
You could try using a join between the two queries

$second = $wpdb->get_var( $wpdb->prepare("SELECT b.meta_value
FROM wp_postmeta a
INNER JOIN wp_postmeta b ON a.post_id = b.post_id
WHERE a.meta_key = '_ticket_order' AND a.meta_value = %d", $order_id ) );


问:
Polymorphic association foreign_type sets ancestor type instead current, using STI class
I have

```<code>class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end
</code>```

I have to mention that I'm using a single table called cars which has a field type.

```<code>class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end
</code>```

When I do

```<code>  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"
</code>```

And it should be

```<code>  a.itemable_type
  => "Porsche"
</code>```

Do anybody have an idea about this?

Update

According to bor1s's answer probably this is the right behaviour. So if is it, then my question is how can I set it to Porsche implicitly?

答:
I think if you add type field to the Car table, you'll be able to get Porsche type using :
  PageItem.new(:itemable => Porsche.new).itemable.type

Body:
I have

class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end

I have to mention that I'm using a single table called cars which has a field type.

class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end

When I do

  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"

And it should be

  a.itemable_type
  => "Porsche"

Do anybody have an idea about this?

Update

According to bor1s's answer probably this is the right behaviour. So if is it, then my question is how can I set it to Porsche implicitly?


问:
Screenshot specific window in background without saving it as file
I would like to screenshot window in the background (not focused) without saving it as a file so it would be only as a variable. I have code that can screenshot the window but it will save it as .bmp. I can open it with pillow than but it would be better if it was saved in a variable instead of a file.
This is the code I use for the screenshot. I than open it with Image.open("imagename")</p>
```<code>def background_screenshot(hwnd, width, height):
        wDC = win32gui.GetWindowDC(hwnd)
        dcObj=win32ui.CreateDCFromHandle(wDC)
        cDC=dcObj.CreateCompatibleDC()
        dataBitMap = win32ui.CreateBitmap()
        dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
        cDC.SelectObject(dataBitMap)
        cDC.BitBlt((0,0), (width, height), dcObj, (0,0), win32con.SRCCOPY)
        dataBitMap.SaveBitmapFile(cDC, "images\\screenshot.bmp")
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, wDC)
        win32gui.DeleteObject(dataBitMap.GetHandle())
</code>```

答:
You can try this, and replace the 'take screenshot' function with your.

```<code>import mss import mss.tools
with mss.mss() as sct: # Use the 1st monitor
monitor = sct.monitors[1]
# Grab the picture
im = sct.grab(monitor)
# From now, you have access to different attributes like `rgb`
# See https://python-mss.readthedocs.io/api.html
# mss.tools.ScreenShot.rgb
# `im.rgb` contains bytes of the screen shot in RGB _but_ you will have to
# build the complete image because it does not set needed headers/structures
# for PNG, JPEG or any picture format.
# You can find the `to_png()` function that does this work for you,
# you can create your own, just take inspiration here:
# https://github.com/BoboTiG/python-mss/blob/master/mss/tools.py#L11
# If you would use that function, it is dead simple:
# args are (raw_data: bytes, (width, height): tuple, output: str)
Raw_bytes = mss.tools.to_png(im.rgb, im)
</code>```

Or you can save the file and write a function that automatically deltes it after use.

```<code>os.remove(filepath)
</code>```

Body:
I would like to screenshot window in the background (not focused) without saving it as a file so it would be only as a variable. I have code that can screenshot the window but it will save it as .bmp. I can open it with pillow than but it would be better if it was saved in a variable instead of a file.
This is the code I use for the screenshot. I than open it with Image.open("imagename")

def background_screenshot(hwnd, width, height):
        wDC = win32gui.GetWindowDC(hwnd)
        dcObj=win32ui.CreateDCFromHandle(wDC)
        cDC=dcObj.CreateCompatibleDC()
        dataBitMap = win32ui.CreateBitmap()
        dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
        cDC.SelectObject(dataBitMap)
        cDC.BitBlt((0,0), (width, height), dcObj, (0,0), win32con.SRCCOPY)
        dataBitMap.SaveBitmapFile(cDC, "images\\screenshot.bmp")
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, wDC)
        win32gui.DeleteObject(dataBitMap.GetHandle())

Body:
You can try this, and replace the 'take screenshot' function with your.

import mss import mss.tools
with mss.mss() as sct: # Use the 1st monitor
monitor = sct.monitors[1]
# Grab the picture
im = sct.grab(monitor)
# From now, you have access to different attributes like `rgb`
# See https://python-mss.readthedocs.io/api.html
# mss.tools.ScreenShot.rgb
# `im.rgb` contains bytes of the screen shot in RGB _but_ you will have to
# build the complete image because it does not set needed headers/structures
# for PNG, JPEG or any picture format.
# You can find the `to_png()` function that does this work for you,
# you can create your own, just take inspiration here:
# https://github.com/BoboTiG/python-mss/blob/master/mss/tools.py#L11
# If you would use that function, it is dead simple:
# args are (raw_data: bytes, (width, height): tuple, output: str)
Raw_bytes = mss.tools.to_png(im.rgb, im)

Or you can save the file and write a function that automatically deltes it after use.

os.remove(filepath)


问:
Extract specific columns and rows from an R dataset creating a new excell file
I'm writing the thesis for my master's degree I should create time series from the covid data of my country, Italy. The data is taken from here:
dataset italy
'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv" from this dataset I would like to have a new excel file that contains only the columns with the date, the denomination of the region, and the total number of deaths. From here I then go on to create the time series for every single Italian region. I hope I explained myself well, thank you very much for your help.
the program used R studio</p>

Body:
library(data.table)
url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv"
data = fread(url)[,.(data,denominazione_regione,deceduti)]

Ouput

> data
                      data denominazione_regione deceduti
    1: 2020-02-24 18:00:00               Abruzzo        0
    2: 2020-02-24 18:00:00            Basilicata        0
    3: 2020-02-24 18:00:00              Calabria        0
    4: 2020-02-24 18:00:00              Campania        0
    5: 2020-02-24 18:00:00        Emilia-Romagna        0
   ---
15137: 2022-02-13 17:00:00               Sicilia     9036
15138: 2022-02-13 17:00:00               Toscana     8637
15139: 2022-02-13 17:00:00                Umbria     1692
15140: 2022-02-13 17:00:00         Valle d'Aosta      514
15141: 2022-02-13 17:00:00                Veneto    13560