问:
semaphore barriers exercise os three easy pieces
I am reading the book OS three easy pieces, In the semaphore chapter I am going through barrier.c question.

Below is the code that needs to be completed for the desired output:

```<code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sched.h>

// If done correctly, each child should print their "before" message
// before either prints their "after" message. Test by adding sleep(1)
// calls in various locations.

// You likely need two semaphores to do this correctly, and some
// other integers to track things.

typedef struct __barrier_t {
    // add semaphores and other information here
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
}

void barrier(barrier_t *b) {
    // barrier code goes here
}

//
// XXX: don't change below here (just run it!)
//
typedef struct __tinfo_t {
    int thread_id;
} tinfo_t;

void *child(void *arg) {
    tinfo_t *t = (tinfo_t *) arg;
    printf("child %d: before\n", t->thread_id);
    barrier(&b);
    printf("child %d: after\n", t->thread_id);
    return NULL;
}

// run with a single argument indicating the number of
// threads you wish to create (1 or more)
int main(int argc, char *argv[]) {
    assert(argc == 2);
    int num_threads = atoi(argv[1]);
    assert(num_threads > 0);

    pthread_t p[num_threads];
    tinfo_t t[num_threads];

    printf("parent: begin\n");
    barrier_init(&b, num_threads);

    int i;
    for (i = 0; i < num_threads; i++) {
    t[i].thread_id = i;
    Pthread_create(&p[i], NULL, child, &t[i]);
    }

    for (i = 0; i < num_threads; i++)
    Pthread_join(p[i], NULL);

    printf("parent: end\n");
    return 0;
}
</code>```

I have add the code and its giving the desired output but I am not sure In the questiing hint is to use 2 semaphore but I have used only one to accomplish the task
Below is my code:

```<code>typedef struct __barrier_t {
    // add semaphores and other information here
    //sem_t s;
    sem_t lock;
    int n_threads;
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
    //sem_init(&b->s, 0, 0);
    sem_init(&b->lock, 0, 1);
    b->n_threads = num_threads;
}

void barrier(barrier_t *b) {
    // barrier code goes here
    sem_wait(&b->lock);
    b->n_threads--;
    sem_post(&b->lock);

    while(b->n_threads >= 1) {
        //pthread_yield();      // causes the calling thread to relinquish the CPU.
        sched_yield();      // force the running thread to relinquish the processor
    }
}
</code>```

I just wanted to know is i am in right direction or I am missing something, Thanks.

Complete code

```<code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sched.h>

// If done correctly, each child should print their "before" message
// before either prints their "after" message. Test by adding sleep(1)
// calls in various locations.

// You likely need two semaphores to do this correctly, and some
// other integers to track things.

typedef struct __barrier_t {
    // add semaphores and other information here
    //sem_t s;
    sem_t lock;
    int n_threads;
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
    //sem_init(&b->s, 0, 0);
    sem_init(&b->lock, 0, 1);
    b->n_threads = num_threads;
}

void barrier(barrier_t *b) {
    // barrier code goes here
    sem_wait(&b->lock);
    b->n_threads--;
    sem_post(&b->lock);

    while(b->n_threads >= 1) {
        //pthread_yield();      // causes the calling thread to relinquish the CPU.
        sched_yield();      // force the running thread to relinquish the processor
    }
}

//
// XXX: don't change below here (just run it!)
//
typedef struct __tinfo_t {
    int thread_id;
} tinfo_t;

void *child(void *arg) {
    tinfo_t *t = (tinfo_t *) arg;
    printf("child %d: before\n", t->thread_id);
    barrier(&b);
    printf("child %d: after\n", t->thread_id);
    return NULL;
}

// run with a single argument indicating the number of
// threads you wish to create (1 or more)
int main(int argc, char *argv[]) {
    assert(argc == 2);
    int num_threads = atoi(argv[1]);
    assert(num_threads > 0);

    pthread_t p[num_threads];
    tinfo_t t[num_threads];

    printf("parent: begin\n");
    barrier_init(&b, num_threads);

    int i;
    for (i = 0; i < num_threads; i++) {
    t[i].thread_id = i;
    pthread_create(&p[i], NULL, child, &t[i]);
    }

    for (i = 0; i < num_threads; i++)
    pthread_join(p[i], NULL);

    printf("parent: end\n");
    return 0;
}
</code>```

Compile:
$ gcc -g -Wall -l pthread barrier.c

output:

```<code> $ ./a.out 5
parent: begin
child 0: before
child 1: before
child 2: before
child 3: before
child 4: before
child 4: after
child 0: after
child 2: after
child 3: after
child 1: after
parent: end
</code>```

Body:
I am reading the book OS three easy pieces, In the semaphore chapter I am going through barrier.c question.

Below is the code that needs to be completed for the desired output:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sched.h>

// If done correctly, each child should print their "before" message
// before either prints their "after" message. Test by adding sleep(1)
// calls in various locations.

// You likely need two semaphores to do this correctly, and some
// other integers to track things.

typedef struct __barrier_t {
    // add semaphores and other information here
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
}

void barrier(barrier_t *b) {
    // barrier code goes here
}

//
// XXX: don't change below here (just run it!)
//
typedef struct __tinfo_t {
    int thread_id;
} tinfo_t;

void *child(void *arg) {
    tinfo_t *t = (tinfo_t *) arg;
    printf("child %d: before\n", t->thread_id);
    barrier(&b);
    printf("child %d: after\n", t->thread_id);
    return NULL;
}

// run with a single argument indicating the number of
// threads you wish to create (1 or more)
int main(int argc, char *argv[]) {
    assert(argc == 2);
    int num_threads = atoi(argv[1]);
    assert(num_threads > 0);

    pthread_t p[num_threads];
    tinfo_t t[num_threads];

    printf("parent: begin\n");
    barrier_init(&b, num_threads);

    int i;
    for (i = 0; i < num_threads; i++) {
    t[i].thread_id = i;
    Pthread_create(&p[i], NULL, child, &t[i]);
    }

    for (i = 0; i < num_threads; i++)
    Pthread_join(p[i], NULL);

    printf("parent: end\n");
    return 0;
}

I have add the code and its giving the desired output but I am not sure In the questiing hint is to use 2 semaphore but I have used only one to accomplish the task
Below is my code:

typedef struct __barrier_t {
    // add semaphores and other information here
    //sem_t s;
    sem_t lock;
    int n_threads;
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
    //sem_init(&b->s, 0, 0);
    sem_init(&b->lock, 0, 1);
    b->n_threads = num_threads;
}

void barrier(barrier_t *b) {
    // barrier code goes here
    sem_wait(&b->lock);
    b->n_threads--;
    sem_post(&b->lock);

    while(b->n_threads >= 1) {
        //pthread_yield();      // causes the calling thread to relinquish the CPU.
        sched_yield();      // force the running thread to relinquish the processor
    }
}

I just wanted to know is i am in right direction or I am missing something, Thanks.

Complete code

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sched.h>

// If done correctly, each child should print their "before" message
// before either prints their "after" message. Test by adding sleep(1)
// calls in various locations.

// You likely need two semaphores to do this correctly, and some
// other integers to track things.

typedef struct __barrier_t {
    // add semaphores and other information here
    //sem_t s;
    sem_t lock;
    int n_threads;
} barrier_t;

// the single barrier we are using for this program
barrier_t b;

void barrier_init(barrier_t *b, int num_threads) {
    // initialization code goes here
    //sem_init(&b->s, 0, 0);
    sem_init(&b->lock, 0, 1);
    b->n_threads = num_threads;
}

void barrier(barrier_t *b) {
    // barrier code goes here
    sem_wait(&b->lock);
    b->n_threads--;
    sem_post(&b->lock);

    while(b->n_threads >= 1) {
        //pthread_yield();      // causes the calling thread to relinquish the CPU.
        sched_yield();      // force the running thread to relinquish the processor
    }
}

//
// XXX: don't change below here (just run it!)
//
typedef struct __tinfo_t {
    int thread_id;
} tinfo_t;

void *child(void *arg) {
    tinfo_t *t = (tinfo_t *) arg;
    printf("child %d: before\n", t->thread_id);
    barrier(&b);
    printf("child %d: after\n", t->thread_id);
    return NULL;
}

// run with a single argument indicating the number of
// threads you wish to create (1 or more)
int main(int argc, char *argv[]) {
    assert(argc == 2);
    int num_threads = atoi(argv[1]);
    assert(num_threads > 0);

    pthread_t p[num_threads];
    tinfo_t t[num_threads];

    printf("parent: begin\n");
    barrier_init(&b, num_threads);

    int i;
    for (i = 0; i < num_threads; i++) {
    t[i].thread_id = i;
    pthread_create(&p[i], NULL, child, &t[i]);
    }

    for (i = 0; i < num_threads; i++)
    pthread_join(p[i], NULL);

    printf("parent: end\n");
    return 0;
}

Compile:
$ gcc -g -Wall -l pthread barrier.c

output:

 $ ./a.out 5
parent: begin
child 0: before
child 1: before
child 2: before
child 3: before
child 4: before
child 4: after
child 0: after
child 2: after
child 3: after
child 1: after
parent: end


来源: stackexchange

问:
Error launching application on sdk gphone64 x86 64
I am new to flutter, and I use the VS code for flutter coding, and android studio for emulaters.
When I tried to run the flutter app in the emulater I got this message:

cmd: Can't find service: activity

Installing build\app\outputs\flutter-apk\app.apk... 2,951ms

Error: ADB exitedwith exit code 1

Performing Streamed Install

adb: failed to install
C:\Users\Mosh\Desktop\SoftwareDevelopment\Projects\flutter\first_app\build\app\outputs\flutter-apk\app.apk:
Error launching application on sdk gphone64 x86 64.

the app is running very well on chrome, but the problem appears when trying to run it on android studio emulater?

ContentLicense: CC BY-SA 4.0


问:
Comparing two list of objects in Python
I have class Host, which has properties ip and ports

```<code>class Host:
    def __init__(self, ip):
        self.ip = ip
        self.ports = []
</code>```

I have two lists of objects: old_hosts and new_hosts. Now I want to compare these lists and found new host or only host with new opened ports. Does exists some special function in python, which could compare these lists?

E.g.

