问:
Using torch.distributed modules on AWS instance to parallelise model training by splitting model
I am wondering how to do model parallelism using pytorch's distributed modules. Basically what I want to do is the following -

class LargeModel(nn.Module):
    def __init__(self, in_features, n_hid, out_features) -> None:
        super().__init__()
        self.to_train_locally = nn.Linear(in_features, n_hid)
        self.to_train_on_aws = nn.Linear(n_hid, out_features)

    def forward(self, input):
        intermediate = self.to_train_locally(input)
        res = send_to_aws_for_forward_pass(self.to_train_on_aws, intermediate)
        return res

```
<p>basically, I want to train a "large" model, which I want to split into the "local" component, which is the <code>self.to_train_locally</code> component which can consist of an aribtrary number of layers, which I want to reside in my personal laptop. I then want a second component of the model to train on an AWS EC2 instance that I have, which is the <code>self.to_train_on_aws</code>, which I want to reside on AWS. This component will be much bigger that the <code>self.to_train_locally</code> component. In this toy example, of course the entire model can be stored locally, but that is not the point - I want a framework that will allow me to train a part of the model locally, while do the bulk of the training on AWS.</p>
<p>How would I set up a training routine for this? I have looked at the following tutorials from pytorch's official documentation, but none of them are of any help -</p>
<ol>
<li><p>https://pytorch.org/tutorials/intermediate/dist_tuto.html This talks about <code>gloo</code> etc. and co-ordination tools that I assume more sense for larger teams. If I want to do this for a personal project, where some layers exist and train on my local laptop and a personal EC2 instance, how would I do this?</p>
</li>
<li><p>https://pytorch.org/tutorials/intermediate/rpc_tutorial.html this is not useful either, because it talks about model parallelism in a single machine, where multiple processes on a single machine are spawned/forked, but this is not what I want to do. For example, I can't just set</p>
</li>
</ol>
<pre class="lang-py prettyprint-override"><code>os.environ['MASTER_ADDR'] = 'my:aws:instance:public:ip:addr'
os.environ['MASTER_PORT'] = '29500' # any port
</code>```

from the RNN example given in this tutorial.

Has anyone tried to do something like this before? How would distributed autograd and a distributed optimiser work in this case in a training loop? Any help will be appreciated, especially if you can point me to code where someone has tried to do something like this before.

I have looked at the following tutorials from pytorch's official documentation, but none of them are of any help -

https://pytorch.org/tutorials/intermediate/dist_tuto.html This talks about gloo etc. and co-ordination tools that I assume more sense for larger teams. If I want to do this for a personal project, where some layers exist and train on my local laptop and a personal EC2 instance, how would I do this?

https://pytorch.org/tutorials/intermediate/rpc_tutorial.html this is not useful either, because it talks about model parallelism in a single machine, where multiple processes on a single machine are spawned/forked, but this is not what I want to do. For example, I can't just set

os.environ['MASTER_ADDR'] = 'my:aws:instance:public:ip:addr'
os.environ['MASTER_PORT'] = '29500' # any port
```

from the RNN example given in this tutorial.

Has anyone tried to do something like this before? How would distributed autograd and a distributed optimiser work in this case in a training loop? Any help will be appreciated, especially if you can point me to code where someone has tried to do something like this before.

EDIT 1

What I am trying to do is basically explained in this paper https://arxiv.org/pdf/1903.11314.pdf, under the title "Model parallelism" -

"In model parallelism, the DL model is split, and each worker loads a different part of the DL model for training (see Figure 5). The worker(s) that hold the input layer of the DL model are fed with the training data. In the forward pass, they compute their output signal
which is propagated to the workers that hold the next layer of the DL model. In the backpropagation
pass, gradients are computed starting at the workers that hold the output layer of the DL model,
propagating to the workers that hold the input layers of the DL model."

Does anyone have an example of how to do this on AWS and using PyTorch?

Body:
I am wondering how to do model parallelism using pytorch's distributed modules. Basically what I want to do is the following -

class LargeModel(nn.Module):
    def __init__(self, in_features, n_hid, out_features) -> None:
        super().__init__()
        self.to_train_locally = nn.Linear(in_features, n_hid)
        self.to_train_on_aws = nn.Linear(n_hid, out_features)

    def forward(self, input):
        intermediate = self.to_train_locally(input)
        res = send_to_aws_for_forward_pass(self.to_train_on_aws, intermediate)
        return res

basically, I want to train a "large" model, which I want to split into the "local" component, which is the self.to_train_locally component which can consist of an aribtrary number of layers, which I want to reside in my personal laptop. I then want a second component of the model to train on an AWS EC2 instance that I have, which is the self.to_train_on_aws, which I want to reside on AWS. This component will be much bigger that the self.to_train_locally component. In this toy example, of course the entire model can be stored locally, but that is not the point - I want a framework that will allow me to train a part of the model locally, while do the bulk of the training on AWS.

How would I set up a training routine for this? I have looked at the following tutorials from pytorch's official documentation, but none of them are of any help -

https://pytorch.org/tutorials/intermediate/dist_tuto.html This talks about gloo etc. and co-ordination tools that I assume more sense for larger teams. If I want to do this for a personal project, where some layers exist and train on my local laptop and a personal EC2 instance, how would I do this?

https://pytorch.org/tutorials/intermediate/rpc_tutorial.html this is not useful either, because it talks about model parallelism in a single machine, where multiple processes on a single machine are spawned/forked, but this is not what I want to do. For example, I can't just set

os.environ['MASTER_ADDR'] = 'my:aws:instance:public:ip:addr'
os.environ['MASTER_PORT'] = '29500' # any port

from the RNN example given in this tutorial.

Has anyone tried to do something like this before? How would distributed autograd and a distributed optimiser work in this case in a training loop? Any help will be appreciated, especially if you can point me to code where someone has tried to do something like this before.

I have looked at the following tutorials from pytorch's official documentation, but none of them are of any help -

https://pytorch.org/tutorials/intermediate/dist_tuto.html This talks about gloo etc. and co-ordination tools that I assume more sense for larger teams. If I want to do this for a personal project, where some layers exist and train on my local laptop and a personal EC2 instance, how would I do this?

https://pytorch.org/tutorials/intermediate/rpc_tutorial.html this is not useful either, because it talks about model parallelism in a single machine, where multiple processes on a single machine are spawned/forked, but this is not what I want to do. For example, I can't just set

os.environ['MASTER_ADDR'] = 'my:aws:instance:public:ip:addr'
os.environ['MASTER_PORT'] = '29500' # any port

from the RNN example given in this tutorial.

Has anyone tried to do something like this before? How would distributed autograd and a distributed optimiser work in this case in a training loop? Any help will be appreciated, especially if you can point me to code where someone has tried to do something like this before.

EDIT 1

What I am trying to do is basically explained in this paper https://arxiv.org/pdf/1903.11314.pdf, under the title "Model parallelism" -

"In model parallelism, the DL model is split, and each worker loads a different part of the DL model for training (see Figure 5). The worker(s) that hold the input layer of the DL model are fed with the training data. In the forward pass, they compute their output signal
which is propagated to the workers that hold the next layer of the DL model. In the backpropagation
pass, gradients are computed starting at the workers that hold the output layer of the DL model,
propagating to the workers that hold the input layers of the DL model."

Does anyone have an example of how to do this on AWS and using PyTorch?


来源: stackexchange

问:
Execution failed for task ':app:signReleaseBundle'
Execution failed for task ':app:signReleaseBundle'.

A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
Failed to read key locii from store "E:\Flutter-App\android\app\locii.jks": No key with alias 'locii' found in keysto
re E:\Flutter-App\android\app\locii.jks

ContentLicense: CC BY-SA 4.0


问:
Styling borders of css grid with fexible number of rows and columns
I have a "table" which consists of wrapper element, which is styled as display:grid and elements which are styled to have border, but elements on the very edge of the table should not have border, creating this border styling pattern:

```<code>
   |    |    |
---+----+----+----
   |    |    |
---+----+----+----
   |    |    |
</code>```

Like this:

Grid has flexible number of columns

    display: grid;
    grid: none / repeat(auto-fill, minmax(auto, 312px))
```
<p>and there are no explicit rows, so number of rows is also flexible. Flexible layout is important to have responsive design.</p>
<p>For the sake of simplicity, let's say that grid is comprised of div container and inner div elements with contents like so:</p>
```

content

content

content

  ...

```

How to style borders of this "table"? Do note that everything is flexible.

Every solution I found so far relies on known number of columns and rows, which is not the case here.

Body:
I have a "table" which consists of wrapper element, which is styled as display:grid and elements which are styled to have border, but elements on the very edge of the table should not have border, creating this border styling pattern:

   |    |    |
---+----+----+----
   |    |    |
---+----+----+----
   |    |    |

Like this:

Grid has flexible number of columns

    display: grid;
    grid: none / repeat(auto-fill, minmax(auto, 312px))

and there are no explicit rows, so number of rows is also flexible. Flexible layout is important to have responsive design.

For the sake of simplicity, let's say that grid is comprised of div container and inner div elements with contents like so:

content

content

content

  ...

How to style borders of this "table"? Do note that everything is flexible.

Every solution I found so far relies on known number of columns and rows, which is not the case here.


问:
Call string variable from yml file to program.cs
Is it possible to call string variable from .github/workflow/file.yml to  program.cs in Blazor?

example:

file.yml

```<code>        env:
         ASPNETCORE_ENVIRONMENT: "Development"
         LICENSE_KEY: "NjM1ODY2QDMyMzAyZTMxMmUzMGpKSS2VmR05KMHVCZjhXTmoxTW41WTg9"
</code>```

pass into program.cs

```<code>   string license_key = Configuration["LICENSE_KEY"];
</code>```

Body:
Is it possible to call string variable from .github/workflow/file.yml to  program.cs in Blazor?

example:

file.yml

        env:
         ASPNETCORE_ENVIRONMENT: "Development"
         LICENSE_KEY: "NjM1ODY2QDMyMzAyZTMxMmUzMGpKSS2VmR05KMHVCZjhXTmoxTW41WTg9"

pass into program.cs

   string license_key = Configuration["LICENSE_KEY"];


问:
How to avoid unnecessary instantiations with Boost.MP11
I have been using my own TMP library for quite some time.  However, I want to start using Boost.MP11.  The interface is quite nice, and, to give myself some motivation to learn it, I did the 2022 Advent of Code as much as I could at compile time, using Boost.MP11.

However, there were some things that I had to do, which I did not like.  I went back to clean some things up, and one place where I am still a bit confused, is how to prevent unnecessary instantiations.  I'm sure some use of mp_valid is the way to go, but I could use some guidance.