```<code>old_hosts:
[0] ip: 192.168.1.1, ports: 53,80
[1] ip: 192.168.1.2, ports: 53,80
[2] ip: 192.168.1.3, ports: 53,80

new_hosts:
[0] ip: 192.168.1.1, ports: 53,80
[1] ip: 192.168.1.2, ports: 53,80,443
[2] ip: 192.168.1.3, ports: 53,80
[3] ip: 192.168.1.4, ports: 53,80
</code>```

And I would like to get something like this

```<code>New discovered host 192.168.1.4
New discovered port 443 on host 192.168.1.2
</code>```

I have solved this problem by three nested for loops, but I don't like this solution. I think there is exists some better way how to do it.

Title: Comparing two list of objects in Python

Body:
I have class Host, which has properties ip and ports

class Host:
    def __init__(self, ip):
        self.ip = ip
        self.ports = []

I have two lists of objects: old_hosts and new_hosts. Now I want to compare these lists and found new host or only host with new opened ports. Does exists some special function in python, which could compare these lists?

E.g.

old_hosts:
[0] ip: 192.168.1.1, ports: 53,80
[1] ip: 192.168.1.2, ports: 53,80
[2] ip: 192.168.1.3, ports: 53,80

new_hosts:
[0] ip: 192.168.1.1, ports: 53,80
[1] ip: 192.168.1.2, ports: 53,80,443
[2] ip: 192.168.1.3, ports: 53,80
[3] ip: 192.168.1.4, ports: 53,80

And I would like to get something like this

New discovered host 192.168.1.4
New discovered port 443 on host 192.168.1.2

I have solved this problem by three nested for loops, but I don't like this solution. I think there is exists some better way how to do it.


问:
After uninstallation SSL get CSRF verification failed
My Domain SSL certificate expired. But after that when I try to login I am getting "CSRF verification failed. Request aborted." error message. But before that my apps working well over the year. Still my app working on SSL domains but not in Non SSL Domain. I am using sub domains. my login form are given bellow:

```<code>   <form class="login-form" action="{% url 'login' %}" method="post">
         {% csrf_token %}
   <div class="form-group">
   <label for="exampleInputUsername" class="text-uppercase">Username</label>
   <input type="text" name="username" placeholder="Enter your username">

   </div>
   <div class="form-group">
   <label for="exampleInputPassword1" class="text-uppercase">Password</label>
   <input type="password" name="password" placeholder="Enter Your Password">
   </div>
   <div class="form-check">
   <button type="submit" class="btn btn-login float-right">Submit</button>
   </div>
   </form>
</code>```

I am getting same error on login admin page also

Body:
My Domain SSL certificate expired. But after that when I try to login I am getting "CSRF verification failed. Request aborted." error message. But before that my apps working well over the year. Still my app working on SSL domains but not in Non SSL Domain. I am using sub domains. my login form are given bellow:

   <form class="login-form" action="{% url 'login' %}" method="post">
         {% csrf_token %}

   Username
   <input type="text" name="username" placeholder="Enter your username">

   Password
   <input type="password" name="password" placeholder="Enter Your Password">

   <button type="submit" class="btn btn-login float-right">Submit</button>

   </form>

I am getting same error on login admin page also


问:
how to refresh some bottom navbar pages with IndexedStack? flutter
I have 5 pages in my app and I'm using a BottomNavigationBar to separate and access them. I had problem with my 'categories' page because I didn't want it to be reloaded each time I select it from navbar.

so I used an IndexedStack to prevent it from reloading and it worked fine. now I want my 'favourites' page to be reloaded each time the user goes to favourites page. how can I do that?

```<code>bottomNavigationBar: BottomNavigationBar(
  currentIndex: _selectedIndex,
  selectedItemColor: Colors.white,
  onTap: _onItemTapped,
  items: <BottomNavigationBarItem>[
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
     ...
    ),
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
    ...
    ),
  ],

),
body: isLoaded?
IndexedStack(children: _pageOptions,index: _selectedIndex,):Container()
</code>```

Body:
I have 5 pages in my app and I'm using a BottomNavigationBar to separate and access them. I had problem with my 'categories' page because I didn't want it to be reloaded each time I select it from navbar.

so I used an IndexedStack to prevent it from reloading and it worked fine. now I want my 'favourites' page to be reloaded each time the user goes to favourites page. how can I do that?

bottomNavigationBar: BottomNavigationBar(
  currentIndex: _selectedIndex,
  selectedItemColor: Colors.white,
  onTap: _onItemTapped,
  items: <BottomNavigationBarItem>[
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
     ...
    ),
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
      ...
    ),
    BottomNavigationBarItem(
    ...
    ),
  ],

),
body: isLoaded?
IndexedStack(children: _pageOptions,index: _selectedIndex,):Container()


问:
Unable to install shinytest in R
i am trying to install "shinytest" in R but not able to.
Below is the error message I am getting. Can anyone help me?
Not sure what the solution is.......

```<code>> install.packages("shinytest", dependencies = T)
Installing package into ‘D:/Windows/Analytics/XXXXXX/GitHub/XXXXX/XXXX/XXXX/renv/library/R-4.0/x86_64-w64-mingw32’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/shinytest_1.5.1.zip'
Content type 'application/zip' length 413601 bytes (403 KB)
downloaded 403 KB

package ‘shinytest’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\vinay\AppData\Local\Temp\RtmpmchoJn\downloaded_packages
> library(shinytest)
Error: package or namespace load failed for ‘shinytest’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 there is no package called ‘png’
In addition: Warning message:
package ‘shinytest’ was built under R version 4.0.5
</code>```

I tried installing png as well. But no use

```<code>Installing package into ‘D:/Windows/Analytics/xxxx/GitHub/xxx/xxx/xxx/renv/library/R-4.0/x86_64-w64-mingw32’
(as ‘lib’ is unspecified)

  There is a binary version available but the source version is later:
    binary source needs_compilation
png  0.1-7  0.1-8              TRUE

installing the source package ‘png’

trying URL 'https://cran.rstudio.com/src/contrib/png_0.1-8.tar.gz'
Content type 'application/x-gzip' length 24880 bytes (24 KB)
downloaded 24 KB

* installing *source* package 'png' ...
** package 'png' successfully unpacked and MD5 sums checked
** using staged installation
  checking PNG headers and libraries
./configure.win: line 11: E:/Program: No such file or directory
make: E:/Program: No such file or directory
make: E:/Program: No such file or directory
make: *** No rule to make target 'E:/Program'.  Stop.
  LOCAL_SOFT does not exist, fall back to external png
  cannot find current PNG files
  attempting to download them
./configure.win: line 38: E:/Program: No such file or directory

 *** ERROR: unable to find PNG files

 They must be either in src/win32, in a tar-ball
 src/libpng-current-win.tar.gz or
 available via the LOCAL_SOFT R make setting.

 You can get the latest binary tar ball from
 http://www.rforge.net/png/files/

ERROR: configuration failed for package 'png'
* removing 'D:/Windows/Analytics/xxxx/GitHub/xxx/xxxx/xxx/renv/library/R-4.0/x86_64-w64-mingw32/png'

The downloaded source packages are in
    ‘C:\Users\vinay\AppData\Local\Temp\RtmpmchoJn\downloaded_packages’
Warning message:
In utils::install.packages("png", dependencies = T) :
  installation of package ‘png’ had non-zero exit status
</code>```

Not sure what the solution is.
Should we install any dependencies?

Title: Unable to install shinytest in R

Body:
i am trying to install "shinytest" in R but not able to.
Below is the error message I am getting. Can anyone help me?
Not sure what the solution is.......

> install.packages("shinytest", dependencies = T)
Installing package into ‘D:/Windows/Analytics/XXXXXX/GitHub/XXXXX/XXXX/XXXX/renv/library/R-4.0/x86_64-w64-mingw32’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/shinytest_1.5.1.zip'
Content type 'application/zip' length 413601 bytes (403 KB)
downloaded 403 KB

package ‘shinytest’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\vinay\AppData\Local\Temp\RtmpmchoJn\downloaded_packages
> library(shinytest)
Error: package or namespace load failed for ‘shinytest’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 there is no package called ‘png’
In addition: Warning message:
package ‘shinytest’ was built under R version 4.0.5

I tried installing png as well. But no use

Installing package into ‘D:/Windows/Analytics/xxxx/GitHub/xxx/xxx/xxx/renv/library/R-4.0/x86_64-w64-mingw32’
(as ‘lib’ is unspecified)

  There is a binary version available but the source version is later:
    binary source needs_compilation
png  0.1-7  0.1-8              TRUE

installing the source package ‘png’

trying URL 'https://cran.rstudio.com/src/contrib/png_0.1-8.tar.gz'
Content type 'application/x-gzip' length 24880 bytes (24 KB)
downloaded 24 KB

* installing *source* package 'png' ...
** package 'png' successfully unpacked and MD5 sums checked
** using staged installation
  checking PNG headers and libraries
./configure.win: line 11: E:/Program: No such file or directory
make: E:/Program: No such file or directory
make: E:/Program: No such file or directory
make: *** No rule to make target 'E:/Program'.  Stop.
  LOCAL_SOFT does not exist, fall back to external png
  cannot find current PNG files
  attempting to download them
./configure.win: line 38: E:/Program: No such file or directory

 *** ERROR: unable to find PNG files

 They must be either in src/win32, in a tar-ball
 src/libpng-current-win.tar.gz or
 available via the LOCAL_SOFT R make setting.

 You can get the latest binary tar ball from
 http://www.rforge.net/png/files/

ERROR: configuration failed for package 'png'
* removing 'D:/Windows/Analytics/xxxx/GitHub/xxx/xxxx/xxx/renv/library/R-4.0/x86_64-w64-mingw32/png'

The downloaded source packages are in
    ‘C:\Users\vinay\AppData\Local\Temp\RtmpmchoJn\downloaded_packages’
Warning message:
In utils::install.packages("png", dependencies = T) :
  installation of package ‘png’ had non-zero exit status

Not sure what the solution is.
Should we install any dependencies?


问:
How can i solve Number validation problem, when Numify v2.0 is set to only accept API key from Numverify and not APILayer?
I have a software (Numify v2.0) for validating phone numbers, the software was made to use Numverify API key. But now Numverify isn't issuing new API keys and the already issued keys are being deleted and some being transferred to APILayer. so i paid for API Layer Number Validation API key but NUMIFY v2.0 is not recognizing the API key. So now it has left me with option to edit the code of the software (Numify v2.0) to change where it routes it API queries. But the problem i have now is that the software is .exe and i dont know how to edit it.

I asked the AI in ChatGPT and it recommended me to use Resource Hacker or XVI32 which wasnt what i was expecting because there's no way to edit the code using those software.


问:
How to reset a Form that has TextFormField with onUserInteraction validation mode
Minimal reproducible code:

class FooPage extends StatefulWidget {
  @override
  State<FooPage> createState() => _FooPageState();
}

class _FooPageState extends State<FooPage> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Form(
            key: _formKey,
            child: TextFormField(
              controller: _controller,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (input) {
                if (input!.isEmpty) return 'Missing';
                if (input.length < 3) return 'Too short';
                return null;
              },
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              // setState(() {}); // Uncomment this line to see the problem.
              await Future.delayed(Duration.zero);
              _formKey.currentState!.reset();
              _controller.clear();
            },
            child: Text('Clear'),
          ),
        ],
      ),
    );
  }
}
```

Type two characters in the text field, and it will show 'Too short' error as expected. Now, click the Clear button and both the form and field will reset, so far so good.

But if you uncomment the setState call in the code above and perform above step, then it gives 'Missing' error. Can anyone please explain what am I doing wrong?

Body:
Minimal reproducible code:

class FooPage extends StatefulWidget {
  @override
  State<FooPage> createState() => _FooPageState();
}

class _FooPageState extends State<FooPage> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Form(
            key: _formKey,
            child: TextFormField(
              controller: _controller,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (input) {
                if (input!.isEmpty) return 'Missing';
                if (input.length < 3) return 'Too short';
                return null;
              },
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              // setState(() {}); // Uncomment this line to see the problem.
              await Future.delayed(Duration.zero);
              _formKey.currentState!.reset();
              _controller.clear();
            },
            child: Text('Clear'),
          ),
        ],
      ),
    );
  }
}

Type two characters in the text field, and it will show 'Too short' error as expected. Now, click the Clear button and both the form and field will reset, so far so good.

But if you uncomment the setState call in the code above and perform above step, then it gives 'Missing' error. Can anyone please explain what am I doing wrong?


问:
the package (puppeteer) ReferenceError: process is not defined vue 3
puppeteerrc.json in root file

```<code>{
    "experiments": {
      "macArmChromiumEnabled": true
    }
  }

</code>```

webscrap.js

```<code>// Import puppeteer
import puppeteer from 'puppeteer';

let puppeteerweb =(async () => {
  // Launch the browser
  const browser = await puppeteer.launch();

  // Create a page
  const page = await browser.newPage();

  // Go to your site
  await page.goto('YOUR_SITE');

  // Query for an element handle.
  const element = await page.waitForSelector('div > .class-name');

  // Do something with element...
  await element.click(); // Just an example.

  // Dispose of handle
  await element.dispose();

  // Close browser.
  await browser.close();
})();

export default puppeteerweb;

</code>```

Webscrap.vue

```<code><script setup>
import puppeteerweb from "../../webscrap";
</script>

<template></template>