For example, consider the following implementation of push_heap, using Boost.MP11 (which I implemented as part of implementing Dijkstra's algorithm for one of the challenges).

It is a bit verbose in order to make it obvious what I want to achieve, namely the instantiation of templates only when they are true.

I must be misunderstanding something about Boost.MP11, so I would like to see an elegant Boost.MP11 implementation of push_heap.

template <typename IndexT>
using parent = mp_constant<(IndexT::value - 1) / 2>;

template <typename ListT, typename IndexT> struct BubbleUp;

template <
    typename ListT,
    typename IndexT,
    typename CondT = mp_less<
        mp_at<ListT, parent<IndexT>>,
        mp_at<ListT, IndexT>>>
struct BubbleUpImpl
: BubbleUp<
    mp_replace_at<
        mp_replace_at<ListT, IndexT, mp_at<ListT, parent<IndexT>>>,
        parent<IndexT>,
        mp_at<ListT, IndexT>>,
    parent<IndexT>>
{ };
template <typename ListT, typename IndexT>
struct BubbleUpImpl<ListT, IndexT, mp_false>
{
    using type = ListT;
};

template <typename ListT, typename IndexT>
struct BubbleUp
: BubbleUpImpl<ListT, IndexT>
{ };
template <typename ListT>
struct BubbleUp<ListT, mp_size_t<0>>
{
    using type = ListT;
};

// Not same as std::push_heap - it pushes and heapifies
template <typename ListT, typename T>
using push_heap = typename BubbleUp<
    mp_push_back<ListT, T>,
    mp_size<ListT>>::type;
```
<hr />
<p><strong>EDIT</strong></p>
<p>Here is my attempt with <code>Boost.MP11</code>, but I am less than enamored with it, and still searching for a better alternative, and especially interested in learning how best to do these kinds of things with <code>Boost.MP11</code>.  Note that the semantics here are the same as <code>std::push_heap</code> - the difference above was to try and simplify.</p>
<pre class="lang-cpp prettyprint-override"><code>namespace heap_detail {

template <typename ListT, typename Index1T, typename Index2T>
using swap_at = mp_replace_at<
    mp_replace_at<ListT, Index1T, mp_at<ListT, Index2T>>,
    Index2T,
    mp_at<ListT, Index1T>>;

template <typename CmpQ>
class PushHeap
{
    template <typename T>
    using heap = mp_first<T>;

    template <typename T>
    using child = mp_second<T>;

    template <typename T>
    using parent = mp_if<
        mp_less<mp_size_t<0>, child<T>>,
        mp_constant<(child<T>::value - 1) / 2>>;

    template <typename T>
    using bubble_up = mp_list<
        mp_if<
            mp_invoke_q<
                CmpQ,
                mp_at<heap<T>, parent<T>>,
                mp_at<heap<T>, child<T>>>,
            swap_at<heap<T>, parent<T>, child<T>>>,
        parent<T>>;

public:
    template <typename ListT>
    using fn = mp_back<mp_iterate<
        mp_list<ListT, mp_minus<mp_size<ListT>, mp_int<1>>>,
        mp_first,
        bubble_up>>;
};
} // namespace heap_detail
</code>```

template <typename ListT, typename CmpQ>
using push_heap_q = mp_invoke_q<heap_detail::PushHeap<CmpQ>, ListT>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using push_heap = push_heap_q<ListT, mp_quote<Cmp>>;
```
<p>Also, for what it's worth, here is the rest of the heap interface.  Maybe these will show more opportunity for learning how better to use <code>Boost.MP11</code>.</p>
<p>make_heap</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename ListT, typename CmpQ>
using make_heap_q = mp_fold_q<
    ListT,
    mp_list<>,
    mp_compose_q<mp_quote<mp_push_back>, mp_bind_back<push_heap_q, CmpQ>>>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using make_heap = make_heap_q<ListT, mp_quote<Cmp>>;
</code>```

And something to push additional items onto the heap

template <typename ListT, typename CmpQ, typename... Ts>
using heap_push_back_q = mp_fold_q<
    mp_list<Ts...>,
    ListT,
    mp_compose_q<mp_quote<mp_push_back>, mp_bind_back<push_heap_q, CmpQ>>>;
```
<p>And <code>pop_heap</code>, which seems way overly complicated - specialization seems much easier to read and write, so, I believe I am missing something fundamental with <code>Boost.MP11</code>.</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename CmpQ>
class PopHeap
{
    template <typename T>
    using heap = mp_first<T>;

    template <typename T>
    using parent = mp_second<T>;

    template <typename T>
    using left_child = mp_constant<parent<T>::value * 2 + 1>;

    template <typename T>
    using right_child = mp_constant<parent<T>::value * 2 + 2>;

    template <typename T>
    using child_to_swap = mp_eval_or_q<
        left_child<T>,
        mp_quote<mp_if>,
        mp_invoke_q<
            CmpQ,
            mp_at<heap<T>, left_child<T>>,
            mp_at<heap<T>, right_child<T>>>,
        right_child<T>,
        left_child<T>>;

    template <typename T>
    using bubble_down = mp_list<
        mp_if<
            mp_invoke_q<
                CmpQ,
                mp_at<heap<T>, parent<T>>,
                mp_at<heap<T>, child_to_swap<T>>>,
            swap_at<heap<T>, parent<T>, child_to_swap<T>>>,
        child_to_swap<T>>;

public:
    template <typename ListT>
    using fn = mp_push_back<
        mp_back<
            mp_iterate<
                mp_list<
                    mp_rotate_right<mp_pop_front<ListT>, mp_int<1>>,
                    mp_size_t<0>>,
                mp_first,
                bubble_down>>,
        mp_first<ListT>>;
};
</code>```

template <typename ListT, typename CmpQ>
using pop_heap_q = mp_invoke_q<heap_detail::PopHeap<CmpQ>, ListT>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using pop_heap = pop_heap_q<ListT, mp_quote<Cmp>>;
```

Body:
I have been using my own TMP library for quite some time.  However, I want to start using Boost.MP11.  The interface is quite nice, and, to give myself some motivation to learn it, I did the 2022 Advent of Code as much as I could at compile time, using Boost.MP11.

However, there were some things that I had to do, which I did not like.  I went back to clean some things up, and one place where I am still a bit confused, is how to prevent unnecessary instantiations.  I'm sure some use of mp_valid is the way to go, but I could use some guidance.

For example, consider the following implementation of push_heap, using Boost.MP11 (which I implemented as part of implementing Dijkstra's algorithm for one of the challenges).

It is a bit verbose in order to make it obvious what I want to achieve, namely the instantiation of templates only when they are true.

I must be misunderstanding something about Boost.MP11, so I would like to see an elegant Boost.MP11 implementation of push_heap.

template <typename IndexT>
using parent = mp_constant<(IndexT::value - 1) / 2>;

template <typename ListT, typename IndexT> struct BubbleUp;

template <
    typename ListT,
    typename IndexT,
    typename CondT = mp_less<
        mp_at<ListT, parent<IndexT>>,
        mp_at<ListT, IndexT>>>
struct BubbleUpImpl
: BubbleUp<
    mp_replace_at<
        mp_replace_at<ListT, IndexT, mp_at<ListT, parent<IndexT>>>,
        parent<IndexT>,
        mp_at<ListT, IndexT>>,
    parent<IndexT>>
{ };
template <typename ListT, typename IndexT>
struct BubbleUpImpl<ListT, IndexT, mp_false>
{
    using type = ListT;
};

template <typename ListT, typename IndexT>
struct BubbleUp
: BubbleUpImpl<ListT, IndexT>
{ };
template <typename ListT>
struct BubbleUp<ListT, mp_size_t<0>>
{
    using type = ListT;
};

// Not same as std::push_heap - it pushes and heapifies
template <typename ListT, typename T>
using push_heap = typename BubbleUp<
    mp_push_back<ListT, T>,
    mp_size<ListT>>::type;

EDIT

Here is my attempt with Boost.MP11, but I am less than enamored with it, and still searching for a better alternative, and especially interested in learning how best to do these kinds of things with Boost.MP11.  Note that the semantics here are the same as std::push_heap - the difference above was to try and simplify.

namespace heap_detail {

template <typename ListT, typename Index1T, typename Index2T>
using swap_at = mp_replace_at<
    mp_replace_at<ListT, Index1T, mp_at<ListT, Index2T>>,
    Index2T,
    mp_at<ListT, Index1T>>;

template <typename CmpQ>
class PushHeap
{
    template <typename T>
    using heap = mp_first<T>;

    template <typename T>
    using child = mp_second<T>;

    template <typename T>
    using parent = mp_if<
        mp_less<mp_size_t<0>, child<T>>,
        mp_constant<(child<T>::value - 1) / 2>>;

    template <typename T>
    using bubble_up = mp_list<
        mp_if<
            mp_invoke_q<
                CmpQ,
                mp_at<heap<T>, parent<T>>,
                mp_at<heap<T>, child<T>>>,
            swap_at<heap<T>, parent<T>, child<T>>>,
        parent<T>>;

public:
    template <typename ListT>
    using fn = mp_back<mp_iterate<
        mp_list<ListT, mp_minus<mp_size<ListT>, mp_int<1>>>,
        mp_first,
        bubble_up>>;
};
} // namespace heap_detail

template <typename ListT, typename CmpQ>
using push_heap_q = mp_invoke_q<heap_detail::PushHeap<CmpQ>, ListT>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using push_heap = push_heap_q<ListT, mp_quote<Cmp>>;

Also, for what it's worth, here is the rest of the heap interface.  Maybe these will show more opportunity for learning how better to use Boost.MP11.

make_heap

template <typename ListT, typename CmpQ>
using make_heap_q = mp_fold_q<
    ListT,
    mp_list<>,
    mp_compose_q<mp_quote<mp_push_back>, mp_bind_back<push_heap_q, CmpQ>>>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using make_heap = make_heap_q<ListT, mp_quote<Cmp>>;

And something to push additional items onto the heap

template <typename ListT, typename CmpQ, typename... Ts>
using heap_push_back_q = mp_fold_q<
    mp_list<Ts...>,
    ListT,
    mp_compose_q<mp_quote<mp_push_back>, mp_bind_back<push_heap_q, CmpQ>>>;

And pop_heap, which seems way overly complicated - specialization seems much easier to read and write, so, I believe I am missing something fundamental with Boost.MP11.

template <typename CmpQ>
class PopHeap
{
    template <typename T>
    using heap = mp_first<T>;

    template <typename T>
    using parent = mp_second<T>;

    template <typename T>
    using left_child = mp_constant<parent<T>::value * 2 + 1>;

    template <typename T>
    using right_child = mp_constant<parent<T>::value * 2 + 2>;

    template <typename T>
    using child_to_swap = mp_eval_or_q<
        left_child<T>,
        mp_quote<mp_if>,
        mp_invoke_q<
            CmpQ,
            mp_at<heap<T>, left_child<T>>,
            mp_at<heap<T>, right_child<T>>>,
        right_child<T>,
        left_child<T>>;

    template <typename T>
    using bubble_down = mp_list<
        mp_if<
            mp_invoke_q<
                CmpQ,
                mp_at<heap<T>, parent<T>>,
                mp_at<heap<T>, child_to_swap<T>>>,
            swap_at<heap<T>, parent<T>, child_to_swap<T>>>,
        child_to_swap<T>>;

public:
    template <typename ListT>
    using fn = mp_push_back<
        mp_back<
            mp_iterate<
                mp_list<
                    mp_rotate_right<mp_pop_front<ListT>, mp_int<1>>,
                    mp_size_t<0>>,
                mp_first,
                bubble_down>>,
        mp_first<ListT>>;
};

template <typename ListT, typename CmpQ>
using pop_heap_q = mp_invoke_q<heap_detail::PopHeap<CmpQ>, ListT>;

template <typename ListT, template <typename...> class Cmp = mp_less>
using pop_heap = pop_heap_q<ListT, mp_quote<Cmp>>;


问:
Classification task based on speech recordings
I'm currently working with a huge dataset consisting of speech recordings of conersations of 120 persons. For each person, I have around 5 conversation recordings lasting 40-60min (the conversations are dyadic). For each recording, I have a label (i.e., around 600 labels). The labels provide information about the mental state of one of the person in the conversation (three classes). To classify this mental state based on the speech recordings, I see the following three possibilities:

Extracting Mel-Spectrograms or MFCCs (better for speech) and training
a RNN CNN (e.g., ConvLSTM) for the classification task. Here I see
the problem that with the small amount of labels, it might overfit.
In addition, recordings are long and thus training a RNN might be
difficult. A pretrained network on a different task (e.g., speech
recognition?) could also be used (but probably not available for
RNN).

Training a CNN autoencoder on Mel-Spectrograms or MFCCs over small
shifted windows (e.g., 1 minutes). The encoder could then be used to
extract features. The problem here is that probably the whole
recording must be used for the prediction. Thus, features need to be
extracted over the whole recording which would require the same
shifted windows as for training the autoencoder.

Extracting the features manually (e.g. frequency-based features etc.)
and using a SVM or Random Forest for the prediction which might suit
better for the small amount of labels (a fully-connected network
could also be used for comparison). Here the advantage is that
features can be chosen that are independent of the length of the
recording.

Which option do you think is best? Do you have any recommendations?


问:
Bootstrap Cards aren't aligning correctly
So, basicly i have these bootstrap cards in a for loop in python flask, everything works well besides the alignment of the cards itself. My cards have good spacing, but when it goes to the next  row the card on the second row sticks to the card above it on the first row.

Here is a Screenshot: https://ibb.co/tsscqzb

HTML:

```<code><div class="container">
      <div class="row row-cols-auto">

        <div class="col">
        <div class="card" id='cardPostPost'  style="width: 350px; border-radius: 23px; background-color: rgb(35, 33, 33); color: white; bottom: -22pc; left: -18pc; ">
          <h5 class="card-header border-bottom border-light" style="color: white" >Teacher's Homework</h5>
          <div class="card-body" style="color: white" >
           <h5 class="card-title">Homework</h5>
            <p class="card-text">No </p>
           <a href="#" class="btn btn-primary">Learn More</a>
           </div>
      </div>
      </div>

        <div class="col">
        <div class="card" id='cardPostPost'  style="width: 350px; border-radius: 23px; background-color: rgb(35, 33, 33); color: white; bottom: -22pc; left: -18pc; ">
          <h5 class="card-header border-bottom border-light" style="color: white" >SomeNewTask</h5>
          <div class="card-body" style="color: white" >
           <h5 class="card-title">Homework</h5>
            <p class="card-text">Yes </p>
           <a href="#" class="btn btn-primary">Learn More</a>
           </div>
      </div>
      </div>

        <div class="col">
        <div class="card" id='cardPostPost'  style="width: 350px; border-radius: 23px; background-color: rgb(35, 33, 33); color: white; bottom: -22pc; left: -18pc; ">
          <h5 class="card-header border-bottom border-light" style="color: white" >wdaadadawdawdad</h5>
          <div class="card-body" style="color: white" >
           <h5 class="card-title">Test</h5>
            <p class="card-text">Yes </p>
           <a href="#" class="btn btn-primary">Learn More</a>
           </div>
      </div>
      </div>

        <div class="col">
        <div class="card" id='cardPostPost'  style="width: 350px; border-radius: 23px; background-color: rgb(35, 33, 33); color: white; bottom: -22pc; left: -18pc; ">
          <h5 class="card-header border-bottom border-light" style="color: white" >wdadwadadadwadawdad</h5>
          <div class="card-body" style="color: white" >
           <h5 class="card-title">Test</h5>
            <p class="card-text">Yes </p>
           <a href="#" class="btn btn-primary">Learn More</a>
           </div>
      </div>
      </div>

        <div class="col">
        <div class="card" id='cardPostPost'  style="width: 350px; border-radius: 23px; background-color: rgb(35, 33, 33); color: white; bottom: -22pc; left: -18pc; ">
          <h5 class="card-header border-bottom border-light" style="color: white" >awdadadad</h5>
          <div class="card-body" style="color: white" >
           <h5 class="card-title">Test</h5>
            <p class="card-text">Yes </p>
           <a href="#" class="btn btn-primary">Learn More</a>
           </div>
      </div>
      </div>
</code>```

I tried deleting the automatic set row thing, but it still didn't work.
Does anyone know how to fix this problem?

Body:
So, basicly i have these bootstrap cards in a for loop in python flask, everything works well besides the alignment of the cards itself. My cards have good spacing, but when it goes to the next  row the card on the second row sticks to the card above it on the first row.

Here is a Screenshot: https://ibb.co/tsscqzb

HTML:

Teacher's Homework

Homework

No

           Learn More

SomeNewTask

Homework

Yes

           Learn More

wdaadadawdawdad

Test

Yes

           Learn More

wdadwadadadwadawdad

Test

Yes

           Learn More

awdadadad

Test

Yes

           Learn More

I tried deleting the automatic set row thing, but it still didn't work.
Does anyone know how to fix this problem?


问:
xcodebuild command fails due to syncfusion_flutter_pdfviewer library
Xcode build fails when executing:

xcodebuild -scheme "Runner" BUILD_DIR=".../_appcircle_temp/appcircle_build_ios_simulator/SimulatorBuildDir" -derivedDataPath ".../_appcircle_temp/appcircle_build_ios_simulator/SimulatorDerivedData" -configuration "Debug"  COMPILER_INDEX_STORE_ENABLE=NO  ONLY_ACTIVE_ARCH=NO  -arch x86_64   -quiet  -workspace ".../_appcircle_temp/Repository/ios/Runner.xcworkspace"
```
<p>Error:</p>
```error: Build input file cannot be found: '....syncfusion_flutter_pdfviewer/syncfusion_flutter_pdfviewer.framework/syncfusion_flutter_pdfviewer'. Did you forget to declare this file as an output of a script phase or custom build rule which produces it? (in target 'syncfusion_flutter_pdfviewer' from project 'Pods')
```

I have tried adding syncfusion_flutter_pdfviewer to my POD file, but it stills failing (And documentation doesn't require to adding to pod file)

Any ideas how to solve this?

Body:
Xcode build fails when executing:

xcodebuild -scheme "Runner" BUILD_DIR=".../_appcircle_temp/appcircle_build_ios_simulator/SimulatorBuildDir" -derivedDataPath ".../_appcircle_temp/appcircle_build_ios_simulator/SimulatorDerivedData" -configuration "Debug"  COMPILER_INDEX_STORE_ENABLE=NO  ONLY_ACTIVE_ARCH=NO  -arch x86_64   -quiet  -workspace ".../_appcircle_temp/Repository/ios/Runner.xcworkspace"

Error:

error: Build input file cannot be found: '....syncfusion_flutter_pdfviewer/syncfusion_flutter_pdfviewer.framework/syncfusion_flutter_pdfviewer'. Did you forget to declare this file as an output of a script phase or custom build rule which produces it? (in target 'syncfusion_flutter_pdfviewer' from project 'Pods')

I have tried adding syncfusion_flutter_pdfviewer to my POD file, but it stills failing (And documentation doesn't require to adding to pod file)

Any ideas how to solve this?


问:
Directory structure for multiple distributed python packages
This question unfortunately requires a little bit of setup so bear with me:

Suppose my startup, travel-is-cool, has three pieces of code

A python packages with information about bicycles

A python package with information about the weather

A C++ library completely that does something but isn't important for the question.

All python code is written with python3.8.10, though it might move to python3.10 in the future.

The folder structure at this startup looks like the following:

```<code>travel-is-cool/ # git root
---- cpp/
---- python/
-------- setup.py
-------- src/
------------ bicycle/
---------------- __init__.py
---------------- bicycle.py
---------------- # Plenty of additional files and folders, this is a large project!
------------ weather/
---------------- __init__.py
---------------- weather.py
---------------- # Plenty of additional files and folders, this is a large project!
</code>```

I've looked over the code and decided I want to enable developers to use pip install travel-is-cool-bicycle and pip install travel-is-cool-weather on their local machines, as these packages are totally separate from one another! I'd also like to build wheels for them. I can't find any best practices with how to do this at all, however.

Is it possible for me to maintain the current structure, and have two setuptools.setup calls in my current setup.py? (Doesn't look like it)

Must I maintain a structure similar to the following:

python/src/bicycle/setup.py

python/src/bicycle/bicycle/code-goes-here

The repeated directory name in this solution seems to simply add clutter, but is a viable option in the worst case.

Is there some pyproject.toml trickery I need to be using? Where should I put that?

This question is mostly related to the correct file structure I need to maintain, and maybe partially related to the contents of a setup.py or associated file. I also require almost all python files to remain inside python/src  (one or two is OK as there are two packages).

Thanks for all the help!

Body:
This question unfortunately requires a little bit of setup so bear with me:

Suppose my startup, travel-is-cool, has three pieces of code

A python packages with information about bicycles

A python package with information about the weather

A C++ library completely that does something but isn't important for the question.

All python code is written with python3.8.10, though it might move to python3.10 in the future.

The folder structure at this startup looks like the following:

travel-is-cool/ # git root
---- cpp/
---- python/
-------- setup.py
-------- src/
------------ bicycle/
---------------- __init__.py
---------------- bicycle.py
---------------- # Plenty of additional files and folders, this is a large project!
------------ weather/
---------------- __init__.py
---------------- weather.py
---------------- # Plenty of additional files and folders, this is a large project!

I've looked over the code and decided I want to enable developers to use pip install travel-is-cool-bicycle and pip install travel-is-cool-weather on their local machines, as these packages are totally separate from one another! I'd also like to build wheels for them. I can't find any best practices with how to do this at all, however.

Is it possible for me to maintain the current structure, and have two setuptools.setup calls in my current setup.py? (Doesn't look like it)

Must I maintain a structure similar to the following:

python/src/bicycle/setup.py

python/src/bicycle/bicycle/code-goes-here

The repeated directory name in this solution seems to simply add clutter, but is a viable option in the worst case.

Is there some pyproject.toml trickery I need to be using? Where should I put that?

This question is mostly related to the correct file structure I need to maintain, and maybe partially related to the contents of a setup.py or associated file. I also require almost all python files to remain inside python/src  (one or two is OK as there are two packages).

Thanks for all the help!


问:
Click the button to move to the next iteration
I'm trying to make a quiz app using SwiftUI. Since I am doing mobile programming for the first time, I am inexperienced and I may have basic mistakes. I keep the questions that I will use in app in a CSV file. I am reading this CSV file with a foreach loop, but all questions are loaded on the screen because the loop is expected to end in the view section. What I want is for the foreach loop to go to the next iteration only when the button is clicked.

```<code>//
//  QuestionView.swift
//  csvQuestions
//
//

import SwiftUI

struct QuestionView: View {
var brandGradient = Gradient(colors: \[Color (.systemPurple), Color(.systemIndigo)\])
@State var Questionx:\[Question\]
var body: some View {
ZStack{
//ARKA PLAN
Image("Image")
.resizable()
.scaledToFill()
.frame(width: UIScreen.main.bounds.width*1,height: UIScreen.main.bounds.height*1)

VStack{
RoundedRectangle(cornerRadius: 20)
.fill(LinearGradient(colors: \[.white,.yellow\], startPoint: .top, endPoint: .bottom))
.frame(width: UIScreen.main.bounds.width*0.9,height: UIScreen.main.bounds.height*0.7)
.padding(80)
.opacity(0.85)
Spacer()

            }

            VStack(){
                ForEach(Questionx){
                    question in

Text(question.detail)
.font(.callout)
.fontWeight(.semibold)
.multilineTextAlignment(.center)
.fontWidth(.standard)
.frame(width:UIScreen.main.bounds.width*0.9,height: UIScreen.main.bounds.height*0.1)
.offset(y:115)
Spacer()
ForEach (optionsGenerator(day: String(question.date), year: String(question.year)),id:.self) { i in
Button {

                    if ((question.date) == "\(i[0]) \(i[1])") && (String(question.year) == i[2])
                        {
                            print ("true")

                        }
                        else {
                            print ("false")

                        }

                    } label: {

Text ("(i\[0\]) " + String(i\[1\]) + " " + i\[2\])
.frame(width: UIScreen.main.bounds.width*0.75,height:UIScreen.main.bounds.height*0.075)
.foregroundColor (.white)
.background (RadialGradient (gradient: brandGradient, center: .center, startRadius: 25,
endRadius: 120))
.clipShape (Capsule())

                    }

                    }

                }
                Spacer()

            }.frame(width: UIScreen.main.bounds.width*1,height: UIScreen.main.bounds.height*1)

        }

    }

}

struct QuestionView_Previews: PreviewProvider {
static var previews: some View {
QuestionView(Questionx: loadCSData())
}
}
</code>```

I looked at the development of similar applications on YouTube but I could not find a solution. I also tried to set up the loop in different ways but with no results.

When I add multiple line of CSV file:

When I add only a single line of CSV file, everything looks like what I want:

Body:
I'm trying to make a quiz app using SwiftUI. Since I am doing mobile programming for the first time, I am inexperienced and I may have basic mistakes. I keep the questions that I will use in app in a CSV file. I am reading this CSV file with a foreach loop, but all questions are loaded on the screen because the loop is expected to end in the view section. What I want is for the foreach loop to go to the next iteration only when the button is clicked.

//
//  QuestionView.swift
//  csvQuestions
//
//

import SwiftUI

struct QuestionView: View {
var brandGradient = Gradient(colors: \[Color (.systemPurple), Color(.systemIndigo)\])
@State var Questionx:\[Question\]
var body: some View {
ZStack{
//ARKA PLAN
Image("Image")
.resizable()
.scaledToFill()
.frame(width: UIScreen.main.bounds.width*1,height: UIScreen.main.bounds.height*1)

VStack{
RoundedRectangle(cornerRadius: 20)
.fill(LinearGradient(colors: \[.white,.yellow\], startPoint: .top, endPoint: .bottom))
.frame(width: UIScreen.main.bounds.width*0.9,height: UIScreen.main.bounds.height*0.7)
.padding(80)
.opacity(0.85)
Spacer()

            }

            VStack(){
                ForEach(Questionx){
                    question in

Text(question.detail)
.font(.callout)
.fontWeight(.semibold)
.multilineTextAlignment(.center)
.fontWidth(.standard)
.frame(width:UIScreen.main.bounds.width*0.9,height: UIScreen.main.bounds.height*0.1)
.offset(y:115)
Spacer()
ForEach (optionsGenerator(day: String(question.date), year: String(question.year)),id:.self) { i in
Button {

                    if ((question.date) == "\(i[0]) \(i[1])") && (String(question.year) == i[2])
                        {
                            print ("true")

                        }
                        else {
                            print ("false")

                        }

                    } label: {

Text ("(i\[0\]) " + String(i\[1\]) + " " + i\[2\])
.frame(width: UIScreen.main.bounds.width*0.75,height:UIScreen.main.bounds.height*0.075)
.foregroundColor (.white)
.background (RadialGradient (gradient: brandGradient, center: .center, startRadius: 25,
endRadius: 120))
.clipShape (Capsule())

                    }

                    }

                }
                Spacer()

            }.frame(width: UIScreen.main.bounds.width*1,height: UIScreen.main.bounds.height*1)

        }

    }

}

struct QuestionView_Previews: PreviewProvider {
static var previews: some View {
QuestionView(Questionx: loadCSData())
}
}

I looked at the development of similar applications on YouTube but I could not find a solution. I also tried to set up the loop in different ways but with no results.

When I add multiple line of CSV file:

When I add only a single line of CSV file, everything looks like what I want:


问:
Rename textarea placeholder function
I have working Jquery written in this format to rename a span:

```<code>// [A]
let _href_w = $('span').filter(function () {
    return this.innerHTML == 'originalText';
})
_href_w.text("replaceOriginalText") //rename span
</code>```

now I need a function to replace the placeholder of textarea:

```<code>HTML
<textarea placeholder="TypeHere"></textarea>

JQUERY
var textarea = $('textarea').filter('[placeholder="TypeHere"]');
textarea.attr('placeholder','replaceTypeHere');
</code>```

but I would like it to be written like [A]

I tried:

```<code>let _href_w = $('textarea').filter(function () {
    return this.attr('placeholder') == 'TypeHere';
})
_href_w.attr('placeholder','replaceTypeHere') //rename textarea_placeholder
</code>```

but error shows: this.attr is not a function

how can I rewrite this?

Title: Rename textarea placeholder function

Body:
I have working Jquery written in this format to rename a span:

// [A]
let _href_w = $('span').filter(function () {
    return this.innerHTML == 'originalText';
})
_href_w.text("replaceOriginalText") //rename span

now I need a function to replace the placeholder of textarea:

HTML
<textarea placeholder="TypeHere"></textarea>

JQUERY
var textarea = $('textarea').filter('[placeholder="TypeHere"]');
textarea.attr('placeholder','replaceTypeHere');

but I would like it to be written like [A]

I tried:

let _href_w = $('textarea').filter(function () {
    return this.attr('placeholder') == 'TypeHere';
})
_href_w.attr('placeholder','replaceTypeHere') //rename textarea_placeholder

but error shows: this.attr is not a function

how can I rewrite this?


问:
Composite relations (relations built out of multiple separate queries)
Let's take two simple queries:

```<code>@c = @project.companies.where("companies.public = ?", true)
@i = @item.companies.where("companies.created_at > ?", Date.today - 3.days).limit(3)
</code>```

Say I want to combine these into a single relation of companies, which I then want to paginate and search on. Let's try:

```<code>@companies = (@c + @i).paginate...
# or #
@companies = (@c << @i).paginate...
</code>```

Both of these fail because @companies is an array, not a relation. How can two or more relations be combined to form a third relation?

ContentLicense: CC BY-SA 3.0

Body:
Let's take two simple queries:

@c = @project.companies.where("companies.public = ?", true)
@i = @item.companies.where("companies.created_at > ?", Date.today - 3.days).limit(3)

Say I want to combine these into a single relation of companies, which I then want to paginate and search on. Let's try:

@companies = (@c + @i).paginate...
# or #
@companies = (@c << @i).paginate...

Both of these fail because @companies is an array, not a relation. How can two or more relations be combined to form a third relation?


问:
upload mp3 to server doesn't work in react-native
I have this code to upload mp3 audio to a server but it gives me [TypeError: Network request failed]
Help please

```<code>export async function uploadFile(fileUri) {
  const url = //my url;
  var token;
  await AsyncStorage.getItem('access_token').then((res) => {
    token = res;
  });
  let data = new FormData();

  data.append('file', {
    uri: fileUri,
    name: 'test.mp3',
    type: 'audio/mpeg',
  });
  return fetch(url, {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + token,
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then((response) => response.json())
    .catch((error) => console.error(error));
}
</code>```

The same exact code works fine for an image uri if I change

```<code>data.append('file', {
    uri: fileUri,
    name: 'test.mp3',
    type: 'audio/mpeg',
  });
</code>```

to

```<code> data.append('file', {
    uri: fileUri,
    name: 'test.jpg',
    type: 'image/jpeg',
  });
</code>```

I'm sure the audio's uri is correct because I use the exact same way to get the uri of the image which works fine.

I tried audio/mpeg and audio/mp3 for the type but neither of them works.

Body:
I have this code to upload mp3 audio to a server but it gives me [TypeError: Network request failed]
Help please

export async function uploadFile(fileUri) {
  const url = //my url;
  var token;
  await AsyncStorage.getItem('access_token').then((res) => {
    token = res;
  });
  let data = new FormData();

  data.append('file', {
    uri: fileUri,
    name: 'test.mp3',
    type: 'audio/mpeg',
  });
  return fetch(url, {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + token,
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then((response) => response.json())
    .catch((error) => console.error(error));
}

The same exact code works fine for an image uri if I change

data.append('file', {
    uri: fileUri,
    name: 'test.mp3',
    type: 'audio/mpeg',
  });

to

 data.append('file', {
    uri: fileUri,
    name: 'test.jpg',
    type: 'image/jpeg',
  });

I'm sure the audio's uri is correct because I use the exact same way to get the uri of the image which works fine.

I tried audio/mpeg and audio/mp3 for the type but neither of them works.


问:
I am trying to make a visitor counter using react and firebase, but getting error at setting data
i am trying to make a visitor counter using React and Firebase but i am stuck at a point where i am unable to save the data in the state.

```<code>const [visitor, setVisitor] = useState([]);
  const [visitorCount, setVisitorCount] = useState(0);
  // const [id, setId] = useState(null);

  const visitorCollectionRef = collection(db, "visitor_counter");

  const addVisitor = async () => {
    console.log("here");
    await addDoc(visitorCollectionRef, {
      visitorCount,
      id: "",
      created: serverTimestamp(),
    });
  };

  const updateVisitor = async (id) => {
    console.log("here");
    //   // await updateDoc();
  };
  useEffect(() => {
    const getVisitor = async () => {
      const data = await getDocs(visitorCollectionRef);

      setVisitor(data.docs.map((doc) => ({ ...doc.data(), id: doc.id }))); // problem shows here

      console.log(visitor);

      if (data.docs.length === 1) {
        updateVisitor(visitorCount);
      } else {
        addVisitor();
      }
    };
    getVisitor();
  }, []);

</code>```

The error i am gettin is

```<code>
Uncaught Error: Objects are not valid as a React child (found: object with keys {visitorCount, created, id}). If you meant to render a collection of children, use an array instead.
    at throwOnInvalidObjectType (react-dom.development.js:14887:1)
    at createChild (react-dom.development.js:15139:1)
    at reconcileChildrenArray (react-dom.development.js:15404:1)
    at reconcileChildFibers (react-dom.development.js:15821:1)
    at reconcileChildren (react-dom.development.js:19174:1)
    at updateFragment (react-dom.development.js:19514:1)
    at beginWork (react-dom.development.js:21640:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)

</code>```

I have debugged my code in every possible way, and problem shows only when calling

setVisitor function to set data.

Please ignore if any mistake, i am a beginner.

Body:
i am trying to make a visitor counter using React and Firebase but i am stuck at a point where i am unable to save the data in the state.

const [visitor, setVisitor] = useState([]);
  const [visitorCount, setVisitorCount] = useState(0);
  // const [id, setId] = useState(null);

  const visitorCollectionRef = collection(db, "visitor_counter");

  const addVisitor = async () => {
    console.log("here");
    await addDoc(visitorCollectionRef, {
      visitorCount,
      id: "",
      created: serverTimestamp(),
    });
  };

  const updateVisitor = async (id) => {
    console.log("here");
    //   // await updateDoc();
  };
  useEffect(() => {
    const getVisitor = async () => {
      const data = await getDocs(visitorCollectionRef);

      setVisitor(data.docs.map((doc) => ({ ...doc.data(), id: doc.id }))); // problem shows here

      console.log(visitor);

      if (data.docs.length === 1) {
        updateVisitor(visitorCount);
      } else {
        addVisitor();
      }
    };
    getVisitor();
  }, []);

The error i am gettin is

Uncaught Error: Objects are not valid as a React child (found: object with keys {visitorCount, created, id}). If you meant to render a collection of children, use an array instead.
    at throwOnInvalidObjectType (react-dom.development.js:14887:1)
    at createChild (react-dom.development.js:15139:1)
    at reconcileChildrenArray (react-dom.development.js:15404:1)
    at reconcileChildFibers (react-dom.development.js:15821:1)
    at reconcileChildren (react-dom.development.js:19174:1)
    at updateFragment (react-dom.development.js:19514:1)
    at beginWork (react-dom.development.js:21640:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)

I have debugged my code in every possible way, and problem shows only when calling

setVisitor function to set data.

Please ignore if any mistake, i am a beginner.


问:
Working with window based on its current icon?
I am constantly finding myself in this edge case of, not being able to identify a perticular window reliably.

I am tired of relying on the devoloper to give their software a title bar with meaningfull information.
So I have set out to solve this. After much searching and reading. I have arrived upon:

```<code>~Browser_Back & space::
WM_SETICON := 0x80
ICON_SMALL := 0
ICON_BIG := 1
IMAGE_ICON := 1

$F1::
   hIcon := LoadPicture("Shell32.dll", "Icon5", IMAGE_ICON)
   SendMessage, WM_SETICON, ICON_SMALL, hIcon,, A
   SendMessage, WM_SETICON, ICON_BIG, hIcon,, A
   Return
</code>```

It will change the active windows icon.

Its not my code, I found it HERE. It works very reliably.

I want to build upon this, Is there a way for Authotkey to work with a window based on its current icon?
Commands like

#IfWinActive

#If

If

etc etc can work on a windows title and controls but what about its icon?

I searched as much as I could on this topic and turned up with nothing.

Any help would be really wellcome

Body:
I am constantly finding myself in this edge case of, not being able to identify a perticular window reliably.

I am tired of relying on the devoloper to give their software a title bar with meaningfull information.
So I have set out to solve this. After much searching and reading. I have arrived upon:

~Browser_Back & space::
WM_SETICON := 0x80
ICON_SMALL := 0
ICON_BIG := 1
IMAGE_ICON := 1

$F1::
   hIcon := LoadPicture("Shell32.dll", "Icon5", IMAGE_ICON)
   SendMessage, WM_SETICON, ICON_SMALL, hIcon,, A
   SendMessage, WM_SETICON, ICON_BIG, hIcon,, A
   Return

It will change the active windows icon.

Its not my code, I found it HERE. It works very reliably.

I want to build upon this, Is there a way for Authotkey to work with a window based on its current icon?
Commands like

#IfWinActive

#If

If

etc etc can work on a windows title and controls but what about its icon?

I searched as much as I could on this topic and turned up with nothing.

Any help would be really wellcome


问:
Does RStudio's autocomplete feature have problems with dplyr's filter() function?
Disclaimer: this is one of the cases where I would say I need to upload screenshots as I don't know how else to show the problem and what I tried to solve it, but I am not allowed to. I hope it's understandable anyway.

I have a tibble t from which I would like to select four columns and then filter one of them using the dplyr package, like so:

```<code>t %>%
    select(Column1, Column2, Column3, Column4) %>%
    filter(Column3 == "XYZ")
</code>```

RStudio's autocomplete feature works within dplyr's select function and recognizes all columns, i.e. when I am in the parentheses of select and press Tab, I get the arguments for select and then all the columns in t.

However, the autocomplete menu in dplyr's filter function for some reason does not recognize Column3, it only shows Column1, Column2 and Column4.

I initially thought it might have something to do with Column3 specifically, but when I tried selecting only Column1, 2 and 4, the autocomplete function no longer recognizes Column4 even though it did before, and only shows Column1 and Column2.

Column1 and Column2 are of class double, Column3 and Column4 are character, so it can't be the data type.

I tried this with several other combinations and more columns than I originally wanted to and it seems like the autocomplete feature within filter recognizes columns at random.

Does anyone know the reason for this? Is that a feature?

EDIT: the data set is the LAX to JFK Sample Dataset from here: https://developer.ibm.com/exchanges/data/all/airline/

I want to select columns Month, DayOfWeek, Reporting_Airline, and CRSDepTime and filter by column Reporting_Airline.

Body:
Disclaimer: this is one of the cases where I would say I need to upload screenshots as I don't know how else to show the problem and what I tried to solve it, but I am not allowed to. I hope it's understandable anyway.

I have a tibble t from which I would like to select four columns and then filter one of them using the dplyr package, like so:

t %>%
    select(Column1, Column2, Column3, Column4) %>%
    filter(Column3 == "XYZ")

RStudio's autocomplete feature works within dplyr's select function and recognizes all columns, i.e. when I am in the parentheses of select and press Tab, I get the arguments for select and then all the columns in t.

However, the autocomplete menu in dplyr's filter function for some reason does not recognize Column3, it only shows Column1, Column2 and Column4.

I initially thought it might have something to do with Column3 specifically, but when I tried selecting only Column1, 2 and 4, the autocomplete function no longer recognizes Column4 even though it did before, and only shows Column1 and Column2.

Column1 and Column2 are of class double, Column3 and Column4 are character, so it can't be the data type.

I tried this with several other combinations and more columns than I originally wanted to and it seems like the autocomplete feature within filter recognizes columns at random.

Does anyone know the reason for this? Is that a feature?

EDIT: the data set is the LAX to JFK Sample Dataset from here: https://developer.ibm.com/exchanges/data/all/airline/

I want to select columns Month, DayOfWeek, Reporting_Airline, and CRSDepTime and filter by column Reporting_Airline.


问:
Having to reauthenticate with spotify api every time I send requests from React
Working with spotipy library and a React frontend. Used the Flask Spotipy example code as a basis and changed it for testing purposes to see if my idea works. Currently stuck on a bug that I can't seem to understand. I am able to authenticate the user just fine however I can only send ONE api request. After that I get an error similar to this

raise SpotifyOauthError(spotipy.oauth2.SpotifyOauthError: error: invalid_grant, error_description: Invalid authorization code

Not sure if it has to do with refresh tokens but I can never send multiple requests when I authroize a user.

Here is my python code and react code

```<code>

import os
from flask import Flask, session, request, redirect, jsonify
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(64)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = './.flask_session/'
CORS(app, resources={r"/*": {"origins": "*"}})
Session(app)

client_id = os.getenv("SPOTIPY_CLIENT_ID")
client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")
scope = 'user-read-currently-playing playlist-modify-private user-read-recently-played'
@app.route('/')
def index():

    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(scope=scope,
                                               cache_handler=cache_handler,
                                               show_dialog=True)

    if request.args.get("code"):
        # Step 2. Being redirected from Spotify auth page
        auth_manager.get_access_token(request.args.get("code"))
        session['access_token'] = auth_manager.get_access_token(request.args.get("code"))
        return redirect('http://localhost:3000/?code=' + request.args.get("code"))

    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        # Step 1. Display sign in link when no token
        auth_url = auth_manager.get_authorize_url()
        # let react grab the url
        return jsonify({'url': auth_url})

    # Step 3. Signed in, display data
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return f'<small><a href="/sign_out">[sign out]<a/></small></h2>' \
           f'<a href="/playlists">my playlists</a> | ' \
           f'<a href="/currently_playing">currently playing</a> | ' \
        f'<a href="/current_user">me</a>' \

@app.route('/sign_out')
def sign_out():
    session.pop("token_info", None)
    return redirect('/')

@app.route('/recently-played')
def recently_played():
    code = request.args.get('code')
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth.validate_token(cache_handler.get_cached_token()):
        token_info = auth.get_access_token(code)
    else:

        token_info = cache_handler.get_cached_token()
    spotify = spotipy.Spotify(auth=token_info['access_token'])
    return spotify.current_user_recently_played(limit=10)

@app.route('/currently_playing')
def currently_playing():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    track = spotify.current_user_playing_track()
    if not track is None:
        return track
    return "No track currently playing."

@app.route('/current_user')
def current_user():
    code = request.args.get('code')
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth.validate_token(cache_handler.get_cached_token()):
        token_info = auth.get_access_token(code)
    else:

        token_info = cache_handler.get_cached_token()
    spotify = spotipy.Spotify(auth=token_info['access_token'])
    return spotify.current_user()

'''
Following lines allow application to be run more conveniently with
`python app.py` (Make sure you're using python3)
(Also includes directive to leverage pythons threading capacity.)
'''
if __name__ == '__main__':
    app.run(threaded=True, port=int(os.environ.get("PORT",
                                                   os.environ.get("SPOTIPY_REDIRECT_URI", "8080").split(":")[-1])))
</code>```

import React, { useState, useEffect } from "react";
import axios from "axios";

const CurrentUser = () => {
    const [currentUser, setCurrentUser] = useState(null);

  const getCurrentUser = () => {

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    axios.get(`http://127.0.0.1:8080/current_user?code=${code}`).then((response) => {
        setCurrentUser(response.data.display_name);
    }
    );
  };

  return (

      <button onClick={getCurrentUser} style={{"margin": "5px"}}>Get Current User</button>

        {currentUser}

  );
};

export default CurrentUser;

import React, { useState, useEffect } from "react";
import axios from "axios";

const RecentPlay = () => {
  const [recentPlay, setRecentPlay] = useState(null);

  const getRecentPlay = () => {

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    axios.get(`http://127.0.0.1:8080/recently-played?code=${code}`).then((response) => {
      setRecentPlay(response.data.items);
    }
    );
  };

  return (

      <button onClick={getRecentPlay}>Get Recent Play</button>

        {recentPlay &&
          recentPlay.map((item,index) => {
            return (

{item.track.name}

{item.track.artists[0].name}

            );
          })}

  );
};

export default RecentPlay;```

Body:
Working with spotipy library and a React frontend. Used the Flask Spotipy example code as a basis and changed it for testing purposes to see if my idea works. Currently stuck on a bug that I can't seem to understand. I am able to authenticate the user just fine however I can only send ONE api request. After that I get an error similar to this

raise SpotifyOauthError(spotipy.oauth2.SpotifyOauthError: error: invalid_grant, error_description: Invalid authorization code

Not sure if it has to do with refresh tokens but I can never send multiple requests when I authroize a user.

Here is my python code and react code

import os
from flask import Flask, session, request, redirect, jsonify
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(64)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = './.flask_session/'
CORS(app, resources={r"/*": {"origins": "*"}})
Session(app)

client_id = os.getenv("SPOTIPY_CLIENT_ID")
client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")
scope = 'user-read-currently-playing playlist-modify-private user-read-recently-played'
@app.route('/')
def index():

    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(scope=scope,
                                               cache_handler=cache_handler,
                                               show_dialog=True)

    if request.args.get("code"):
        # Step 2. Being redirected from Spotify auth page
        auth_manager.get_access_token(request.args.get("code"))
        session['access_token'] = auth_manager.get_access_token(request.args.get("code"))
        return redirect('http://localhost:3000/?code=' + request.args.get("code"))

    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        # Step 1. Display sign in link when no token
        auth_url = auth_manager.get_authorize_url()
        # let react grab the url
        return jsonify({'url': auth_url})

    # Step 3. Signed in, display data
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return f'[sign out]
' \
           f'my playlists | ' \
           f'currently playing | ' \
        f'me' \

@app.route('/sign_out')
def sign_out():
    session.pop("token_info", None)
    return redirect('/')

@app.route('/recently-played')
def recently_played():
    code = request.args.get('code')
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth.validate_token(cache_handler.get_cached_token()):
        token_info = auth.get_access_token(code)
    else:

        token_info = cache_handler.get_cached_token()
    spotify = spotipy.Spotify(auth=token_info['access_token'])
    return spotify.current_user_recently_played(limit=10)

@app.route('/currently_playing')
def currently_playing():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    track = spotify.current_user_playing_track()
    if not track is None:
        return track
    return "No track currently playing."

@app.route('/current_user')
def current_user():
    code = request.args.get('code')
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth.validate_token(cache_handler.get_cached_token()):
        token_info = auth.get_access_token(code)
    else:

        token_info = cache_handler.get_cached_token()
    spotify = spotipy.Spotify(auth=token_info['access_token'])
    return spotify.current_user()

'''
Following lines allow application to be run more conveniently with
`python app.py` (Make sure you're using python3)
(Also includes directive to leverage pythons threading capacity.)
'''
if __name__ == '__main__':
    app.run(threaded=True, port=int(os.environ.get("PORT",
                                                   os.environ.get("SPOTIPY_REDIRECT_URI", "8080").split(":")[-1])))

import React, { useState, useEffect } from "react";
import axios from "axios";

const CurrentUser = () => {
    const [currentUser, setCurrentUser] = useState(null);

  const getCurrentUser = () => {

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    axios.get(`http://127.0.0.1:8080/current_user?code=${code}`).then((response) => {
        setCurrentUser(response.data.display_name);
    }
    );
  };

  return (

      <button onClick={getCurrentUser} style={{"margin": "5px"}}>Get Current User</button>

        {currentUser}

  );
};

export default CurrentUser;

import React, { useState, useEffect } from "react";
import axios from "axios";

const RecentPlay = () => {
  const [recentPlay, setRecentPlay] = useState(null);

  const getRecentPlay = () => {

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    axios.get(`http://127.0.0.1:8080/recently-played?code=${code}`).then((response) => {
      setRecentPlay(response.data.items);
    }
    );
  };

  return (

      <button onClick={getRecentPlay}>Get Recent Play</button>

        {recentPlay &&
          recentPlay.map((item,index) => {
            return (

{item.track.name}

{item.track.artists[0].name}

            );
          })}

  );
};

export default RecentPlay;


问:
How to get Python code visible in GDB TUI window?
For debugging Python code I use PDB++. It is a nice drop-in replacement for PDB and allows me (in sticky mode) to step through code and interact with it in a text terminal in a visual way.

However, when a Python program is already running, it is not possible to attach to the process and start debugging. That is why I am using GDB here. GDB has been configured and compiled with the --with-python option. Python has been compiled with debug symbols. When I attach to a process, commands like py-list and py-bt work fine. However, I cannot get the Python source code displayed in the TUI, like I can with e.g. C++ program and step in visual mode through code.

I tried creating a new layout, like described in the GDB documentation - TUI commands where I replaced (in a naive way) the tag src for py-list or py-src, but obviously that doesn't work.

Is there a way to have the Python source code in TUI mode and step line by line through the Python script instead of the underlying CPython implementation?


问:
I'm trying to code a random number generator for poker but I keep getting an exception
I am trying to recreate poker in Python and I'm trying to move cards from 2 lists, the deckNumber and deckSuit lists, into playerHand and I'm getting an "empty range for randrange() (0,0, 0)" error when using randint in line 11.

```<code>import random

deckNumber = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
deckSuit = ["Spades", "Diamonds", "Clubs", "Hearts"]
playerHand = []
oppHand = []

for i in range(5):
    number = deckNumber.pop(random.randint(0, len(deckNumber)-1))
    suit = deckSuit.pop(random.randint(0, len(deckSuit)-1))
    playerHand.append(number + " " + suit)

    print(playerHand)
</code>```

I've tried putting another number between 0 and len(deckSuit)-1 but then it says I'm using 4 inputs instead of 3. I've also tried doing len(deckSuit)-2 and just len(deckSuit), but len(deckSuit) gives me an "out of range" error and len(deckSuit)-2 gives me the "empty range" error.

Body:
I am trying to recreate poker in Python and I'm trying to move cards from 2 lists, the deckNumber and deckSuit lists, into playerHand and I'm getting an "empty range for randrange() (0,0, 0)" error when using randint in line 11.

import random

deckNumber = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
deckSuit = ["Spades", "Diamonds", "Clubs", "Hearts"]
playerHand = []
oppHand = []

for i in range(5):
    number = deckNumber.pop(random.randint(0, len(deckNumber)-1))
    suit = deckSuit.pop(random.randint(0, len(deckSuit)-1))
    playerHand.append(number + " " + suit)

    print(playerHand)

I've tried putting another number between 0 and len(deckSuit)-1 but then it says I'm using 4 inputs instead of 3. I've also tried doing len(deckSuit)-2 and just len(deckSuit), but len(deckSuit) gives me an "out of range" error and len(deckSuit)-2 gives me the "empty range" error.


问:
how do I concatenate a variable container using a variable+ a string

type = "grass"
grassStrong = ["water", "ground", "rock"];
console.log(this[type + "Strong"])```

Is there a way to get something like this to work? i have multiple lists that are "type" strong, "type" weak and it would be much easier to use these lists if I can just concatenate the container in this way. I want to put 2 strings together to get a variable

Body:
type = "grass"
grassStrong = ["water", "ground", "rock"];
console.log(this[type + "Strong"])

Is there a way to get something like this to work? i have multiple lists that are "type" strong, "type" weak and it would be much easier to use these lists if I can just concatenate the container in this way. I want to put 2 strings together to get a variable


问:
useProgress React three drei always goes from 0 to 100
I'm using useProgress from react three drei. Apparently, this is used to keep track of the loading state from the models on the scene. I have created a loading screen with a progress bar in which I will be showing the loading state from this progress. But, In all occasions, the progress always goes from 0 to 100 instantly, it does not go from 0...45...50..90.100. Which I believe is wrong, since I have some large models.

This is the base experience component.

```<code>import { Dispatch, SetStateAction, Suspense, useRef, useState } from "react";
import OrbitControls from "./components/OrbitControls";
import { Perf } from "r3f-perf";
import { ObjectForReference } from "./components/ObjectForReference";
import * as THREE from "three";
import Room from "./components/Room";
import useLevaControls from "./hook/useLevaControls";
import OverlayLoading from "./components/OverlayLoading";

interface ExperienceProps {
  setHiddenLeva: Dispatch<SetStateAction<boolean>>;
}

export default function Experience({ setHiddenLeva }: ExperienceProps) {
  const invisibleObjectRef = useRef<THREE.Mesh | null>(null);
  const [orbitControlsDisabled, setOrbitControlsDisabled] =
    useState<boolean>(false);
  // Hide overaly
  const [hideOverlay, setHideOverlay] = useState<boolean>(false);
  const [isPointerOnHtml, setIsPointerOnHtml] = useState<boolean>(false);
  const { viewWebpage, showPerformace } = useLevaControls();

  return (
    <>
      <color args={["#2E282A"]} attach="background" />

      {showPerformace && <Perf position="top-left" />}

      <OrbitControls
        invisibleObjectRef={invisibleObjectRef}
        isPointerOnHtml={isPointerOnHtml}
        focusOnHtml={viewWebpage}
        disabled={orbitControlsDisabled}
      />

      <ObjectForReference
        meshRef={invisibleObjectRef}
        position={new THREE.Vector3(-4, 1.7, 0)}
      />

      {!hideOverlay && (
        <OverlayLoading
          setOrbitControlsDisabled={setOrbitControlsDisabled}
          setHiddenLeva={setHiddenLeva}
          setHideOverlay={setHideOverlay}
        />
      )}

      <Suspense>
        <Room
          setIsPointerOnHtml={setIsPointerOnHtml}
          isFocusOnHtml={viewWebpage}
        />
      </Suspense>
    </>
  );
}
</code>```

As you can see I added some suspense on the Room component so I can render the OveralyLoading first.

This is to render some presentation data:

```<code>import "./index.css";
import { useState, useCallback, Dispatch, SetStateAction } from "react";
import { Html } from "@react-three/drei";
import IntroOne from "../IntroScreens/IntroOne";
import IntroTwo from "../IntroScreens/IntroTwo";
import IntroThree from "../IntroScreens/IntroThree";

interface HtmlOverlayProps {
  setOrbitControlsDisabled: Dispatch<SetStateAction<boolean>>;
  setHiddenLeva: Dispatch<SetStateAction<boolean>>;
  setHideOverlay: Dispatch<SetStateAction<boolean>>;
  planeMeshRef: any;
}

export default function HtmlOverlay({
  setHideOverlay,
  setHiddenLeva,
  setOrbitControlsDisabled,
  planeMeshRef,
}: HtmlOverlayProps) {
  const [presentationScreens, setPresentationScreens] = useState(0);

  const handlePresentationScreen = useCallback(() => {
    switch (presentationScreens) {
      case 0:
        return <IntroOne setPresentationScreens={setPresentationScreens} />;
      case 1:
        return <IntroTwo setPresentationScreens={setPresentationScreens} />;
      case 2:
        return (
          <IntroThree
            setHideOverlay={setHideOverlay}
            setHiddenLeva={setHiddenLeva}
            setOrbitControlsDisabled={setOrbitControlsDisabled}
            planeMeshRef={planeMeshRef}
          />
        );
    }
  }, [
    planeMeshRef,
    presentationScreens,
    setHiddenLeva,
    setHideOverlay,
    setOrbitControlsDisabled,
  ]);

  return (
    <Html fullscreen className="htmlComponent">
      {handlePresentationScreen()}
    </Html>
  );
}

</code>```

The screen inside the Overlay loading, keeps track of the progress:

```<code>import { Dispatch, SetStateAction, useEffect } from "react";
import { useProgress } from "@react-three/drei";
import gsap from "gsap";

interface IntroOneProps {
  setPresentationScreens: Dispatch<SetStateAction<number>>;
}

export default function IntroOne({ setPresentationScreens }: IntroOneProps) {
  const { progress } = useProgress();

  useEffect(() => {
    if (progress === 100) {
      setTimeout(() => {
        gsap.to(".opacityControl", {
          opacity: 0,
          onComplete: () => {
            setPresentationScreens(1);
          },
        });
      }, 1500);
    }
  }, [progress, setPresentationScreens]);

  return (
    <div className="localHtml opacityControl">
      <div className="commonHtml">
        <div style={{ marginBottom: 20 }}>
          <span className="introText">We are loading your experience</span>
        </div>

        <div className="progressBar">
          <div
            style={{
              height: "100%",
              borderRadius: 10,
              width: `${progress}%`,
              backgroundColor: "#0061FF",
            }}
          ></div>
        </div>
      </div>
    </div>
  );
}

</code>```

Body:
I'm using useProgress from react three drei. Apparently, this is used to keep track of the loading state from the models on the scene. I have created a loading screen with a progress bar in which I will be showing the loading state from this progress. But, In all occasions, the progress always goes from 0 to 100 instantly, it does not go from 0...45...50..90.100. Which I believe is wrong, since I have some large models.

This is the base experience component.

import { Dispatch, SetStateAction, Suspense, useRef, useState } from "react";
import OrbitControls from "./components/OrbitControls";
import { Perf } from "r3f-perf";
import { ObjectForReference } from "./components/ObjectForReference";
import * as THREE from "three";
import Room from "./components/Room";
import useLevaControls from "./hook/useLevaControls";
import OverlayLoading from "./components/OverlayLoading";

interface ExperienceProps {
  setHiddenLeva: Dispatch<SetStateAction<boolean>>;
}

export default function Experience({ setHiddenLeva }: ExperienceProps) {
  const invisibleObjectRef = useRef<THREE.Mesh | null>(null);
  const [orbitControlsDisabled, setOrbitControlsDisabled] =
    useState<boolean>(false);
  // Hide overaly
  const [hideOverlay, setHideOverlay] = useState<boolean>(false);
  const [isPointerOnHtml, setIsPointerOnHtml] = useState<boolean>(false);
  const { viewWebpage, showPerformace } = useLevaControls();

  return (
    <>
      <color args={["#2E282A"]} attach="background" />

      {showPerformace && <Perf position="top-left" />}

      <OrbitControls
        invisibleObjectRef={invisibleObjectRef}
        isPointerOnHtml={isPointerOnHtml}
        focusOnHtml={viewWebpage}
        disabled={orbitControlsDisabled}
      />

      <ObjectForReference
        meshRef={invisibleObjectRef}
        position={new THREE.Vector3(-4, 1.7, 0)}
      />

      {!hideOverlay && (
        <OverlayLoading
          setOrbitControlsDisabled={setOrbitControlsDisabled}
          setHiddenLeva={setHiddenLeva}
          setHideOverlay={setHideOverlay}
        />
      )}

      <Suspense>
        <Room
          setIsPointerOnHtml={setIsPointerOnHtml}
          isFocusOnHtml={viewWebpage}
        />
      </Suspense>
    </>
  );
}

As you can see I added some suspense on the Room component so I can render the OveralyLoading first.

This is to render some presentation data:

import "./index.css";
import { useState, useCallback, Dispatch, SetStateAction } from "react";
import { Html } from "@react-three/drei";
import IntroOne from "../IntroScreens/IntroOne";
import IntroTwo from "../IntroScreens/IntroTwo";
import IntroThree from "../IntroScreens/IntroThree";

interface HtmlOverlayProps {
  setOrbitControlsDisabled: Dispatch<SetStateAction<boolean>>;
  setHiddenLeva: Dispatch<SetStateAction<boolean>>;
  setHideOverlay: Dispatch<SetStateAction<boolean>>;
  planeMeshRef: any;
}

export default function HtmlOverlay({
  setHideOverlay,
  setHiddenLeva,
  setOrbitControlsDisabled,
  planeMeshRef,
}: HtmlOverlayProps) {
  const [presentationScreens, setPresentationScreens] = useState(0);

  const handlePresentationScreen = useCallback(() => {
    switch (presentationScreens) {
      case 0:
        return <IntroOne setPresentationScreens={setPresentationScreens} />;
      case 1:
        return <IntroTwo setPresentationScreens={setPresentationScreens} />;
      case 2:
        return (
          <IntroThree
            setHideOverlay={setHideOverlay}
            setHiddenLeva={setHiddenLeva}
            setOrbitControlsDisabled={setOrbitControlsDisabled}
            planeMeshRef={planeMeshRef}
          />
        );
    }
  }, [
    planeMeshRef,
    presentationScreens,
    setHiddenLeva,
    setHideOverlay,
    setOrbitControlsDisabled,
  ]);

  return (

      {handlePresentationScreen()}

  );
}

The screen inside the Overlay loading, keeps track of the progress:

import { Dispatch, SetStateAction, useEffect } from "react";
import { useProgress } from "@react-three/drei";
import gsap from "gsap";

interface IntroOneProps {
  setPresentationScreens: Dispatch<SetStateAction<number>>;
}

export default function IntroOne({ setPresentationScreens }: IntroOneProps) {
  const { progress } = useProgress();

  useEffect(() => {
    if (progress === 100) {
      setTimeout(() => {
        gsap.to(".opacityControl", {
          opacity: 0,
          onComplete: () => {
            setPresentationScreens(1);
          },
        });
      }, 1500);
    }
  }, [progress, setPresentationScreens]);

  return (

          We are loading your experience

          <div
            style={{
              height: "100%",
              borderRadius: 10,
              width: `${progress}%`,
              backgroundColor: "#0061FF",
            }}
          >

  );
}


问:
Put text containing lots of quotes inside a String
I have a very long text when I try to put it in a String variable inside a quote mark or a double quote mark an error occurs because the text contains a lot of single and double quotes and some of them are not closed, is there a solution other than deleting the quotes from the text?

I use flutter.

and this is the text:

```<code>Once upon a time, in a small village nestled in the rolling hills of the countryside, there lived a young boy named Jack. Jack was a curious and adventurous boy who loved to explore the fields and forests around his village.
One day, as he was walking through the woods, he came upon a beautiful clearing filled with wildflowers. In the center of the clearing stood a large, old oak tree. As Jack walked closer to the tree, he noticed a small door set into the trunk.
Intrigued, Jack pushed open the door and peered inside. To his surprise, he saw a tiny, cozy room filled with all sorts of treasures: shiny jewels, golden coins, and sparkling crystals. Jack couldn't believe his eyes!
As he reached out to touch the glittering jewels, a soft voice spoke from behind him. "Who are you, and what are you doing in my tree?"
Startled, Jack turned around to see a tiny fairy with shimmering wings and a bright smile. "I'm sorry," said Jack, bowing his head. "I didn't mean to intrude. I was just exploring and I saw the door and couldn't resist coming in."
The fairy chuckled and flew closer to Jack. "There's no need to apologize, dear boy," she said. "I'm glad you found my tree. It's not often that humans stumble upon my home. My name is Luna, and I'm the guardian of this forest."
Jack's eyes widened in amazement. "A guardian fairy! I've never met one before. Can you grant me wishes, like in the stories?"
Luna laughed and shook her head. "I'm afraid not, dear Jack. But I can give you a gift, if you'd like. Choose something from my treasure trove to take with you on your adventures."
Jack thought for a moment, then reached for a small, shimmering crystal. "This one, please," he said, holding it up for Luna to see.
"Ah, a wise choice," said Luna, smiling. "That crystal will bring you good luck and protect you on your travels."
With a grateful heart, Jack thanked Luna and promised to take good care of the crystal. And as he left the tree and made his way back through the woods, he felt a sense of magic and wonder surrounding him, knowing that he had made a new friend in the magical guardian of the forest.
</code>```

Body:
I have a very long text when I try to put it in a String variable inside a quote mark or a double quote mark an error occurs because the text contains a lot of single and double quotes and some of them are not closed, is there a solution other than deleting the quotes from the text?

I use flutter.

and this is the text:

Once upon a time, in a small village nestled in the rolling hills of the countryside, there lived a young boy named Jack. Jack was a curious and adventurous boy who loved to explore the fields and forests around his village.
One day, as he was walking through the woods, he came upon a beautiful clearing filled with wildflowers. In the center of the clearing stood a large, old oak tree. As Jack walked closer to the tree, he noticed a small door set into the trunk.
Intrigued, Jack pushed open the door and peered inside. To his surprise, he saw a tiny, cozy room filled with all sorts of treasures: shiny jewels, golden coins, and sparkling crystals. Jack couldn't believe his eyes!
As he reached out to touch the glittering jewels, a soft voice spoke from behind him. "Who are you, and what are you doing in my tree?"
Startled, Jack turned around to see a tiny fairy with shimmering wings and a bright smile. "I'm sorry," said Jack, bowing his head. "I didn't mean to intrude. I was just exploring and I saw the door and couldn't resist coming in."
The fairy chuckled and flew closer to Jack. "There's no need to apologize, dear boy," she said. "I'm glad you found my tree. It's not often that humans stumble upon my home. My name is Luna, and I'm the guardian of this forest."
Jack's eyes widened in amazement. "A guardian fairy! I've never met one before. Can you grant me wishes, like in the stories?"
Luna laughed and shook her head. "I'm afraid not, dear Jack. But I can give you a gift, if you'd like. Choose something from my treasure trove to take with you on your adventures."
Jack thought for a moment, then reached for a small, shimmering crystal. "This one, please," he said, holding it up for Luna to see.
"Ah, a wise choice," said Luna, smiling. "That crystal will bring you good luck and protect you on your travels."
With a grateful heart, Jack thanked Luna and promised to take good care of the crystal. And as he left the tree and made his way back through the woods, he felt a sense of magic and wonder surrounding him, knowing that he had made a new friend in the magical guardian of the forest.


问:
How to cache data into Pyspark before using multiple sql.write functions properly
I'm new to pyspark, and I'm trying to create a Insert Update component.

Basically I got a dataframe, "df", with a column named "action", where I can filter the actions between "insert" and "update". The code looks something like that:

```<code>df_to_insert = df.filter(df.action == 1)
df_to_upsert = df.filter(df.action == 2)
</code>```

What I'm trying to do is chaching the dataframe df, this way I can use a count operation to see if there is any row to update or to insert in a faster way:

```<code>cached_dataframe = df.cache()
df_to_insert = df.filter(df.action == 1)
df_to_update = df.filter(df.action == 2)

if df_to_insert.count() != 0:
    #insert rows

if df_to_update.count() != 0:
    #update rows
</code>```

As you should know, the first count is quite slow, once the pyspark applies all the transformations required, but the second one is much faster, since I cached the dataframe df.

After chaching the data and diving it between insert and update I just need to drop the "action" column, then I'm using the io.github.spark_redshift_community.spark.redshift connector to perform a write function into a redshift database. The code looks like this:

```<code>df_to_insert.write.format("io.github.spark_redshift_community.spark.redshift").options(
            url=f"jdbc:redshift://{HOST_REDSHIFT}:{PORT_REDSHIFT}/{DATABASE_REDSHIFT}",
            user=USER_REDSHIFT,
            password=PASSWORD_REDSHIFT,
            tempdir= f"s3a://{S3_BUCKET}/test_folder",
            dbtable=table,
            forward_spark_s3_credentials="true",
            fetchsize="100000") \
        .mode("append").save()
</code>```

But performing the insert with cached data to a database is taking to long.

What is the best approach here?
Should I cache the data in this case?
If so, what am I doing wrong?

Thank you in advance!

Body:
I'm new to pyspark, and I'm trying to create a Insert Update component.

Basically I got a dataframe, "df", with a column named "action", where I can filter the actions between "insert" and "update". The code looks something like that:

df_to_insert = df.filter(df.action == 1)
df_to_upsert = df.filter(df.action == 2)

What I'm trying to do is chaching the dataframe df, this way I can use a count operation to see if there is any row to update or to insert in a faster way:

cached_dataframe = df.cache()
df_to_insert = df.filter(df.action == 1)
df_to_update = df.filter(df.action == 2)

if df_to_insert.count() != 0:
    #insert rows

if df_to_update.count() != 0:
    #update rows

As you should know, the first count is quite slow, once the pyspark applies all the transformations required, but the second one is much faster, since I cached the dataframe df.

After chaching the data and diving it between insert and update I just need to drop the "action" column, then I'm using the io.github.spark_redshift_community.spark.redshift connector to perform a write function into a redshift database. The code looks like this:

df_to_insert.write.format("io.github.spark_redshift_community.spark.redshift").options(
            url=f"jdbc:redshift://{HOST_REDSHIFT}:{PORT_REDSHIFT}/{DATABASE_REDSHIFT}",
            user=USER_REDSHIFT,
            password=PASSWORD_REDSHIFT,
            tempdir= f"s3a://{S3_BUCKET}/test_folder",
            dbtable=table,
            forward_spark_s3_credentials="true",
            fetchsize="100000") \
        .mode("append").save()

But performing the insert with cached data to a database is taking to long.

What is the best approach here?
Should I cache the data in this case?
If so, what am I doing wrong?

Thank you in advance!


问:
problems with the event.MOUSEBUTTONDOWN in pygame glitches when executed
I am trying to create a tic-tac-toe game in python using the pygame library and went as far as drawing X's on each rectangle in a grid that is clicked on and simultinously drawing circles in any random ractangle in that grid, but the problem here is that most of times when i boot up the program and click on 4 rectangles only three circles appear or even only two appear and some times it works just fine.

Here is my code:

```<code>import pygame
import random

white = (245, 243, 232)
hight = 3
width = 3
size = 167

screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Tic Tac Toe")
screen.fill(white)

for i in range(0, hight):
    for j in range(0, width):
        pygame.draw.rect(screen, "Black", (i*size, j*size, size, size), 1)

def rect(x, y):
# Return the Rect object created by the draw.rect method
    return pygame.draw.rect(screen, white, (x, y, 163, 163), 0)

rect1 = rect(2, 2)
rect2 = rect(169, 2)
rect3 = rect(336, 2)
rect4 = rect(2, 169)
rect5 = rect(169, 169)
rect6 = rect(336, 169)
rect7 = rect(2, 336)
rect8 = rect(169, 336)
rect9 = rect(336, 336)

def cross(x, y):
    pygame.draw.line(screen, "Black", (x, y), (x + 166, y + 166), 3)
    pygame.draw.line(screen, "Black", (x + 166, y-2), (x-2 , y + 166), 3)

    pygame.display.update()

def circle(x, y):
    pygame.draw.circle(screen, "Black", (x + 81.5, y + 81.5), 50, 3)

    pygame.display.update()

flag = False
flag_ = False
flag__ = False
flag___= False
flag____ = False
flag_____= False
flag______= False
flag_______= False
flag________= False
pygame.display.update()

rectch = [rect1, rect2, rect3, rect4, rect5, rect6, rect7, rect8, rect9]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            if rect1.collidepoint(pos) and not flag:
                cross(2,2)
                rectch.remove(rect1)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag = True
            elif rect2.collidepoint(pos) and not flag_:
                cross(169,2)
                rectch.remove(rect2)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag_ = True
            elif rect3.collidepoint(pos) and not flag__:
                cross(336,2)
                rectch.remove(rect3)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag__ = True
            elif rect4.collidepoint(pos) and not flag___:
                cross(2,169)
                rectch.remove(rect4)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag___ = True
            elif rect5.collidepoint(pos) and not flag____:
                cross(169,169)
                flag____ = True
            elif rect6.collidepoint(pos) and not flag_____:
                cross(336,169)
                flag_____ = True
            elif rect7.collidepoint(pos) and not flag______:
                cross(2,336)
                flag______ = True
            elif rect8.collidepoint(pos) and not flag_______:
                cross(169,336)
                flag_______ = True
            elif rect9.collidepoint(pos) and not flag________:
                cross(336,336)
                flag________ = True

</code>```

now you might see in the code block that i tried to print "here" in 4 conditional statments in the while loop i tried to do that so i could see if the circle function is called  when i click on that certian rect and low and behold 4 of them print out just fine on each execution so i dont know what is happeneing here.

i know its hard to image the process so here are some pictures that could describe the problem:

[this is when i click on 4 rectangles but only three circles are produced]

[this when i click on 4 rectangles and all 4 circles are produced and is working fine (please keep in mind that i did not change the code)]

Body:
I am trying to create a tic-tac-toe game in python using the pygame library and went as far as drawing X's on each rectangle in a grid that is clicked on and simultinously drawing circles in any random ractangle in that grid, but the problem here is that most of times when i boot up the program and click on 4 rectangles only three circles appear or even only two appear and some times it works just fine.

Here is my code:

import pygame
import random

white = (245, 243, 232)
hight = 3
width = 3
size = 167

screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Tic Tac Toe")
screen.fill(white)

for i in range(0, hight):
    for j in range(0, width):
        pygame.draw.rect(screen, "Black", (i*size, j*size, size, size), 1)

def rect(x, y):
# Return the Rect object created by the draw.rect method
    return pygame.draw.rect(screen, white, (x, y, 163, 163), 0)

rect1 = rect(2, 2)
rect2 = rect(169, 2)
rect3 = rect(336, 2)
rect4 = rect(2, 169)
rect5 = rect(169, 169)
rect6 = rect(336, 169)
rect7 = rect(2, 336)
rect8 = rect(169, 336)
rect9 = rect(336, 336)

def cross(x, y):
    pygame.draw.line(screen, "Black", (x, y), (x + 166, y + 166), 3)
    pygame.draw.line(screen, "Black", (x + 166, y-2), (x-2 , y + 166), 3)

    pygame.display.update()

def circle(x, y):
    pygame.draw.circle(screen, "Black", (x + 81.5, y + 81.5), 50, 3)

    pygame.display.update()

flag = False
flag_ = False
flag__ = False
flag___= False
flag____ = False
flag_____= False
flag______= False
flag_______= False
flag________= False
pygame.display.update()

rectch = [rect1, rect2, rect3, rect4, rect5, rect6, rect7, rect8, rect9]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            if rect1.collidepoint(pos) and not flag:
                cross(2,2)
                rectch.remove(rect1)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag = True
            elif rect2.collidepoint(pos) and not flag_:
                cross(169,2)
                rectch.remove(rect2)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag_ = True
            elif rect3.collidepoint(pos) and not flag__:
                cross(336,2)
                rectch.remove(rect3)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag__ = True
            elif rect4.collidepoint(pos) and not flag___:
                cross(2,169)
                rectch.remove(rect4)
                chosen_rect = random.choice(rectch)
                x, y = chosen_rect.topleft
                circle(x, y)
                print("here")
                flag___ = True
            elif rect5.collidepoint(pos) and not flag____:
                cross(169,169)
                flag____ = True
            elif rect6.collidepoint(pos) and not flag_____:
                cross(336,169)
                flag_____ = True
            elif rect7.collidepoint(pos) and not flag______:
                cross(2,336)
                flag______ = True
            elif rect8.collidepoint(pos) and not flag_______:
                cross(169,336)
                flag_______ = True
            elif rect9.collidepoint(pos) and not flag________:
                cross(336,336)
                flag________ = True

now you might see in the code block that i tried to print "here" in 4 conditional statments in the while loop i tried to do that so i could see if the circle function is called  when i click on that certian rect and low and behold 4 of them print out just fine on each execution so i dont know what is happeneing here.

i know its hard to image the process so here are some pictures that could describe the problem:

[this is when i click on 4 rectangles but only three circles are produced]

[this when i click on 4 rectangles and all 4 circles are produced and is working fine (please keep in mind that i did not change the code)]