</code>```

here i ateying to website warpper paricluar div using
the package (puppeteer).but igot a error
ReferenceError: process is not defined
how to solve this?

Body:
puppeteerrc.json in root file

{
    "experiments": {
      "macArmChromiumEnabled": true
    }
  }

webscrap.js

// Import puppeteer
import puppeteer from 'puppeteer';

let puppeteerweb =(async () => {
  // Launch the browser
  const browser = await puppeteer.launch();

  // Create a page
  const page = await browser.newPage();

  // Go to your site
  await page.goto('YOUR_SITE');

  // Query for an element handle.
  const element = await page.waitForSelector('div > .class-name');

  // Do something with element...
  await element.click(); // Just an example.

  // Dispose of handle
  await element.dispose();

  // Close browser.
  await browser.close();
})();

export default puppeteerweb;

Webscrap.vue

<template></template>

here i ateying to website warpper paricluar div using
the package (puppeteer).but igot a error
ReferenceError: process is not defined
how to solve this?


问:
how to implement graphql in .net 7 with relay
```<code>public class Vehicle
{
    public string Name { get; set; }
    public string Model { get; set; }
    public string Manufacturer { get; set; }
    public string Length { get; set; }
    public string Type { get; set; }
}
public class VehicleGraphType : NodeGraphType<Vehicle>{
     public VehicleGraphType(){
         Field(p => p.Name);
        Field(p => p.Model);
        Field(p => p.Manufacturer);
        Field(p => p.Length);
        Field(p => p.Type);
}
</code>```

}

```<code> public class RootQuery : ObjectGraphType{
  RootQuery(IRepoService _service){
   Connection<VehicleGraphType >()
            .Name("vehicle")
             .Argument<StringGraphType>("type")
            .ResolveAsync(async ctx =>{
             var data= await _service.GetVehilcesByType(ctx.GetArgument<string>("type"))
              return ConnectionUtils.ToConnection(data,context)
    })
 }
</code>```

}

```<code> public class RootSchema : Schema
{
    public RootSchema(IServiceProvider provider) : base(provider)
    {
        Query = provider.GetRequiredService<RootQuery>();

    }
}
</code>```

Hi, I am new to GraphQl.I am trying to implement GraphQL with .NET 7 with entity framework using GraphQl relay to achieve cursor-based pagination. I am facing some issue with my code which I have implemented.

Getting Error "Response not Success Received Status code 400" on load of UI.PlayGround

following NPM is installed for GraphQl

GraphQL 7.2.0

GraphQL.UI.Playground 7.20

GraphQL.Relay 0.9.1

GraphQL.Server.Transport.AspNetCore 7.20

Body:
public class Vehicle
{
    public string Name { get; set; }
    public string Model { get; set; }
    public string Manufacturer { get; set; }
    public string Length { get; set; }
    public string Type { get; set; }
}
public class VehicleGraphType : NodeGraphType<Vehicle>{
     public VehicleGraphType(){
         Field(p => p.Name);
        Field(p => p.Model);
        Field(p => p.Manufacturer);
        Field(p => p.Length);
        Field(p => p.Type);
}

}

 public class RootQuery : ObjectGraphType{
  RootQuery(IRepoService _service){
   Connection<VehicleGraphType >()
            .Name("vehicle")
             .Argument<StringGraphType>("type")
            .ResolveAsync(async ctx =>{
             var data= await _service.GetVehilcesByType(ctx.GetArgument<string>("type"))
              return ConnectionUtils.ToConnection(data,context)
    })
 }

}

 public class RootSchema : Schema
{
    public RootSchema(IServiceProvider provider) : base(provider)
    {
        Query = provider.GetRequiredService<RootQuery>();

    }
}

Hi, I am new to GraphQl.I am trying to implement GraphQL with .NET 7 with entity framework using GraphQl relay to achieve cursor-based pagination. I am facing some issue with my code which I have implemented.

Getting Error "Response not Success Received Status code 400" on load of UI.PlayGround

following NPM is installed for GraphQl

GraphQL 7.2.0

GraphQL.UI.Playground 7.20

GraphQL.Relay 0.9.1

GraphQL.Server.Transport.AspNetCore 7.20


问:
How to recreate/reinit/restart hilt components in Android?
I'm working on an app that allows you to change the language locally.

To make this work without having to restart the app, I'm using the ContextWrapper on the BaseActivity, where I assign the language to the context:

```<code>override fun attachBaseContext(newBase: Context{
     super.attachBaseContext(ContextWrapper(newBase.setAppLocale(Session.getLanguage())))
}
</code>```

To change the language, I have used both the setLocale legacy and the ApplicationDelegate:

Legacy

```<code>fun setLocale(lang: String) {
     val myLocale = Locale(lang.toString())
     Locale.setDefault(myLocale)
     val res = resources
     val dm = res.displayMetrics
     val conf = res.configuration
     conf.locale = myLocale
     res.updateConfiguration(conf, dm)
}
</code>```

New API SDK 33

```<code>val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(it)
AppCompatDelegate.setApplicationLocales(appLocale)
</code>```

They both do pretty much the same thing. The 2nd is more efficient since it recreates the layouts itself.

The problem is that I am using an architecture with ViewModels that implement a RESOURCES Wrapper to get certain types of resources inside the ViewModel without having leaked a context. There is no mistake on the part of the team in using something wrong.

The wrapper is as follows:

```<code>class ResourceManager(val context: Context) {

     fun getColor(@ColorRes resId: Int): Int = ContextCompat.getColor(getContextWrapped(), resId)

     fun getString(@StringRes resId: Int): String = getContextWrapped().getString(resId)

     fun getDrawable(@DrawableRes resId: Int): Drawable? = getContextWrapped().getDrawable(resId)

     private fun getContextWrapped(): Context {
         return ContextWrapper(context.setAppLocale(Session.getLanguage()))
     }
}
</code>```

What is the real problem?
The problem is that this ResourceManager uses a CONTEXT that when changing the language, this CONTEXT remains with the previous LANGUAGE resource. That is, if the app starts in English and I change it to Italian, the ResourceManager will stay in English.

The solution I found is to Restart HILT as I did with Dagger before, which generated a new component and cleaned the old one. But, with HILT, I don't know how this can be achieved. How can I override singleton resources and create new ones.

Body:
I'm working on an app that allows you to change the language locally.

To make this work without having to restart the app, I'm using the ContextWrapper on the BaseActivity, where I assign the language to the context:

override fun attachBaseContext(newBase: Context{
     super.attachBaseContext(ContextWrapper(newBase.setAppLocale(Session.getLanguage())))
}

To change the language, I have used both the setLocale legacy and the ApplicationDelegate:

Legacy

fun setLocale(lang: String) {
     val myLocale = Locale(lang.toString())
     Locale.setDefault(myLocale)
     val res = resources
     val dm = res.displayMetrics
     val conf = res.configuration
     conf.locale = myLocale
     res.updateConfiguration(conf, dm)
}

New API SDK 33

val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(it)
AppCompatDelegate.setApplicationLocales(appLocale)

They both do pretty much the same thing. The 2nd is more efficient since it recreates the layouts itself.

The problem is that I am using an architecture with ViewModels that implement a RESOURCES Wrapper to get certain types of resources inside the ViewModel without having leaked a context. There is no mistake on the part of the team in using something wrong.

The wrapper is as follows:

class ResourceManager(val context: Context) {

     fun getColor(@ColorRes resId: Int): Int = ContextCompat.getColor(getContextWrapped(), resId)

     fun getString(@StringRes resId: Int): String = getContextWrapped().getString(resId)

     fun getDrawable(@DrawableRes resId: Int): Drawable? = getContextWrapped().getDrawable(resId)

     private fun getContextWrapped(): Context {
         return ContextWrapper(context.setAppLocale(Session.getLanguage()))
     }
}

What is the real problem?
The problem is that this ResourceManager uses a CONTEXT that when changing the language, this CONTEXT remains with the previous LANGUAGE resource. That is, if the app starts in English and I change it to Italian, the ResourceManager will stay in English.

The solution I found is to Restart HILT as I did with Dagger before, which generated a new component and cleaned the old one. But, with HILT, I don't know how this can be achieved. How can I override singleton resources and create new ones.


问:
How to browse an image and display it in certain size and after converting it to a sketch
I have two codes: one browses a photo and displays it but sometimes the photo has large height and width and doesn't fit the screen. The other code converts a given image to a sketch but won't allow user to browse.

what can i add to the first code (which browses the picture and displays it ) to make it display it in certain size and convert it to a sketch?

```<code>from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk

class Root(Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title("Python Tkinter Dialog Widget")
        self.minsize(640, 400)

        self.labelFrame = ttk.LabelFrame(self, text = "Open File")
        self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)

        self.button()

    def button(self):
        self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
        self.button.grid(column = 1, row = 1)

    def fileDialog(self):

        self.filename = filedialog.askopenfilename(initialdir =  "/", title = "Select A File", filetype =
        (("jpeg files","*.jpg"),("all files","*.*")) )
        self.label = ttk.Label(self.labelFrame, text = "")
        self.label.grid(column = 1, row = 2)
        self.label.configure(text = self.filename)

        img = Image.open(self.filename)
        photo = ImageTk.PhotoImage(img)

        self.label2 = Label(image=photo)
        self.label2.image = photo
        self.label2.grid(column=3, row=4)

root = Root()
root.mainloop()
</code>```

Second code:

```<code>import cv2

img_location = "C:/Users/alene/OneDrive/Desktop/"
filename = "puppy.webp"

img = cv2.imread(img_location+filename)

gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

inverted_gray_image = 255 - gray_image

blurred_img = cv2.GaussianBlur(inverted_gray_image, (21,21), 0)
inverted_blurred_img = 255 - blurred_img

pencil_sketch_IMG = cv2.divide(gray_image, inverted_blurred_img, scale=256.0)

cv2.imshow("new image", pencil_sketch_IMG)
cv2.waitKey(0)
</code>```

I'd really appreciate it if you could help me

Body:
I have two codes: one browses a photo and displays it but sometimes the photo has large height and width and doesn't fit the screen. The other code converts a given image to a sketch but won't allow user to browse.

what can i add to the first code (which browses the picture and displays it ) to make it display it in certain size and convert it to a sketch?

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk

class Root(Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title("Python Tkinter Dialog Widget")
        self.minsize(640, 400)

        self.labelFrame = ttk.LabelFrame(self, text = "Open File")
        self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)

        self.button()

    def button(self):
        self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
        self.button.grid(column = 1, row = 1)

    def fileDialog(self):

        self.filename = filedialog.askopenfilename(initialdir =  "/", title = "Select A File", filetype =
        (("jpeg files","*.jpg"),("all files","*.*")) )
        self.label = ttk.Label(self.labelFrame, text = "")
        self.label.grid(column = 1, row = 2)
        self.label.configure(text = self.filename)

        img = Image.open(self.filename)
        photo = ImageTk.PhotoImage(img)

        self.label2 = Label(image=photo)
        self.label2.image = photo
        self.label2.grid(column=3, row=4)

root = Root()
root.mainloop()

Second code:

import cv2

img_location = "C:/Users/alene/OneDrive/Desktop/"
filename = "puppy.webp"

img = cv2.imread(img_location+filename)

gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

inverted_gray_image = 255 - gray_image

blurred_img = cv2.GaussianBlur(inverted_gray_image, (21,21), 0)
inverted_blurred_img = 255 - blurred_img

pencil_sketch_IMG = cv2.divide(gray_image, inverted_blurred_img, scale=256.0)

cv2.imshow("new image", pencil_sketch_IMG)
cv2.waitKey(0)

I'd really appreciate it if you could help me


问:
TypeError: can't convert np.ndarray of type numpy.object_
So I am trying to write a RNN for the dataset from Quickdraw. My problem is, that the data, which is in ndjson, has multiple lists inside of it.

So one row would look like this:

```<code>{"word":"The Eiffel Tower","countrycode":"GB","timestamp":"2017-03-11 14:47:44.05242 UTC","recognized":true,"key_id":"5027286841556992","drawing":[[[0,22,37,64,255],[218,220,227,228,211]],[[76,95,135,141,150,159,166,180,186,201],[220,138,31,0,63,79,117,150,191,224]],[[94,104,111,119,127,141,143,142,180,191],[212,167,149,80,59,41,30,134,202,232]],[[109,127,137,147,150,162,172,185],[122,120,104,97,99,124,128,128]],[[75,130,158],[162,159,150]]]}
</code>```

Now my Problem is, I only need the word and drawing data, which I managed, but I cant seem to figure out, how to convert the data to tensors to use.
The error looks like this:

```<code>TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.
</code>```

I tried to find a solution, but I couldn't find anything that worked.
Here is part of my code:

files = glob.glob("data/*.ndjson")

for file in files:
    print (file) # iterate over the list of files
    with open(file, "r") as fin:
        data = ndjson.load(fin)
df = pd.DataFrame(data)
X = df['drawing'].to_numpy()
y = df['word'].to_numpy()  # assuming that the target column is named 'word'
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)

# Convert the data to PyTorch tensors and create DataLoaders for the training and validation sets
train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(y_train))
val_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_val), torch.from_numpy(y_val))
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=32, shuffle=True)
#help
```

I get the error in the line from train_dataset

Body:
So I am trying to write a RNN for the dataset from Quickdraw. My problem is, that the data, which is in ndjson, has multiple lists inside of it.

So one row would look like this:

{"word":"The Eiffel Tower","countrycode":"GB","timestamp":"2017-03-11 14:47:44.05242 UTC","recognized":true,"key_id":"5027286841556992","drawing":[[[0,22,37,64,255],[218,220,227,228,211]],[[76,95,135,141,150,159,166,180,186,201],[220,138,31,0,63,79,117,150,191,224]],[[94,104,111,119,127,141,143,142,180,191],[212,167,149,80,59,41,30,134,202,232]],[[109,127,137,147,150,162,172,185],[122,120,104,97,99,124,128,128]],[[75,130,158],[162,159,150]]]}

Now my Problem is, I only need the word and drawing data, which I managed, but I cant seem to figure out, how to convert the data to tensors to use.
The error looks like this:

TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

I tried to find a solution, but I couldn't find anything that worked.
Here is part of my code:

files = glob.glob("data/*.ndjson")

for file in files:
    print (file) # iterate over the list of files
    with open(file, "r") as fin:
        data = ndjson.load(fin)
df = pd.DataFrame(data)
X = df['drawing'].to_numpy()
y = df['word'].to_numpy()  # assuming that the target column is named 'word'
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)

# Convert the data to PyTorch tensors and create DataLoaders for the training and validation sets
train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(y_train))
val_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_val), torch.from_numpy(y_val))
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=32, shuffle=True)
#help

I get the error in the line from train_dataset


问:
Should we unregister the OnBackPressedCallback?
Starting from SDK 33 the onBackPressed() method is deprecated and as a replacement, I want to use the onBackPressedDispatcher property instead.

To avoid memory leaks, should we somehow unregister the OnBackPressedCallback in the onDestroy method?


问:
How to resolve Access denied (1045) error when creating tenant in tenancyforlaravel package
I have a laravel 9 project, that I am trying to make multi-tenant. I am using the tenancyforlaravel.com package It gives me the following error, but when I check  in the the db server the database is created.But it is created with a new user, not the root user.

What could be the problem?

```<code>Illuminate\Database\QueryException  SQLSTATE[HY000] [1045] Access denied for user 'MAHcx42oEpVhqADN'@'localhost' (using password: YES) (SQL: select * from information_schema.tables where table_schema = school_db and table_name = migrations and table_type = 'BASE TABLE').
</code>```

I am using MacOS and phpMyAdmin.

Body:
I have a laravel 9 project, that I am trying to make multi-tenant. I am using the tenancyforlaravel.com package It gives me the following error, but when I check  in the the db server the database is created.But it is created with a new user, not the root user.

What could be the problem?

Illuminate\Database\QueryException  SQLSTATE[HY000] [1045] Access denied for user 'MAHcx42oEpVhqADN'@'localhost' (using password: YES) (SQL: select * from information_schema.tables where table_schema = school_db and table_name = migrations and table_type = 'BASE TABLE').

I am using MacOS and phpMyAdmin.


问:
What's the best way for searching items in MongoDB?
I'm new to MongoDB and I'd like to know if the following is ok or if there is a better option to do the search:

I have a Dotnet project divided in Apps and App Items. Apps' info is in an App Collection and Items are stored in an Item Collection in Mongo, with its App Id as a field. It's structured like this because the Apps are created by the user, customizing its fields and so on, so to avoid creating infinite Collections for each App created, I just store their info in the Apps Collection and then reference them in each item.

My question is wether or not should I filter items first using the App Id field and then search the item that I want with find; just use find; only use filters... Efficiently speaking.

For example, this is the filter that I'm using to find the App in my UpdateApp method:

```<code>public async Task UpdateApp(App app)
        {
            var filter = Builders<App>
                .Filter
                .Eq(s => s.Id, app.Id);

            await Collection.ReplaceOneAsync(filter, app);
        }
</code>```

But for the GetApp I'm using this:

```<code>public async Task<App> GetAppById(string id)
        {
            return await Collection.FindAsync(
               new BsonDocument { { "_id", new ObjectId(id) } }).Result.
               FirstAsync();
        }
</code>```

Body:
I'm new to MongoDB and I'd like to know if the following is ok or if there is a better option to do the search:

I have a Dotnet project divided in Apps and App Items. Apps' info is in an App Collection and Items are stored in an Item Collection in Mongo, with its App Id as a field. It's structured like this because the Apps are created by the user, customizing its fields and so on, so to avoid creating infinite Collections for each App created, I just store their info in the Apps Collection and then reference them in each item.

My question is wether or not should I filter items first using the App Id field and then search the item that I want with find; just use find; only use filters... Efficiently speaking.

For example, this is the filter that I'm using to find the App in my UpdateApp method:

public async Task UpdateApp(App app)
        {
            var filter = Builders<App>
                .Filter
                .Eq(s => s.Id, app.Id);

            await Collection.ReplaceOneAsync(filter, app);
        }

But for the GetApp I'm using this:

public async Task<App> GetAppById(string id)
        {
            return await Collection.FindAsync(
               new BsonDocument { { "_id", new ObjectId(id) } }).Result.
               FirstAsync();
        }


问:
Using ".measure" on a View with a Ref, x and y coordinates always are 0 when run in Android but works fine on iOS (React Native)
I've assigned a view with a Ref, and I'm using this reference to get the coordinates of the view. It works fine on iOS, where I get a Y-value where the View is located. However, on Android, the Y-value is always zero.

I've read that you should use collapsable={false} on the View you are measuring, but the only thing that did was to no longer return "undefined" but instead return "0".

I've created a snack for the issue, will appreciate any feedback on how to resolve this.

https://snack.expo.dev/@minifisk/quiet-cashew?platform=ios


问:
A plot showing the edit distance as a line between two cities. The thickness / opacity of the line can be adjusted based on the edit distance score
I have calculate the edit disctance between differents language, as shown below.

Now i am trying to plot showing the edit distance as a line between two cities. The thickness / opacity of the line can be adjusted based on the edit distance score. e.g. source

I have done alot of effort to design it in excel  tried map graph

please someone have idea of it guide me.


问:
Verify async message push in pact provider verification on a PHP provider microservice
I am currently integrating consumer driven contract testing via Pact with a legacy php microservice.

As I understood, php is currently not fully supported for testing asynchronous message workflows. So far, this was not an issue for me, as testing the provider against the contracts defined by my consumers does only require a running instance of that microservice and no php specific interaction.

Currently, I am struggling with my test case about a message queue workflow, as I did not find out, how I can trigger the defined async message to be pushed by my provider while executing the pact-provider-verifier ... command.

I was thinking about a definition in my pact .json file to tell pact how the async message can be triggered from the provider (e.g. by calling a special http-endpoint on that provider instance). But so fare I did not find out, how that can be defined within the json schema (v3) or if I have to tigger that message manually during the verification workflow.


问:
How to kill process Parallel in python?
There are 10 different hosts where I run the same function and I go to them with for loops.
And I used parallel to run them simultaneously.

```<code>def run_parallel():

    pool = Pool(processes=len(hostList))
    pool.map(allFunc,hostList)

if __name__ == '__main__':
    run_parallel()
</code>```

This way they all work in parallel and the code is finished in a very short time.
This script is running in cron.

But i am having a problem;
When I look at the processes running in the backend on the server, I constantly see this script.

Somehow (possibly due to access problem or not getting a reply in a long time) the script does not terminate and periodically a new one starts (every 15 minutes at cron) and it does not end, it accumulates constantly.

I need to put termination information in this parallel.
How can I get this. I tried terminate vs but it didn't terminate.

Thanks.

Title: How to kill process Parallel in python?

Body:
There are 10 different hosts where I run the same function and I go to them with for loops.
And I used parallel to run them simultaneously.

def run_parallel():

    pool = Pool(processes=len(hostList))
    pool.map(allFunc,hostList)

if __name__ == '__main__':
    run_parallel()

This way they all work in parallel and the code is finished in a very short time.
This script is running in cron.

But i am having a problem;
When I look at the processes running in the backend on the server, I constantly see this script.

Somehow (possibly due to access problem or not getting a reply in a long time) the script does not terminate and periodically a new one starts (every 15 minutes at cron) and it does not end, it accumulates constantly.

I need to put termination information in this parallel.
How can I get this. I tried terminate vs but it didn't terminate.

Thanks.


问:
When using NGRX with Angular SSR, the initial load of the page doesn't show async HTML
I've been trying a good amount of time now but I can't seem to wrap my head around this, I'm using Angular Universal to serve this SSR project. In order to make my product page crawlable, I have to have product information available in the first DOC fetch. Since I'm using NGRX to load data asynchronously, this requires a bit of extra work (but I'm not sure if my thinking is correct).

So for example:

```<code><ng-container *ngIf="storeData$ | async as data">
    <h1 [innerHtml]="data.name"></h1>
    <p [innerHtml]="data.description"></p>
</ng-container>
</code>```

When resolving this page I've tried 2 different route guards.

1st route guard:

Go through my normal chain of NGRX effects and resolving the navigation when data is present in the store. This chain of effects includes getting product information via GraphQL, calculating prices, getting filter options and other custom objects we need in order to build the page. I've checked the ngOnInit, this always fires after the resolve is done, so there is no timing issue here (it seems). But nothing shows up in the initial DOC, even when there's just static content outside of the async ng-container this won't show up in the initial load either.

```<code>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const getPayload = {
      categorySlug: route.params['subcategorySlug'],
      productGroupSlug: route.params['productGroupSlug'],
      productSlug: route.params['productSlug'],
      locale: this.locale,
      setFilters: []
    };

    return this.getProductQueryResult(getPayload).pipe(
      switchMap(() => {
        console.log('RESOLVE!');
        return of(true);
      }),
      catchError(() => {
        console.log('CATCH!');
        return of(false);
      })
    );
  }

  private getProductQueryResult(getPayload: any) {
    return this._store.select('FilterPage', 'Loaded', 'ProductPage', 'queryResult').pipe(
      tap(data => this.prefetch(data, getPayload)),
      filter(data => !!data),
      take(1)
    );
  }

  private prefetch(queryResult, getPayload) {
    if (!queryResult) {
      this._store.dispatch(filterActions.initProduct(getPayload));
    }
  }
</code>```

2nd route guard:

Only get the essential product information via an HTTP get call, toPromise(), then store in NGRX, resolve the page, async load data (see html snippet) from NGRX. This DOES work.

```<code>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return new Promise<any>((resolve, reject) => {
      const productSlug = route.params['productSlug'];
      const predicate = `masterData(current(slug(${this.locale}%3D%22${productSlug}%22)))`;
      const url = environment.commercetoolsURL + '/' + environment.commercetoolsProjectKey + '/products?where=' + predicate;

      this.http.get(url).toPromise().then((res: any) => {
        this._store.dispatch(filterActions.setProductPrerenderData({data: res.results[0]}));
        resolve(res);
      });
    });
  }
</code>```

I could use the 2nd option for creating a prerender for the page but that would mean that I have to fetch the product information twice: once for the prerender, and once for the async page view, which is not ideal.

A few of my findings:

No route guard doesn't work. Only static HTML gets loaded in the initial DOC.

Route guard with NGRX doesn't work. Nothing gets loaded in the initial DOC.

Route guard with HTTP GET works, but other essential information, included in the NGRX effects won't get fetched, need an extra call for that.

The most important question I have is. Why doesn't it work when the page is resolved when the store data is loaded, and served on the page instantly?

Body:
I've been trying a good amount of time now but I can't seem to wrap my head around this, I'm using Angular Universal to serve this SSR project. In order to make my product page crawlable, I have to have product information available in the first DOC fetch. Since I'm using NGRX to load data asynchronously, this requires a bit of extra work (but I'm not sure if my thinking is correct).

So for example:

<ng-container *ngIf="storeData$ | async as data">

</ng-container>

When resolving this page I've tried 2 different route guards.

1st route guard:

Go through my normal chain of NGRX effects and resolving the navigation when data is present in the store. This chain of effects includes getting product information via GraphQL, calculating prices, getting filter options and other custom objects we need in order to build the page. I've checked the ngOnInit, this always fires after the resolve is done, so there is no timing issue here (it seems). But nothing shows up in the initial DOC, even when there's just static content outside of the async ng-container this won't show up in the initial load either.

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const getPayload = {
      categorySlug: route.params['subcategorySlug'],
      productGroupSlug: route.params['productGroupSlug'],
      productSlug: route.params['productSlug'],
      locale: this.locale,
      setFilters: []
    };

    return this.getProductQueryResult(getPayload).pipe(
      switchMap(() => {
        console.log('RESOLVE!');
        return of(true);
      }),
      catchError(() => {
        console.log('CATCH!');
        return of(false);
      })
    );
  }

  private getProductQueryResult(getPayload: any) {
    return this._store.select('FilterPage', 'Loaded', 'ProductPage', 'queryResult').pipe(
      tap(data => this.prefetch(data, getPayload)),
      filter(data => !!data),
      take(1)
    );
  }

  private prefetch(queryResult, getPayload) {
    if (!queryResult) {
      this._store.dispatch(filterActions.initProduct(getPayload));
    }
  }

2nd route guard:

Only get the essential product information via an HTTP get call, toPromise(), then store in NGRX, resolve the page, async load data (see html snippet) from NGRX. This DOES work.

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return new Promise<any>((resolve, reject) => {
      const productSlug = route.params['productSlug'];
      const predicate = `masterData(current(slug(${this.locale}%3D%22${productSlug}%22)))`;
      const url = environment.commercetoolsURL + '/' + environment.commercetoolsProjectKey + '/products?where=' + predicate;

      this.http.get(url).toPromise().then((res: any) => {
        this._store.dispatch(filterActions.setProductPrerenderData({data: res.results[0]}));
        resolve(res);
      });
    });
  }

I could use the 2nd option for creating a prerender for the page but that would mean that I have to fetch the product information twice: once for the prerender, and once for the async page view, which is not ideal.

A few of my findings:

No route guard doesn't work. Only static HTML gets loaded in the initial DOC.

Route guard with NGRX doesn't work. Nothing gets loaded in the initial DOC.

Route guard with HTTP GET works, but other essential information, included in the NGRX effects won't get fetched, need an extra call for that.

The most important question I have is. Why doesn't it work when the page is resolved when the store data is loaded, and served on the page instantly?


问:
Add teammembers in squadcast with roles
Here in this yaml file team1 is team name having users list which will have user role .
and have another list of users having observer role

yaml

```<code>team1:
 - role: User
   users:
    - test@email.com
    - test@yahoo.com
 - role: Observer
   users:
    - test@email.com
</code>```

now this is the terraform code

```<code>locals {

  membership_nested = yamldecode(file("${path.module}/test.yaml"))
membership_flat = distinct(flatten(
    [
      for team_key, team in local.membership_nested : [
        for role in team : {
          "team_name" = team_key
          "roles" = role.role
          "user_name" = role.users
        }
      ]
    ]
  ))
}

data "squadcast_team" "team_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  name     = each.value.team_name
}

data "squadcast_user" "user_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  email    = each.value.user_name
}

data "squadcast_team_role" "role_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  name     = each.value.roles
  team_id  = data.squadcast_team.team_name[each.key].id
}

resource "squadcast_team_member" "membership" {
  for_each = { for i, v in local.membership_flat : i => v }
  team_id  = data.squadcast_team.team_name[each.key].id
  user_id  = data.squadcast_user.user_name[each.key].id
  role_ids = [data.squadcast_team_role.role_name[each.key].id]

}
</code>```

error :

```<code>│

 Error: Incorrect attribute value type
│
│   on teammembers.tf line 67, in data "squadcast_user" "user_name":
│   67:   email    = each.value.user_name
│     ├────────────────
│     │ each.value.user_name is list of string with 1 element
│
│ Inappropriate value for attribute "email": string required.
</code>```

i want like one team that is team 1 . in that all users should be added as per list with role that have given to them

Title: Add teammembers in squadcast with roles

Body:
Here in this yaml file team1 is team name having users list which will have user role .
and have another list of users having observer role

yaml

team1:
 - role: User
   users:
    - test@email.com
    - test@yahoo.com
 - role: Observer
   users:
    - test@email.com

now this is the terraform code

locals {

  membership_nested = yamldecode(file("${path.module}/test.yaml"))
membership_flat = distinct(flatten(
    [
      for team_key, team in local.membership_nested : [
        for role in team : {
          "team_name" = team_key
          "roles" = role.role
          "user_name" = role.users
        }
      ]
    ]
  ))
}

data "squadcast_team" "team_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  name     = each.value.team_name
}

data "squadcast_user" "user_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  email    = each.value.user_name
}

data "squadcast_team_role" "role_name" {
  for_each = { for i, v in local.membership_flat : i => v }
  name     = each.value.roles
  team_id  = data.squadcast_team.team_name[each.key].id
}

resource "squadcast_team_member" "membership" {
  for_each = { for i, v in local.membership_flat : i => v }
  team_id  = data.squadcast_team.team_name[each.key].id
  user_id  = data.squadcast_user.user_name[each.key].id
  role_ids = [data.squadcast_team_role.role_name[each.key].id]

}

error :

│

 Error: Incorrect attribute value type
│
│   on teammembers.tf line 67, in data "squadcast_user" "user_name":
│   67:   email    = each.value.user_name
│     ├────────────────
│     │ each.value.user_name is list of string with 1 element
│
│ Inappropriate value for attribute "email": string required.

i want like one team that is team 1 . in that all users should be added as per list with role that have given to them


问:
aarch64-linux-gnu-gdb start with some errors
When I use aaarch64-Linux-GNU-GDB debugger, there are some errors when aaarch64-Linux-GNU-GDB starts.

```<code>➜  gdb aarch64-linux-gnu-gdb
Traceback (most recent call last):
  File "/usr/share/gdb/python/gdb/__init__.py", line 144, in auto_load_packages
    __import__(modname)
  File "/usr/share/gdb/python/gdb/command/explore.py", line 756, in <module>
    Explorer.init_env()
  File "/usr/share/gdb/python/gdb/command/explore.py", line 135, in init_env
    gdb.TYPE_CODE_RVALUE_REF : ReferenceExplorer,
AttributeError: 'module' object has no attribute 'TYPE_CODE_RVALUE_REF'
</code>```

Python version information is as follows

```<code>➜  gdb python -V
Python 2.7.17
➜  gdb which python
/usr/bin/python
</code>```

Body:
When I use aaarch64-Linux-GNU-GDB debugger, there are some errors when aaarch64-Linux-GNU-GDB starts.

➜  gdb aarch64-linux-gnu-gdb
Traceback (most recent call last):
  File "/usr/share/gdb/python/gdb/__init__.py", line 144, in auto_load_packages
    __import__(modname)
  File "/usr/share/gdb/python/gdb/command/explore.py", line 756, in <module>
    Explorer.init_env()
  File "/usr/share/gdb/python/gdb/command/explore.py", line 135, in init_env
    gdb.TYPE_CODE_RVALUE_REF : ReferenceExplorer,
AttributeError: 'module' object has no attribute 'TYPE_CODE_RVALUE_REF'

Python version information is as follows

➜  gdb python -V
Python 2.7.17
➜  gdb which python
/usr/bin/python


问:
flutter app running on Xcode throws error module 'firebase_auth' not found
I added the package 'firebase_auth' to my flutter project 'flutter pub add firebase_auth'

Running the app in vscode works fine, only building in Xcode (open the Runner.xcworkspace) throws the error.

I work on MacBook Pro 2022 M2

GeneratedPluginRegistrant.h:

```<code>#import "GeneratedPluginRegistrant.h"

#if __has_include(<firebase_auth/FLTFirebaseAuthPlugin.h>)
#import <firebase_auth/FLTFirebaseAuthPlugin.h>
#else
@import firebase_auth; #here is the error
#endif
</code>```

pubspec.yaml

```<code>environment:
  sdk: '>=2.18.6 <3.0.0'

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_core: ^2.4.1
  firebase_auth: ^4.2.4
  google_sign_in: ^5.4.2
</code>```

I also try:
flutter clean,
flutter pub get
flutter pub upgrade
delete podfile, podfile.lock, pod folder
pod install
pod install --repo-update
un-commenting the line in Podfile
platform :ios, '12.0'

If I create a new flutter project, the build on Xcode is success.

Body:
I added the package 'firebase_auth' to my flutter project 'flutter pub add firebase_auth'

Running the app in vscode works fine, only building in Xcode (open the Runner.xcworkspace) throws the error.

I work on MacBook Pro 2022 M2

GeneratedPluginRegistrant.h:

#import "GeneratedPluginRegistrant.h"

#if __has_include(<firebase_auth/FLTFirebaseAuthPlugin.h>)
#import <firebase_auth/FLTFirebaseAuthPlugin.h>
#else
@import firebase_auth; #here is the error
#endif

pubspec.yaml

environment:
  sdk: '>=2.18.6 <3.0.0'

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_core: ^2.4.1
  firebase_auth: ^4.2.4
  google_sign_in: ^5.4.2

I also try:
flutter clean,
flutter pub get
flutter pub upgrade
delete podfile, podfile.lock, pod folder
pod install
pod install --repo-update
un-commenting the line in Podfile
platform :ios, '12.0'

If I create a new flutter project, the build on Xcode is success.


问:
how to re run script if error and automation
I am looking for a solution to automate my script to re-run in an infinite loop till the script is stopped, and also i am having difficulties to let the script continue after any error, it should just re-start the process.

At current, if all goes well it will run for some time till i get and error, then requires me to re-run the script manually evetime, here is the error i receive:

```<code>? new Error(`${response.errorText} at ${url}`)
                  ^
Error: net::ERR_CONNECTION_CLOSED at https://*********.com
at navigate (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Frame.js:210:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Frame.goto (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Frame.js:180:21)
at async CDPPage.goto (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.js:436:16)
at async file:///C:/Users/Omega/Desktop/GOLOGIN/create.js:65:3
</code>```

Here is my full code:

```<code>import puppeteer from 'puppeteer-core';
import GoLogin from './node_modules/gologin/src/gologin.js';

const delay = ms => new Promise(res => setTimeout(res, ms));

const { connect } = puppeteer;

function fingerprint(){

(async () => {
  const GL = new GoLogin({
    token: '********************',
  });

  // Generate Random Profile Username
  let randomProfile = Math.floor(Math.random()*89999+1000000)

  // next parameters are required for creating

  const profile_id = await GL.create({
    name: randomProfile,
    os: 'win',
    navigator: {
      language: 'enUS',
      userAgent: 'random', // get random user agent for selected os
      resolution: '1920x1080',
      platform: 'win',
    },
    proxyEnabled: true,
     proxy: {
        mode:   'http',
        host:   '********.com',
        port:   '10000',
        username:   '*******',
        password:   '*******',
        autoProxyRegion: 'us',
     },
  });

  console.log('profile id=', profile_id);

  await GL.update({
    id: profile_id,
    name: randomProfile,
  });

  const profile = await GL.getProfile(profile_id);
  console.log('new profile name=', profile.name);

  // Goto site and wait, then delete profile
  const { status, wsUrl } = await GL.start();
  const browser = await connect({
    browserWSEndpoint: wsUrl.toString(),
    ignoreHTTPSErrors: true,
  });

  const page = await browser.newPage();
  await page.goto('https://*************.com');
  await delay(5000);
  console.log(await page.content());
  await delay(15000);
  await browser.close();
  await GL.stopLocal({ posting: false });
  await GL.delete(profile_id);
  console.log('Success');

})();

};

function run() {
    setInterval(fingerprint, 25000);
  };

  run();
</code>```

Would appreciate if someone could guide me or show me a better way to automate the loop and also if an error the system should just re-run the script.

Body:
I am looking for a solution to automate my script to re-run in an infinite loop till the script is stopped, and also i am having difficulties to let the script continue after any error, it should just re-start the process.

At current, if all goes well it will run for some time till i get and error, then requires me to re-run the script manually evetime, here is the error i receive:

? new Error(`${response.errorText} at ${url}`)
                  ^
Error: net::ERR_CONNECTION_CLOSED at https://*********.com
at navigate (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Frame.js:210:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Frame.goto (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Frame.js:180:21)
at async CDPPage.goto (file:///C:/Users/Omega/Desktop/GOLOGIN/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.js:436:16)
at async file:///C:/Users/Omega/Desktop/GOLOGIN/create.js:65:3

Here is my full code:

import puppeteer from 'puppeteer-core';
import GoLogin from './node_modules/gologin/src/gologin.js';

const delay = ms => new Promise(res => setTimeout(res, ms));

const { connect } = puppeteer;

function fingerprint(){

(async () => {
  const GL = new GoLogin({
    token: '********************',
  });

  // Generate Random Profile Username
  let randomProfile = Math.floor(Math.random()*89999+1000000)

  // next parameters are required for creating

  const profile_id = await GL.create({
    name: randomProfile,
    os: 'win',
    navigator: {
      language: 'enUS',
      userAgent: 'random', // get random user agent for selected os
      resolution: '1920x1080',
      platform: 'win',
    },
    proxyEnabled: true,
     proxy: {
        mode:   'http',
        host:   '********.com',
        port:   '10000',
        username:   '*******',
        password:   '*******',
        autoProxyRegion: 'us',
     },
  });

  console.log('profile id=', profile_id);

  await GL.update({
    id: profile_id,
    name: randomProfile,
  });

  const profile = await GL.getProfile(profile_id);
  console.log('new profile name=', profile.name);

  // Goto site and wait, then delete profile
  const { status, wsUrl } = await GL.start();
  const browser = await connect({
    browserWSEndpoint: wsUrl.toString(),
    ignoreHTTPSErrors: true,
  });

  const page = await browser.newPage();
  await page.goto('https://*************.com');
  await delay(5000);
  console.log(await page.content());
  await delay(15000);
  await browser.close();
  await GL.stopLocal({ posting: false });
  await GL.delete(profile_id);
  console.log('Success');

})();

};

function run() {
    setInterval(fingerprint, 25000);
  };

  run();

Would appreciate if someone could guide me or show me a better way to automate the loop and also if an error the system should just re-run the script.


问:
Send data from one microbit to another each 10 minutes
please does someone have any suggestion how to send data from one microbit to another each 10 minutes? I wanted to use pause function, but in documentation I understood that max pause time is 10 seconds. Thanks for any reply :)</p>


问:
Tree Widget Alignment
Does anybody know how could i align the tree view like that one of the comboboxes?

How it looks and how i would like to look

```<code>        self.tree_view = QtWidgets.QTreeView()
        self.tree_view.setModel(self.model)
        self.tree_view.setRootIndex(self.model.index(root_path))
        self.tree_view.hideColumn(1)
        self.tree_view.setColumnWidth(0,300)
        self.tree_view.setFixedSize(200,250)

        self.model.setNameFilters(["*.py"])
        self.model.setNameFilterDisables(False)

    def create_layouts(self):

        attr_layout = QtWidgets.QHBoxLayout()
        attr_layout.addWidget(self.project_combobox)
        attr_layout.addWidget(self.assets_combobox)
        attr_layout.addWidget(self.path_combobox)
        attr_layout.addWidget(self.model_combobox)
        attr_layout.addWidget(self.character_combobox)
        attr_layout.addWidget(self.tree_view)
        attr_layout.setAlignment(QtCore.Qt.AlignLeft)
</code>```

Title: Tree Widget Alignment

Body:
Does anybody know how could i align the tree view like that one of the comboboxes?

How it looks and how i would like to look

        self.tree_view = QtWidgets.QTreeView()
        self.tree_view.setModel(self.model)
        self.tree_view.setRootIndex(self.model.index(root_path))
        self.tree_view.hideColumn(1)
        self.tree_view.setColumnWidth(0,300)
        self.tree_view.setFixedSize(200,250)

        self.model.setNameFilters(["*.py"])
        self.model.setNameFilterDisables(False)

    def create_layouts(self):

        attr_layout = QtWidgets.QHBoxLayout()
        attr_layout.addWidget(self.project_combobox)
        attr_layout.addWidget(self.assets_combobox)
        attr_layout.addWidget(self.path_combobox)
        attr_layout.addWidget(self.model_combobox)
        attr_layout.addWidget(self.character_combobox)
        attr_layout.addWidget(self.tree_view)
        attr_layout.setAlignment(QtCore.Qt.AlignLeft)


问:
How to get validation schema value when using useFormik hook
I am making common components for input, select, etc. I want to automatically put asterisk next to required fields. For that I want to access the validation schema from formik object which is available by useFormik hook. Is there a way to achieve that

Here is my input component for reference

```<code>const FormikInputGroup = ({
  formik,
  label = "",
  required = false,
  name,
  fullWidth,
  ...props
}) => {
  return (
    <div className={fullWidth ? "w-full" : ""}>
      <label className="block text-sm font-medium mb-1" htmlFor={name}>
        {label} {required && <span className="text-rose-500">*</span>}
      </label>
      <input
        type="text"
        value={_.at(formik.values, name)[0]}
        onChange={formik.handleChange}
        name={name}
        onBlur={formik.handleBlur}
        className="w-full form-input"
        {...props}
      />
      {formik.errors[name] && formik.touched[name] ? (
        <p className="text-xs text-red-500">{formik.errors[name]}</p>
      ) : null}
    </div>
  );
};
</code>```

As you can see in this example I have to explicitly pass required prop, but I want to achieve something like this

```<code>const FormikInputGroup = ({
  formik,
  label = "",
  name,
  fullWidth,
  ...props
}) => {
  return (
    <div className={fullWidth ? "w-full" : ""}>
      <label className="block text-sm font-medium mb-1" htmlFor={name}>
        {label}
       {formik.validationSchema[name].required && <span className="text-rose-500">*</span>}
      </label>
      /// rest of the input component
    </div>
  );
};
</code>```

Body:
I am making common components for input, select, etc. I want to automatically put asterisk next to required fields. For that I want to access the validation schema from formik object which is available by useFormik hook. Is there a way to achieve that

Here is my input component for reference

const FormikInputGroup = ({
  formik,
  label = "",
  required = false,
  name,
  fullWidth,
  ...props
}) => {
  return (

        {label} {required && *}

      <input
        type="text"
        value={_.at(formik.values, name)[0]}
        onChange={formik.handleChange}
        name={name}
        onBlur={formik.handleBlur}
        className="w-full form-input"
        {...props}
      />
      {formik.errors[name] && formik.touched[name] ? (

{formik.errors[name]}

      ) : null}

  );
};

As you can see in this example I have to explicitly pass required prop, but I want to achieve something like this

const FormikInputGroup = ({
  formik,
  label = "",
  name,
  fullWidth,
  ...props
}) => {
  return (

        {label}
       {formik.validationSchema[name].required && *}

      /// rest of the input component

  );
};


问:
Where does Postman store the history on mac?
I need to move from Mac to Linux and I would like to transfer my Postman history to Linux.

I'm not able to find where is the history stored on Mac.


问:
Python While loop is running several times more than it should
While Loop running extra several steps

Condition Outside While is False but inside while it becomes True,
how does the same variable start has different values inside and outside while loop??

Below is the python code I am executing

```<code>END = 10
STEP = 3
def generate(start , last ):
    print ("START:%s , END: %s " %(start, last))
    if start > END:
        print ("Should have stopped,", start, END)
    while (start < END):
        print (start < END, start , END)
        start = last
        last = last +STEP
        print("NEXT---start:%s Stop : %s " % (start, last))
        generate(start = start, last=last )
 generate(0, STEP)
</code>```

Output

This is the print output of above code .

```<code>START:0 , END: 3
     True 0 10
    NEXT---start:3 Stop : 6
    START:3 , END: 6
    True 3 10
    NEXT---start:6 Stop : 9
    START:6 , END: 9
    True 6 10
    NEXT---start:9 Stop : 12
    START:9 , END: 12
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 6 10
    NEXT---start:9 Stop : 12
    START:9 , END: 12
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 3 10
NEXT---start:6 Stop : 9
START:6 , END: 9
True 6 10
NEXT---start:9 Stop : 12
START:9 , END: 12
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 6 10
NEXT---start:9 Stop : 12
START:9 , END: 12
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
</code>```

It stops here only

Body:
While Loop running extra several steps

Condition Outside While is False but inside while it becomes True,
how does the same variable start has different values inside and outside while loop??

Below is the python code I am executing

END = 10
STEP = 3
def generate(start , last ):
    print ("START:%s , END: %s " %(start, last))
    if start > END:
        print ("Should have stopped,", start, END)
    while (start < END):
        print (start < END, start , END)
        start = last
        last = last +STEP
        print("NEXT---start:%s Stop : %s " % (start, last))
        generate(start = start, last=last )
 generate(0, STEP)

Output

This is the print output of above code .

START:0 , END: 3
     True 0 10
    NEXT---start:3 Stop : 6
    START:3 , END: 6
    True 3 10
    NEXT---start:6 Stop : 9
    START:6 , END: 9
    True 6 10
    NEXT---start:9 Stop : 12
    START:9 , END: 12
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 6 10
    NEXT---start:9 Stop : 12
    START:9 , END: 12
    True 9 10
    NEXT---start:12 Stop : 15
    START:12 , END: 15
    Should have stopped, 12 10
    True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 3 10
NEXT---start:6 Stop : 9
START:6 , END: 9
True 6 10
NEXT---start:9 Stop : 12
START:9 , END: 12
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 6 10
NEXT---start:9 Stop : 12
START:9 , END: 12
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10
True 9 10
NEXT---start:12 Stop : 15
START:12 , END: 15
Should have stopped, 12 10

It stops here only


问:
How do I set a custom marker icon in Quasar using Vue2-Leaflet?
I'm having problems displaying an icon marker image using vue2-Leaflet and Quasar. What gets displayed is a broken image and a 404 in the console. I have read close to all of the workarounds and did get it fixed using Leaflet.js and Quasar but not using vue2-Leaflet and Quasar.  My map code is:

```<code>  <l-map style="height: 1000px" :zoom="zoom" :center="center">
  <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
  <l-geo-json :geojson="geojson"></l-geo-json>
  <l-marker v-for="marker in markers" :key="marker.id" :visible="marker.visible" :draggable="marker.draggable" :lat-lng="marker.position"  :icon = "marker.icon"></l-marker>
  </l-map>
</code>```

and my JavaScript is:

```<code>markers: [
                { id: "m1", position : {lat:34.586956, lng:-82.238054}, tooltip: "tooltip for marker3", draggable: true, visible: true, icon: this.defaultIcon },
                { id: "m2", position : {lat:34.409676, lng:-82.246337}, tooltip: "tooltip for marker4", draggable: true, visible: true, icon: this.defaultIcon }
            ],

 defaultIcon: L.icon({
        iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png',
        shadowUrl: 'http://leafletjs.com/examples/custom-icons/leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
      }),
</code>```

I was trying to follow the example at https://jsfiddle.net/Boumi/z3bmc1ex/1/

but I still get a broken image and

```<code>  GET https://static.neshan.org/sdk/leaflet/1.4.0marker-icon.png 404
  GET https://static.neshan.org/sdk/leaflet/1.4.0marker-shadow.png 404
</code>```

I have also tried:

```<code>import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

    let DefaultIcon = L.icon({
    iconUrl: icon,
    shadowUrl: iconShadow,
    iconSize: [24,36],
    iconAnchor: [12,36]
});

L.Marker.prototype.options.icon = DefaultIcon;
</code>```

which fixed it using Leaflet.js and Quasar but not in vue2-leaflet.js and Quasar.

I'm open for suggestions.  Thanks

Body:
I'm having problems displaying an icon marker image using vue2-Leaflet and Quasar. What gets displayed is a broken image and a 404 in the console. I have read close to all of the workarounds and did get it fixed using Leaflet.js and Quasar but not using vue2-Leaflet and Quasar.  My map code is:

  <l-map style="height: 1000px" :zoom="zoom" :center="center">
  <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
  <l-geo-json :geojson="geojson"></l-geo-json>
  <l-marker v-for="marker in markers" :key="marker.id" :visible="marker.visible" :draggable="marker.draggable" :lat-lng="marker.position"  :icon = "marker.icon"></l-marker>
  </l-map>

and my JavaScript is:

markers: [
                { id: "m1", position : {lat:34.586956, lng:-82.238054}, tooltip: "tooltip for marker3", draggable: true, visible: true, icon: this.defaultIcon },
                { id: "m2", position : {lat:34.409676, lng:-82.246337}, tooltip: "tooltip for marker4", draggable: true, visible: true, icon: this.defaultIcon }
            ],

 defaultIcon: L.icon({
        iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png',
        shadowUrl: 'http://leafletjs.com/examples/custom-icons/leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
      }),

I was trying to follow the example at https://jsfiddle.net/Boumi/z3bmc1ex/1/

but I still get a broken image and

  GET https://static.neshan.org/sdk/leaflet/1.4.0marker-icon.png 404
  GET https://static.neshan.org/sdk/leaflet/1.4.0marker-shadow.png 404

I have also tried:

import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

    let DefaultIcon = L.icon({
    iconUrl: icon,
    shadowUrl: iconShadow,
    iconSize: [24,36],
    iconAnchor: [12,36]
});

L.Marker.prototype.options.icon = DefaultIcon;

which fixed it using Leaflet.js and Quasar but not in vue2-leaflet.js and Quasar.

I'm open for suggestions.  Thanks


问:
Pinia Vue3 - How to return a spread operator object?
I have an API to get user information like this:

```<code>{
  name: 'John Doe',
  birthday: '2000-01-01',
  email: 'john@doe.com'
  ...
}
</code>```

I have a Pinia store called userStore to handle all User-related data, including calling that API.

import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useUserStore= defineStore('user', () => {
  const profile = ref({});

  async function queryProfile() {
    const response = await axios.get('http://mysite.test/api/profile');
    profile.value = response.data;
  }

  return {
    profile,
    queryProfile,
  }
});
```
<p>It works but I don't like how I need to write <code>userStore.profile.name</code> to get the data.</p>
<p>I prefer if we can directly call <code>userStore.name</code>.</p>
<p>I tried spreading the <code>profile</code> like this but doesn't work (no error message, the store is empty when checked with devtools):</p>
<pre class="lang-js prettyprint-override"><code>return {
  ...profile,
  queryProfile,
};
</code>```

I also tried using toRefs, but same error:

```<code>return {
  ...toRefs(profile),
  queryProfile,
};
</code>```

Technically I can go the dirty-route and do this:

import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useUserStore= defineStore('user', () => {
  const name = ref('');
  const birthday = ref('');
  const email = ref('');

  async function queryProfile() {
    const response = await axios.get('http://mysite.test/api/profile');
    name.value = response.data.name;
    birthday.value = response.data.birthday;
    email.value = response.data.email;
  }

  return {
    name,
    birthday,
    email,
    queryProfile,
  }
});
```

But I have a lot of fields in the Profile, so this is the last resort if no other way.

Thanks before.

Body:
I have an API to get user information like this:

{
  name: 'John Doe',
  birthday: '2000-01-01',
  email: 'john@doe.com'
  ...
}

I have a Pinia store called userStore to handle all User-related data, including calling that API.

import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useUserStore= defineStore('user', () => {
  const profile = ref({});

  async function queryProfile() {
    const response = await axios.get('http://mysite.test/api/profile');
    profile.value = response.data;
  }

  return {
    profile,
    queryProfile,
  }
});

It works but I don't like how I need to write userStore.profile.name to get the data.

I prefer if we can directly call userStore.name.

I tried spreading the profile like this but doesn't work (no error message, the store is empty when checked with devtools):

return {
  ...profile,
  queryProfile,
};

I also tried using toRefs, but same error:

return {
  ...toRefs(profile),
  queryProfile,
};

Technically I can go the dirty-route and do this:

import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useUserStore= defineStore('user', () => {
  const name = ref('');
  const birthday = ref('');
  const email = ref('');

  async function queryProfile() {
    const response = await axios.get('http://mysite.test/api/profile');
    name.value = response.data.name;
    birthday.value = response.data.birthday;
    email.value = response.data.email;
  }

  return {
    name,
    birthday,
    email,
    queryProfile,
  }
});

But I have a lot of fields in the Profile, so this is the last resort if no other way.

Thanks before.


问:
fetch fails silently in Vercel
I have a simple Express.js API that works fine locally. But when I deploy the API to Vercel, any endpoints with fetch fail with a 404 without logging anything. Here is a minimal example:

```<code>import express from "express"
import fetch from "node-fetch"
import cors from "cors"

const app = express()
app.use(express.json())
app.use(express.urlencoded())
app.use(cors())

app.get("/testfetch", async (req, res) => {
    const test = await fetch("https://www.google.com").then(res => res.text());
    res.send(test)
})

app.get("/time", async (req, res) => {
    res.send(new Date())
})
</code>```

The /time endpoint works fine and returns the server time. The /testfetch endpoint returns a 404. However, locally both endpoints work.

How do I get fetch to work in Vercel?

Title: fetch fails silently in Vercel

Body:
I have a simple Express.js API that works fine locally. But when I deploy the API to Vercel, any endpoints with fetch fail with a 404 without logging anything. Here is a minimal example:

import express from "express"
import fetch from "node-fetch"
import cors from "cors"

const app = express()
app.use(express.json())
app.use(express.urlencoded())
app.use(cors())

app.get("/testfetch", async (req, res) => {
    const test = await fetch("https://www.google.com").then(res => res.text());
    res.send(test)
})

app.get("/time", async (req, res) => {
    res.send(new Date())
})

The /time endpoint works fine and returns the server time. The /testfetch endpoint returns a 404. However, locally both endpoints work.

How do I get fetch to work in Vercel?


问:
I have these models i want to get the postinlanguage queryset based on how much comments they have
i have these models in django

```<code>class PostInLanguages(models.Model):
    post_in_language_uuid = models.UUIDField(
        default=uuid.uuid4, editable=False)
    post = models.ForeignKey(
        Post, related_name='post_language', null=False, on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_language = models.BooleanField(default=True)
    parent_post_language_id = models.PositiveIntegerField(null=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    like = models.ManyToManyField(
        'User', through='PostLanguageLike', related_name='post_like', blank=True)
    hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True)
    created_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}'.format(self.post.id)

    class Meta:
        indexes = [
                models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']),
            ]
</code>```
```<code>class Comments(models.Model):
    comment_uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    language_post = models.ForeignKey(
        PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_comment = models.BooleanField(default=True)
    parent_post_comment_id = models.PositiveIntegerField(null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    description = models.CharField(max_length=400, blank=False)
    created_on = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["-created_on"]
        indexes = [
                models.Index(fields=['comment_uuid', 'parent_post_comment_id', 'is_post_comment', 'language_post']),
            ]

    def __str__(self):
        return '{}'.format(self.user)

    def total_comment(self):
        return self.language_post.count()
</code>```

Im trying to get the postinlanguage queryset based on how much comments they have.

and i want to make the filter of minimum this much comments

haven't got any success.

Body:
i have these models in django

class PostInLanguages(models.Model):
    post_in_language_uuid = models.UUIDField(
        default=uuid.uuid4, editable=False)
    post = models.ForeignKey(
        Post, related_name='post_language', null=False, on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_language = models.BooleanField(default=True)
    parent_post_language_id = models.PositiveIntegerField(null=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    like = models.ManyToManyField(
        'User', through='PostLanguageLike', related_name='post_like', blank=True)
    hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True)
    created_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}'.format(self.post.id)

    class Meta:
        indexes = [
                models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']),
            ]

class Comments(models.Model):
    comment_uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    language_post = models.ForeignKey(
        PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE)
    language = models.ForeignKey(
        Languages, default=2, on_delete=models.CASCADE)
    is_post_comment = models.BooleanField(default=True)
    parent_post_comment_id = models.PositiveIntegerField(null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    description = models.CharField(max_length=400, blank=False)
    created_on = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["-created_on"]
        indexes = [
                models.Index(fields=['comment_uuid', 'parent_post_comment_id', 'is_post_comment', 'language_post']),
            ]

    def __str__(self):
        return '{}'.format(self.user)

    def total_comment(self):
        return self.language_post.count()

Im trying to get the postinlanguage queryset based on how much comments they have.

and i want to make the filter of minimum this much comments

haven't got any success.