问:
NestJS for same Applicaiton to use multiple Connections using TypeORM module
We re-write an API to NestJS. However, due to a business logic older framework developers replicated the same code base each time. So itt is required to connect to multiple databases which contain similar tables. For example if one Database contains tables user,facilities and products then the other contains all of them too. In short everything is duplicate for each installation. Only the content of the databases is of course different.

Let's go to coding shall we? To prevent the duplication at least of the code base we tried to create named multiple connections, named after the company name i.e db_google,db_linkedin and a param in url that defines which connection to fetch from the pool

```<code>app.module.ts

imports: [
  TypeOrmModule.forRoot({
    type: 'mysql',
    name: 'google',
    host: 'our_host_url',
    port: 3306,
    username: 'username',
    password: 'password',
    database: 'db_google',
    entities: [Facility, FacilityCategory, Customer],
    synchronize: false,
  }),
  TypeOrmModule.forRoot({
    type: 'mysql',
    name: 'linkedin',
    host: 'our_host_url',
    port: 3306,
    username: 'username',
    password: 'password',
    database: 'db_linkedin',
    entities: [Facility, FacilityCategory, Customer],
    synchronize: false,

  }),

</code>```

After this we import it to each module we need to fetch data from DB (almost every module import it)

```<code>customer.module.ts
imports: [
  TypeOrmModule.forFeature([Customer, Facility], 'db_google'),
  TypeOrmModule.forFeature([Customer, Facility], 'db_linkedin'),
],

</code>```

To distinct databases in each [module].service.ts we use switch case and using the parameter from url to define which connection to use

```<code>customer.service.ts

constructor(
  @InjectDataSource('google')
  private dataSourceGoogle: DataSource,
  @InjectDataSource('linkedin')
  private dataSourceLinkedin: DataSource,
) {}

async findCustomer(
  username: string,
  companyName: string,
): Promise<Customer | null> {
  switch (companyName) {
    case 'apollohotels':
      return this.dataSourceGoogle.getRepository(Customer).findOneBy({
        username: username,
      });
    case 'saniresort':
      return this.dataSourceLinkedin.getRepository(Customer).findOneBy({
        username: username,
      });
  }
}

</code>```

So we thought to prevent duplication code to create a module to import all these databases for example "ConnectionPool" module, and import it to each module that needs to fetch data from DB. And their service to return the correct datasource depending the companyName parameter. It is a good approach? Does it happen someone to have the same problem and find another better solution?

Body:
We re-write an API to NestJS. However, due to a business logic older framework developers replicated the same code base each time. So itt is required to connect to multiple databases which contain similar tables. For example if one Database contains tables user,facilities and products then the other contains all of them too. In short everything is duplicate for each installation. Only the content of the databases is of course different.

Let's go to coding shall we? To prevent the duplication at least of the code base we tried to create named multiple connections, named after the company name i.e db_google,db_linkedin and a param in url that defines which connection to fetch from the pool

app.module.ts

imports: [
  TypeOrmModule.forRoot({
    type: 'mysql',
    name: 'google',
    host: 'our_host_url',
    port: 3306,
    username: 'username',
    password: 'password',
    database: 'db_google',
    entities: [Facility, FacilityCategory, Customer],
    synchronize: false,
  }),
  TypeOrmModule.forRoot({
    type: 'mysql',
    name: 'linkedin',
    host: 'our_host_url',
    port: 3306,
    username: 'username',
    password: 'password',
    database: 'db_linkedin',
    entities: [Facility, FacilityCategory, Customer],
    synchronize: false,

  }),

After this we import it to each module we need to fetch data from DB (almost every module import it)

customer.module.ts
imports: [
  TypeOrmModule.forFeature([Customer, Facility], 'db_google'),
  TypeOrmModule.forFeature([Customer, Facility], 'db_linkedin'),
],

To distinct databases in each [module].service.ts we use switch case and using the parameter from url to define which connection to use

customer.service.ts

constructor(
  @InjectDataSource('google')
  private dataSourceGoogle: DataSource,
  @InjectDataSource('linkedin')
  private dataSourceLinkedin: DataSource,
) {}

async findCustomer(
  username: string,
  companyName: string,
): Promise<Customer | null> {
  switch (companyName) {
    case 'apollohotels':
      return this.dataSourceGoogle.getRepository(Customer).findOneBy({
        username: username,
      });
    case 'saniresort':
      return this.dataSourceLinkedin.getRepository(Customer).findOneBy({
        username: username,
      });
  }
}

So we thought to prevent duplication code to create a module to import all these databases for example "ConnectionPool" module, and import it to each module that needs to fetch data from DB. And their service to return the correct datasource depending the companyName parameter. It is a good approach? Does it happen someone to have the same problem and find another better solution?


来源: stackexchange

问:
GDP Pyomo: List of Disjunctions
I would like to create a disjunction OR for each c in model.Cset. The code below somehow works, but it only takes the value of the last c in the for loop. The aim is to have a disjunction for each c: model.C2(c1), model.C2(c2),etc.

So, for each c, x[(p,c,m)] is forced to assume either the model.d1.c value or model.d2.c value for each m.
I tried also by defining

```<code>model.C2 = pyo.ConstraintList()
</code>```

and then changing the last sentence as

```<code>model.C2.add( Disjunction(expr=[model.d1, model.d2] )
</code>```

but it gives me the following error: ValueError: Constraint 'C2[1]' does not have a proper value. Found 'ScalarDisjunction' Expecting a tuple or relational expression. Examples: sum(model.costs) == model.income(0, model.price[item], 50) model.x is the variable model.Dparam is a parameter model.d1.c and model.d2.c are Constraint lists

```<code>
for c in model.Cset :
    model.d1 = Disjunct()
    model.d1.c = Constraint(expr= sum(model.x[(p,c,m)] * model.Dparam[(p,c,m)] for m in list_m)
                                == sum(model.Dparam[(p,c,m)] for m in list_m)
                               )
    model.d2 = Disjunct()
    model.d2.c = Constraint(expr= sum(model.x[(p,c,m)] * model.Dparam[(p,c,m)] for m in list_m) == 0)

    model.C2  = Disjunction(expr=[model.d1, model.d2])

</code>```

ContentLicense: CC BY-SA 4.0

Title: GDP Pyomo: List of Disjunctions

Body:
I would like to create a disjunction OR for each c in model.Cset. The code below somehow works, but it only takes the value of the last c in the for loop. The aim is to have a disjunction for each c: model.C2(c1), model.C2(c2),etc.

So, for each c, x[(p,c,m)] is forced to assume either the model.d1.c value or model.d2.c value for each m.
I tried also by defining

model.C2 = pyo.ConstraintList()

and then changing the last sentence as

model.C2.add( Disjunction(expr=[model.d1, model.d2] )

but it gives me the following error: ValueError: Constraint 'C2[1]' does not have a proper value. Found 'ScalarDisjunction' Expecting a tuple or relational expression. Examples: sum(model.costs) == model.income(0, model.price[item], 50) model.x is the variable model.Dparam is a parameter model.d1.c and model.d2.c are Constraint lists

for c in model.Cset :
    model.d1 = Disjunct()
    model.d1.c = Constraint(expr= sum(model.x[(p,c,m)] * model.Dparam[(p,c,m)] for m in list_m)
                                == sum(model.Dparam[(p,c,m)] for m in list_m)
                               )
    model.d2 = Disjunct()
    model.d2.c = Constraint(expr= sum(model.x[(p,c,m)] * model.Dparam[(p,c,m)] for m in list_m) == 0)

    model.C2  = Disjunction(expr=[model.d1, model.d2])


问:
Virtualenv error: command 'cmake' failed: No such file or directory
I get the following error in my virtualenv when installing; snowflake-connector-python

```<code>% pip3 install snowflake-connector-python

Collecting snowflake-connector-python
  Downloading snowflake-connector-python-2.9.0.tar.gz (394 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 394.3/394.3 kB 3.9 MB/s eta 0:00:00
  Installing build dependencies ... error
  error: subprocess-exited-with-error

  ...

  Building wheels for collected packages: pyarrow
       Building wheel for pyarrow (pyproject.toml): started
       Building wheel for pyarrow (pyproject.toml): finished with status 'error'
       error: subprocess-exited-with-error

  ...

  Traceback (most recent call last):
  File "/my_virtualenvs/tester/bin/cmake", line 5, in <module>
       from cmake import cmake
       ModuleNotFoundError: No module named 'cmake'
       error: command '/my_virtualenvs/tester/bin/cmake' failed with exit code 1
</code>```

cmake is installed in the directory noted in the error and is available via the PATH:

```<code>% ECHO $PATH
/my_virtualenvs/tester/bin/cmake:/my_virtualenvs/tester/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

I can import cmake in the Python shell and call it via the terminal:

```<code>% bin/cmake --version
cmake version 3.25.0
</code>```

Environment:

MacOS 12.5 Monterey

Apple Silicon M1

How can I solve this error?

Body:
I get the following error in my virtualenv when installing; snowflake-connector-python

% pip3 install snowflake-connector-python

Collecting snowflake-connector-python
  Downloading snowflake-connector-python-2.9.0.tar.gz (394 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 394.3/394.3 kB 3.9 MB/s eta 0:00:00
  Installing build dependencies ... error
  error: subprocess-exited-with-error

  ...

  Building wheels for collected packages: pyarrow
       Building wheel for pyarrow (pyproject.toml): started
       Building wheel for pyarrow (pyproject.toml): finished with status 'error'
       error: subprocess-exited-with-error

  ...

  Traceback (most recent call last):
  File "/my_virtualenvs/tester/bin/cmake", line 5, in <module>
       from cmake import cmake
       ModuleNotFoundError: No module named 'cmake'
       error: command '/my_virtualenvs/tester/bin/cmake' failed with exit code 1

cmake is installed in the directory noted in the error and is available via the PATH:

% ECHO $PATH
/my_virtualenvs/tester/bin/cmake:/my_virtualenvs/tester/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

I can import cmake in the Python shell and call it via the terminal:

% bin/cmake --version
cmake version 3.25.0

Environment:

MacOS 12.5 Monterey

Apple Silicon M1

How can I solve this error?


问:
Carve out admin module from main app module in nestjs to run on separate server
i am currently working on a project which has multiple modules.All code is in a single codebase.One of the modules is Admin module. Now I need to run this admin module on another server separate from the main app server.Is there any way I can achieve this? Help would be greatly appreciated. Using nestjs v9

Tried nestjs standalone application but it did't work for this use case.


问:
Let a user from SQL database to chat in socket.io chat app
I'm making a chat application with socket.io. I already have a login system where a user is stored in a SQL database.
So I want my chat app to get the user from the database to access the chat.
I have tried several methods, and I often get this error:

```<code>Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: messages.username
</code>```

It should not be allowed be NULL in the username, as I want the users that are logged in to access the chat.

Here is some of my code:

From my server:

```<code>io.on('connection', (socket) => {

  console.log("a user connected");

  });
  socket.on('join', async function(name){

    socket.username = await getUserByUsername();
      io.sockets.emit("addChatter", name);

      const messages = await getAllMessages();
      io.sockets.emit('messages', messages);
      io.sockets.emit('new_message', {username: 'Server', message: 'Velkommen ' + name + '!'});

    });

    // When server recieves a new message
  socket.on('new_message', function(message){

    addMessageToDatabase({message: message, username: socket.username});
    const username = socket.username
    console.log(username + ': ' + message);
    io.sockets.emit("new_message", {username, message});
  });

  // When a user dis
  socket.on('disconnect', function(name){
    console.log('a user disconnected');
    io.sockets.emit("removeChatter", socket.username);
  });
});
</code>```

My client:

```<code>const socket = io()

   socket.on('connection', async function (e) {
   e.preventDefault();
   var username = await getUserByUsername();
   socket.emit('join', username);
   })

  // Listens for form submission
  $("#chatForm").on('submit', function(e){
    e.preventDefault();
    var message = $("#message").val();
    socket.emit('new_message', message)
    $("#message").val("");
  })

  // adds HTML message to chat
  const addMessageToChat = (message) => {
    const messageElement = document.createElement('li');

    messageElement.innerText = new Date(message.timestamp).toLocaleTimeString('DK')
      + ': ' + message.username
      + ": " + message.message

    $("#messagesContainer").append(messageElement);
  }

  // On receiving one message
  socket.on('new_message', function(message){
    console.log('message: ', message)
    addMessageToChat(message);
  })

  // on receiving a list of messages
  socket.on('messages', function(messages) {
    console.log('messages: ', messages)
    messages.forEach(message => {
      addMessageToChat(message);
    })
  })

  // On person joined chat
  socket.on('addChatter', function(name){
    var $chatter = $("<li>", {
      text: name,
      attr: {
        'data-name':name
      }
    })
    $("#chatters").append($chatter)
  })

  // On person disconnect
  socket.on("removeChatter", function(name){
    $("#chatters li[data-name=" + name +"]").remove()
  })
</code>```

Body:
I'm making a chat application with socket.io. I already have a login system where a user is stored in a SQL database.
So I want my chat app to get the user from the database to access the chat.
I have tried several methods, and I often get this error:

Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: messages.username

It should not be allowed be NULL in the username, as I want the users that are logged in to access the chat.

Here is some of my code:

From my server:

io.on('connection', (socket) => {

  console.log("a user connected");

  });
  socket.on('join', async function(name){

    socket.username = await getUserByUsername();
      io.sockets.emit("addChatter", name);

      const messages = await getAllMessages();
      io.sockets.emit('messages', messages);
      io.sockets.emit('new_message', {username: 'Server', message: 'Velkommen ' + name + '!'});

    });

    // When server recieves a new message
  socket.on('new_message', function(message){

    addMessageToDatabase({message: message, username: socket.username});
    const username = socket.username
    console.log(username + ': ' + message);
    io.sockets.emit("new_message", {username, message});
  });

  // When a user dis
  socket.on('disconnect', function(name){
    console.log('a user disconnected');
    io.sockets.emit("removeChatter", socket.username);
  });
});

My client:

const socket = io()

   socket.on('connection', async function (e) {
   e.preventDefault();
   var username = await getUserByUsername();
   socket.emit('join', username);
   })

  // Listens for form submission
  $("#chatForm").on('submit', function(e){
    e.preventDefault();
    var message = $("#message").val();
    socket.emit('new_message', message)
    $("#message").val("");
  })

  // adds HTML message to chat
  const addMessageToChat = (message) => {
    const messageElement = document.createElement('li');

    messageElement.innerText = new Date(message.timestamp).toLocaleTimeString('DK')
      + ': ' + message.username
      + ": " + message.message

    $("#messagesContainer").append(messageElement);
  }

  // On receiving one message
  socket.on('new_message', function(message){
    console.log('message: ', message)
    addMessageToChat(message);
  })

  // on receiving a list of messages
  socket.on('messages', function(messages) {
    console.log('messages: ', messages)
    messages.forEach(message => {
      addMessageToChat(message);
    })
  })

  // On person joined chat
  socket.on('addChatter', function(name){
    var $chatter = $("
", {
      text: name,
      attr: {
        'data-name':name
      }
    })
    $("#chatters").append($chatter)
  })

  // On person disconnect
  socket.on("removeChatter", function(name){
    $("#chatters li[data-name=" + name +"]").remove()
  })


问:
GridView infinite pagination Range error Invalid value: Not in inclusive range 0..21: 22
I have infinite pagination in my gridView but when i want to add CircularProgressIndicator() to my GridView i get RangeError (index): Invalid value: Not in inclusive range 0..21: 22, in itemCount i have items + 1, why is my CircularProgressIndicator() not working?

```<code>  Widget buildCatalog(List<Product> product) => GridView.builder(
    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
      // mainAxisExtent: ,
        maxCrossAxisExtent: 300,
        childAspectRatio: MediaQuery.of(context).size.width*1.22 /
            (MediaQuery.of(context).size.height),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10),
    controller: sController,
    itemCount: product.length + 1,
    itemBuilder: (context, index) {
      final media = product[index].media?.map((e) => e.toJson()).toList();
      final photo = media?[0]['links']['local']['thumbnails']['350'];
      if (index < product.length) {
        final productItem = product[index];
        return GestureDetector(
          onTap: () {
          },
          child: Container(
            child: Column(
              children: <Widget>[
                InkWell(
                  child: Container(
                    margin: EdgeInsets.only(top: 5),
                    child: Image.network(...)
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  '${productItem.name}\n',
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14),
                ),
                // Spacer(),
                SizedBox(height: 8),
                Text('${productItem.price} ₸',
                    textAlign: TextAlign.start,
                    style: TextStyle(fontSize: 20, color: Colors.red)),
                SizedBox(height: 5),
                buildButton(index, productItem.id),
              ],
            ),
          ),
        );
      }
      return const Center(child: CircularProgressIndicator(),);
    },
  );
</code>```

Body:
I have infinite pagination in my gridView but when i want to add CircularProgressIndicator() to my GridView i get RangeError (index): Invalid value: Not in inclusive range 0..21: 22, in itemCount i have items + 1, why is my CircularProgressIndicator() not working?

  Widget buildCatalog(List<Product> product) => GridView.builder(
    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
      // mainAxisExtent: ,
        maxCrossAxisExtent: 300,
        childAspectRatio: MediaQuery.of(context).size.width*1.22 /
            (MediaQuery.of(context).size.height),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10),
    controller: sController,
    itemCount: product.length + 1,
    itemBuilder: (context, index) {
      final media = product[index].media?.map((e) => e.toJson()).toList();
      final photo = media?[0]['links']['local']['thumbnails']['350'];
      if (index < product.length) {
        final productItem = product[index];
        return GestureDetector(
          onTap: () {
          },
          child: Container(
            child: Column(
              children: <Widget>[
                InkWell(
                  child: Container(
                    margin: EdgeInsets.only(top: 5),
                    child: Image.network(...)
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  '${productItem.name}\n',
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14),
                ),
                // Spacer(),
                SizedBox(height: 8),
                Text('${productItem.price} ₸',
                    textAlign: TextAlign.start,
                    style: TextStyle(fontSize: 20, color: Colors.red)),
                SizedBox(height: 5),
                buildButton(index, productItem.id),
              ],
            ),
          ),
        );
      }
      return const Center(child: CircularProgressIndicator(),);
    },
  );


问:
Assuring that Objects are Disposed before Finalization in C#
I have trouble implementing a C# wrapper for rcl which has a struct named rcl_context_s encapsulating non-global state for some rcl_node_s structs.
There are functions for finalizing these structs which require that all nodes of a given context are finalized before the context itself is finalized.

I implemented IDisposable for the context wrapper which has a private Dictionary containing all associated nodes by disposing all nodes before calling the rcl finalization function.

I want the context to dispose itself (and all associated nodes) on finalization if it has not been disposed yet but since the disposing is happening during finalization I cant count on other objects like the Dictionary for not being finalized.

I thought that using GC.SuppressFinalize and GC.ReRegisterForFinalize for preventing the Dictionary from being finalized before the wrapper is disposed could solve this issue since the node wrappers have no finalizer because they can rely on the context wrapper to dispose them if the user forgets it.

I want to know if there are any problems with my idea or betters ways of solving this problem since I am not that experienced in C# and its (possible) quirks.

Update

I just found this question which had a similar problem and seems to hint that preventing the Dictionary from being finalized does not prevent its internals from being finalized and thus becoming unusable.

Maybe I can solve the problem by allowing the node wrappers to dispose themselves on finalization and using CriticalFinalizerObject to make the context wrappers finalizer run after them but that would still be unsafe since the finalizers of the node wrappers are not guaranteed to run.


问:
How to map some fields to their own columns and some to a single JSON column with JPA
We have a class that we want to store to a table, for example:

@Entity
public class SomeClass {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    private String fieldA;

    private String fieldB;

    private String fieldC;
}
```
<p>Is there a way to map some of the fields, e.g. <code>id</code> and <code>fieldA</code> to specific columns and the others to a single JSON column so that the result would be:</p>
```mysql> select * from SomeClass;
+----+--------+--------------------------------+
| id | fieldA | otherFields                    |
+----+--------+--------------------------------+
|  1 | aaa    | {"fieldB":"b1"}                |
|  2 | bbb    | {"fieldB":"b2", fieldC: "c2"}  |
+----+--------+--------------------------------+
```

We don't want to move fieldB and fieldC to a separate class.

I've tried to use the @Convert annotation with an AttributeConverter but the AttributeConverter can only be used for a single column.

Body:
We have a class that we want to store to a table, for example:

@Entity
public class SomeClass {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    private String fieldA;

    private String fieldB;

    private String fieldC;
}

Is there a way to map some of the fields, e.g. id and fieldA to specific columns and the others to a single JSON column so that the result would be:

mysql> select * from SomeClass;
+----+--------+--------------------------------+
| id | fieldA | otherFields                    |
+----+--------+--------------------------------+
|  1 | aaa    | {"fieldB":"b1"}                |
|  2 | bbb    | {"fieldB":"b2", fieldC: "c2"}  |
+----+--------+--------------------------------+

We don't want to move fieldB and fieldC to a separate class.

I've tried to use the @Convert annotation with an AttributeConverter but the AttributeConverter can only be used for a single column.


问:
Reverse the order of variables in the confidence interval plot
How do I reverse the order of variables in the confidence interval plot?
Here are the data:

```<code>dataout
              variables coefficients lower..95 upper..95
             Mother    0.9411774 0.8968472 0.9876988
            sibling    0.8714648 0.7983499 0.9512757
                 X1    1.1250240 1.0106318 1.2523641
                 X2    1.1792050 1.0062237 1.3819239
                 X3    1.0473570 0.8227960 1.3332062
                 X4    1.5371143 1.2682586 1.8629644
                 X5    1.3714805 1.1762861 1.5990656
                 X6    0.8939320 0.7480613 1.0682473
                 X7    0.7126186 0.5683382 0.8935264
</code>```

When I plot the confidence intervals, the list of variables runs from the bottom to the top. How can I reverse it so that the variables are listed from the top to bottom?

Body:
How do I reverse the order of variables in the confidence interval plot?
Here are the data:

dataout
              variables coefficients lower..95 upper..95
             Mother    0.9411774 0.8968472 0.9876988
            sibling    0.8714648 0.7983499 0.9512757
                 X1    1.1250240 1.0106318 1.2523641
                 X2    1.1792050 1.0062237 1.3819239
                 X3    1.0473570 0.8227960 1.3332062
                 X4    1.5371143 1.2682586 1.8629644
                 X5    1.3714805 1.1762861 1.5990656
                 X6    0.8939320 0.7480613 1.0682473
                 X7    0.7126186 0.5683382 0.8935264

When I plot the confidence intervals, the list of variables runs from the bottom to the top. How can I reverse it so that the variables are listed from the top to bottom?


问:
Deploy to App Engine Standard dialog doesn't appear - Eclipse Version: 2022-12 (4.26.0)

Cloud Tools for Eclipse version: 1.9.1.202211291623

Google Cloud SDK version: 411.0.0 (auto-managed)

Eclipse version: 4.26.0.v20221123-1800

OS: Mac OS X 13.0.1

Java version: 1.8.0_352

I've a GAE project. When I try to deploy, the deploy dialog with the list of GAE projects doesn't appear. I've installed 03-2022 eclipse version and then installed Google Cloud Tools plugin. Then I updated the eclipse version to the latest i.e 12-2022. I've also installed https://github.com/ianbrandt/m2e-maven-dependency-plugin

I also tried to upgrade to 06-2022 & 09-2022, but it doesn't work.

I've also raised the issue in google-cloud-eclipse.
https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/3703

https://www.dropbox.com/s/i06xvbdrksue8c6/Deploy%20Eclipse.mov?dl=0


问:
How to download file from server using ftp or other methods in REACT-NATIVE?
I'm using Hostinger server and i want to download file from server.Is there any way to perform these operation(download or upload) directly from REACT-NATIVE app.
Please don't suggest REACT-NATIVE-FTP.

I'have tried REACT-NATIVE-FTP but it didn't works well.


问:
How to properly represent the bayesian linear regression in a plot? (PyMC)
I am currently trying to learn Bayesian Statistics and how to implement it with pymc for a project at work.
So far I'm just playing around with this linear regression tutorial.

Here's the code snippet to generate y_observed:

```<code>size = 200
true_intercept = 1
true_slope = 2

x = np.linspace(0,1,size)

# y = a + b*x

true_y = true_intercept + true_slope * x
y_observed = true_y + np.random.normal(scale=0.5, size=size)
</code>```

And here's the plot of y_observed and true_y:

Then, following the tutorial I fit the model as

```<code>with pm.Model() as model:
    sigma = pm.HalfCauchy("sigma", beta=10)

    intercept = pm.Normal("intercept", 0, sigma=20)

    slope = pm.Normal("slope", 0, sigma=20)

    likelihood = pm.Normal("y", mu = intercept + slope*x, sigma=sigma, observed=y_observed)

    idata = pm.sample(3000)
</code>```

My question then is... how should I represent the posterior that I got (idata.posterior) in my graph?

Considering that the posterior was sampled from 4 different chains, I thought in calculating the mean of my intercept, slope and sigma; and plot them plus and minus the std of sigma... but that gave me a very bad line, which makes me believe that is wrong.

Below my code snippet for what I just mentioned and the graph that I got:

```<code>def plot(x, true_y, true_line,idata):
    intercept_mean = float(idata.posterior.intercept.mean()) # get the mean of the intercept (from all 4 chains)
    slope_mean = float(idata.posterior.slope.mean()) # get the mean of the slope (from all 4 chains)
    sigma_mean = float(idata.posterior.sigma.mean()) # the mean of the error (from all 4 chains)
    sigma_std = float(idata.posterior.sigma.std()) # the std of the error (from all 4 chains)

    y_pred_no_std = intercept_mean + slope_mean*x + sigma_mean
    y_pred_plus = y_pred_no_std + sigma_std
    y_pred_minus = y_pred_no_std - sigma_std

    fig = plt.figure(figsize=(7, 7))
    ax = fig.add_subplot(111, xlabel="x", ylabel="y", title="Generated data and underlying model")
    ax.plot(x, true_line, "x", label="y_observed")
    ax.plot(x, true_y, label="true regression line", lw=2.0)
    ax.plot(x, y_pred_plus, label="pymc regression mean + std")
    ax.plot(x, y_pred_no_std, label='pymc regression mean')
    ax.plot(x, y_pred_minus, label="pymc regression mean - std")
    plt.legend(loc=0)
</code>```

Body:
I am currently trying to learn Bayesian Statistics and how to implement it with pymc for a project at work.
So far I'm just playing around with this linear regression tutorial.

Here's the code snippet to generate y_observed:

size = 200
true_intercept = 1
true_slope = 2

x = np.linspace(0,1,size)

# y = a + b*x

true_y = true_intercept + true_slope * x
y_observed = true_y + np.random.normal(scale=0.5, size=size)

And here's the plot of y_observed and true_y:

Then, following the tutorial I fit the model as

with pm.Model() as model:
    sigma = pm.HalfCauchy("sigma", beta=10)

    intercept = pm.Normal("intercept", 0, sigma=20)

    slope = pm.Normal("slope", 0, sigma=20)

    likelihood = pm.Normal("y", mu = intercept + slope*x, sigma=sigma, observed=y_observed)

    idata = pm.sample(3000)

My question then is... how should I represent the posterior that I got (idata.posterior) in my graph?

Considering that the posterior was sampled from 4 different chains, I thought in calculating the mean of my intercept, slope and sigma; and plot them plus and minus the std of sigma... but that gave me a very bad line, which makes me believe that is wrong.

Below my code snippet for what I just mentioned and the graph that I got:

def plot(x, true_y, true_line,idata):
    intercept_mean = float(idata.posterior.intercept.mean()) # get the mean of the intercept (from all 4 chains)
    slope_mean = float(idata.posterior.slope.mean()) # get the mean of the slope (from all 4 chains)
    sigma_mean = float(idata.posterior.sigma.mean()) # the mean of the error (from all 4 chains)
    sigma_std = float(idata.posterior.sigma.std()) # the std of the error (from all 4 chains)

    y_pred_no_std = intercept_mean + slope_mean*x + sigma_mean
    y_pred_plus = y_pred_no_std + sigma_std
    y_pred_minus = y_pred_no_std - sigma_std

    fig = plt.figure(figsize=(7, 7))
    ax = fig.add_subplot(111, xlabel="x", ylabel="y", title="Generated data and underlying model")
    ax.plot(x, true_line, "x", label="y_observed")
    ax.plot(x, true_y, label="true regression line", lw=2.0)
    ax.plot(x, y_pred_plus, label="pymc regression mean + std")
    ax.plot(x, y_pred_no_std, label='pymc regression mean')
    ax.plot(x, y_pred_minus, label="pymc regression mean - std")
    plt.legend(loc=0)


问:
Name Arrtibute's functionality
How does the "name" attribute works within an input tag (radio type)?

I need to know how does it specify an option from the radio type, in other words how it works.

Title: Name Arrtibute's functionality


问:
Why is my dependency code not being transpiled?
I'm using Webpack and Babel together with the following webpack5.config.prod.js config and everything was fine until I added @googlemaps/markerclusterer as a dependency.

Everything works fine in most browsers however in IE11, I get errors I believe due to the fact that the MarkerClusterer code is not being transpiled to IE11 compatible code, it still using classes etc.

I do have the node_modules folder excluded in the config however I've attempted to include it (or exclude it from the exclude) but still nothing.

Any ideas where I'm going wrong here?

Also, does the @googlemaps/markerclusterer need to be added as a dependency? Could it not be simply added as a devDependency and then the library itself downloaded along with the main GMaps library?

Thanks in advance

```<code>const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const ESLintPlugin = require('eslint-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
    entry: [
        'core-js/stable',
        './index.ts',
        './scss/_main.scss'
    ],
    output: {
        path: path.resolve(__dirname, '../app/dist/'),
        filename: 'bundle.prod.js',
        publicPath: '',
    },
    resolve: {
        extensions: ['.js', '.ts'],
    },
    mode: 'production',
    target: ['web', 'es5'],
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-classes']
                        },
                    }
                ],
                exclude: /node_modules(?!\/@googlemaps\markerclusterer\/)/
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'styles.prod.css',
                        }
                    },
                    {
                        loader: 'extract-loader'
                    },
                    {
                        loader: 'css-loader?-url'
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'sass-loader'
                    }
                ],
            },
            {
                test: /\.css$/,
                use: ['css-loader'],
            },
        ],
    },
    plugins: [
        new ESLintPlugin({
            extensions: ['ts'],
        }),
        new CleanWebpackPlugin({
            dry: true,      // simulate the removal of files when true i.e. a dry-run
            verbose: true,  // output the deleted filenames (always enabled when dry is true)
        }),
    ],
    optimization: {
        minimize: true,
        minimizer: [
            new CssMinimizerPlugin(),
            new TerserPlugin(),
        ],
    },
};
</code>```

Body:
I'm using Webpack and Babel together with the following webpack5.config.prod.js config and everything was fine until I added @googlemaps/markerclusterer as a dependency.

Everything works fine in most browsers however in IE11, I get errors I believe due to the fact that the MarkerClusterer code is not being transpiled to IE11 compatible code, it still using classes etc.

I do have the node_modules folder excluded in the config however I've attempted to include it (or exclude it from the exclude) but still nothing.

Any ideas where I'm going wrong here?

Also, does the @googlemaps/markerclusterer need to be added as a dependency? Could it not be simply added as a devDependency and then the library itself downloaded along with the main GMaps library?

Thanks in advance

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const ESLintPlugin = require('eslint-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
    entry: [
        'core-js/stable',
        './index.ts',
        './scss/_main.scss'
    ],
    output: {
        path: path.resolve(__dirname, '../app/dist/'),
        filename: 'bundle.prod.js',
        publicPath: '',
    },
    resolve: {
        extensions: ['.js', '.ts'],
    },
    mode: 'production',
    target: ['web', 'es5'],
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-classes']
                        },
                    }
                ],
                exclude: /node_modules(?!\/@googlemaps\markerclusterer\/)/
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'styles.prod.css',
                        }
                    },
                    {
                        loader: 'extract-loader'
                    },
                    {
                        loader: 'css-loader?-url'
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'sass-loader'
                    }
                ],
            },
            {
                test: /\.css$/,
                use: ['css-loader'],
            },
        ],
    },
    plugins: [
        new ESLintPlugin({
            extensions: ['ts'],
        }),
        new CleanWebpackPlugin({
            dry: true,      // simulate the removal of files when true i.e. a dry-run
            verbose: true,  // output the deleted filenames (always enabled when dry is true)
        }),
    ],
    optimization: {
        minimize: true,
        minimizer: [
            new CssMinimizerPlugin(),
            new TerserPlugin(),
        ],
    },
};


问:
`ps --sort -cmd` on Unix is not sorting consistently on different servers
Given 2 servers, I want to print the ps for MYAPP on them.
Yet, despite the sort, both servers print QA and UAT in seemingly random orders.
(sorting by time seems to work fine)

BOTH SERVERS:
ps -ef
UID PID PPID C STIME TTY TIME CMD
..........
```
<pre class="lang-bash prettyprint-override"><code>BOTH SERVERS:
ps -ef | sort -k 8 | grep MYAPP
ourID #### ### # Dec01 ?    02:45:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....
ourID #### ### # Dec01 ?    06:00:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....
</code>```

But using ps built-in sort:

#SERVER 1:
ps -ef --sort -cmd | grep MYAPP

ourID #### ### # Dec01 ?    06:00:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....
ourID #### ### # Dec01 ?    02:45:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....

#SERVER 2:
ps -ef --sort -cmd | grep MYAPP
ourID #### ### # Dec01 ?    03:00:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....
ourID #### ### # Dec01 ?    06:45:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....
```

Body:
Given 2 servers, I want to print the ps for MYAPP on them.
Yet, despite the sort, both servers print QA and UAT in seemingly random orders.
(sorting by time seems to work fine)

BOTH SERVERS:
ps -ef
UID PID PPID C STIME TTY TIME CMD
..........

BOTH SERVERS:
ps -ef | sort -k 8 | grep MYAPP
ourID #### ### # Dec01 ?    02:45:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....
ourID #### ### # Dec01 ?    06:00:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....

But using ps built-in sort:

#SERVER 1:
ps -ef --sort -cmd | grep MYAPP

ourID #### ### # Dec01 ?    06:00:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....
ourID #### ### # Dec01 ?    02:45:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....

#SERVER 2:
ps -ef --sort -cmd | grep MYAPP
ourID #### ### # Dec01 ?    03:00:00 /path/to/our/java/MYAPP_SERVICE_QA_JAVA....
ourID #### ### # Dec01 ?    06:45:00 /path/to/our/java/MYAPP_SERVICE_UAT_JAVA....


问:
How do you switch the headers to columns using tabulate? instead of the headers in rows i want it in columns
```<code>from tabulate import tabulate as t
class INFO_SETUP():
  def infoSort(self,name):
    print("Format of table is:","Name","Phone Number","Office Location",sep="\n")
    global StaffName
    global StaffPhone
    global StaffOffice
    StaffName = ["Faran","Yahya","Hamza","Aliya","Zainab","Hashim","Kilian","Messi","Fatima","Imaan","Francis"]
    StaffPhone = [4374312,2784916,4009234,7859612,3469871,8376482,2385015,9091245,2551085,1745748,9375123]
    StaffOffice = ["London","Toronto","Riyadh","London","Washington","Indiana","Paris","Buenos Aires","Vaduz","Vatican City","Adelaide"]
    sorted(zip(StaffName,StaffPhone,StaffOffice))
    StaffName, StaffPhone, StaffOffice = zip(*sorted(zip(StaffName,StaffPhone,StaffOffice)))
    Info=[StaffName,StaffPhone,StaffOffice]
    table = t(Info, tablefmt='fancy_grid')
    print(table)
    for x in range(0,len(StaffName)):
      if name==StaffName[x]:
        print("Name Found",name,StaffPhone[x],StaffOffice[x],sep="\n")
</code>```
```<code>a=input("Enter Name → ")
INFO_SETUP().infoSort(a)
</code>```

the result:

```<code>Enter Name → Faran
Format of table is:
Name
Phone Number
Office Location
╒═════════╤═════════╤═════════╤══════════╤═════════╤═════════╤══════════════╤═════════╤══════════════╤════════════════╤═══════════════════╕
│         │         │         │          │         │         │              │         │ Name         │ Phone Number   │ Office Location   │
╞═════════╪═════════╪═════════╪══════════╪═════════╪═════════╪══════════════╪═════════╪══════════════╪════════════════╪═══════════════════╡
│ Aliya   │ Faran   │ Fatima  │ Francis  │ Hamza   │ Hashim  │ Imaan        │ Kilian  │ Messi        │ Yahya          │ Zainab            │
├─────────┼─────────┼─────────┼──────────┼─────────┼─────────┼──────────────┼─────────┼──────────────┼────────────────┼───────────────────┤
│ 7859612 │ 4374312 │ 2551085 │ 9375123  │ 4009234 │ 8376482 │ 1745748      │ 2385015 │ 9091245      │ 2784916        │ 3469871           │
├─────────┼─────────┼─────────┼──────────┼─────────┼─────────┼──────────────┼─────────┼──────────────┼────────────────┼───────────────────┤
│ London  │ London  │ Vaduz   │ Adelaide │ Riyadh  │ Indiana │ Vatican City │ Paris   │ Buenos Aires │ Toronto        │ Washington        │
╘═════════╧═════════╧═════════╧══════════╧═════════╧═════════╧══════════════╧═════════╧══════════════╧════════════════╧═══════════════════╛
Name Found
Faran
4374312
London
</code>```

I want it to say in the first column, the name then the phone number then the office location and finally start with the array. I don't want the phone number, office location and name to be in rows

Body:
from tabulate import tabulate as t
class INFO_SETUP():
  def infoSort(self,name):
    print("Format of table is:","Name","Phone Number","Office Location",sep="\n")
    global StaffName
    global StaffPhone
    global StaffOffice
    StaffName = ["Faran","Yahya","Hamza","Aliya","Zainab","Hashim","Kilian","Messi","Fatima","Imaan","Francis"]
    StaffPhone = [4374312,2784916,4009234,7859612,3469871,8376482,2385015,9091245,2551085,1745748,9375123]
    StaffOffice = ["London","Toronto","Riyadh","London","Washington","Indiana","Paris","Buenos Aires","Vaduz","Vatican City","Adelaide"]
    sorted(zip(StaffName,StaffPhone,StaffOffice))
    StaffName, StaffPhone, StaffOffice = zip(*sorted(zip(StaffName,StaffPhone,StaffOffice)))
    Info=[StaffName,StaffPhone,StaffOffice]
    table = t(Info, tablefmt='fancy_grid')
    print(table)
    for x in range(0,len(StaffName)):
      if name==StaffName[x]:
        print("Name Found",name,StaffPhone[x],StaffOffice[x],sep="\n")

a=input("Enter Name → ")
INFO_SETUP().infoSort(a)

the result:

Enter Name → Faran
Format of table is:
Name
Phone Number
Office Location
╒═════════╤═════════╤═════════╤══════════╤═════════╤═════════╤══════════════╤═════════╤══════════════╤════════════════╤═══════════════════╕
│         │         │         │          │         │         │              │         │ Name         │ Phone Number   │ Office Location   │
╞═════════╪═════════╪═════════╪══════════╪═════════╪═════════╪══════════════╪═════════╪══════════════╪════════════════╪═══════════════════╡
│ Aliya   │ Faran   │ Fatima  │ Francis  │ Hamza   │ Hashim  │ Imaan        │ Kilian  │ Messi        │ Yahya          │ Zainab            │
├─────────┼─────────┼─────────┼──────────┼─────────┼─────────┼──────────────┼─────────┼──────────────┼────────────────┼───────────────────┤
│ 7859612 │ 4374312 │ 2551085 │ 9375123  │ 4009234 │ 8376482 │ 1745748      │ 2385015 │ 9091245      │ 2784916        │ 3469871           │
├─────────┼─────────┼─────────┼──────────┼─────────┼─────────┼──────────────┼─────────┼──────────────┼────────────────┼───────────────────┤
│ London  │ London  │ Vaduz   │ Adelaide │ Riyadh  │ Indiana │ Vatican City │ Paris   │ Buenos Aires │ Toronto        │ Washington        │
╘═════════╧═════════╧═════════╧══════════╧═════════╧═════════╧══════════════╧═════════╧══════════════╧════════════════╧═══════════════════╛
Name Found
Faran
4374312
London

I want it to say in the first column, the name then the phone number then the office location and finally start with the array. I don't want the phone number, office location and name to be in rows


问:
Widen a dataframe in R by adding columns based on unique values of specified column
I have the following dataframe:

```<code>> input
  Year Variable Value
1 1950   Class1     1
2 1951   Class1     2
3 1952   Class1     3
4 1950   Class2     4
5 1951   Class2     5
6 1952   Class2     6
7 1950   Class3     7
8 1951   Class3     8
9 1952   Class3     9
</code>```

I would like to create a wider dataframe that retains the "Year" column, removes the "Variable" and "Value" columns and adds columns called "Class1", "Class2" and "Class3", with values drawn from the "Value" column.  The output would look like:

```<code>> output
  Year Class1 Class2 Class3
1 1950      1      4      7
2 1951      2      5      8
3 1952      3      6      9
</code>```

I assume there is some way to use pivot_wider to do this, but I can't figure it out.  Thanks!

Body:
I have the following dataframe:

> input
  Year Variable Value
1 1950   Class1     1
2 1951   Class1     2
3 1952   Class1     3
4 1950   Class2     4
5 1951   Class2     5
6 1952   Class2     6
7 1950   Class3     7
8 1951   Class3     8
9 1952   Class3     9

I would like to create a wider dataframe that retains the "Year" column, removes the "Variable" and "Value" columns and adds columns called "Class1", "Class2" and "Class3", with values drawn from the "Value" column.  The output would look like:

> output
  Year Class1 Class2 Class3
1 1950      1      4      7
2 1951      2      5      8
3 1952      3      6      9

I assume there is some way to use pivot_wider to do this, but I can't figure it out.  Thanks!


问:
How to mark all soccer fields in flutter?
I'm a total noob with flutter and I'm trying to create an app that shows me some markers on a map pointing the location of the soccer fields and only this.
enter image description here

Currently i have the google map marks all the places nearby. I did this using the google Nearvy places API. So I need it to only mark the nearby soccer fields, but this option does not appear in the type section.

This is the code that I use to use the google api. As u seen in the url, the word soccer in type does not work.

```<code>  Future<dynamic> getPlaceDetails(LatLng coords, int radius) async {
    var lat = coords.latitude;
    var lng = coords.longitude;

    final String url =
        'https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=$lat,$lng&radius=$radius&type=soccer&key=$key';

    var response = await http.get(Uri.parse(url));

    var json = convert.jsonDecode(response.body);

    return json;
  }
</code>```

This is the method I use to mark the nearvy places

```<code>void maracaCanchas() {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(Duration(seconds: 2), () async {
      var placesResult =
          await MapServices().getPlaceDetails(tappedPoint, radiusValue.toInt());
     List<dynamic> placesWithin = placesResult['results'] as List;

    allFavoritePlaces = placesWithin;
 tokenKey = placesResult['next_page_token'] ?? 'none';

 _markers = {};

    placesWithin.forEach((element) {
        _setNearMarker(
          LatLng(element['geometry']['location']['lat'],
              element['geometry']['location']['lng']),
          element['name'],
          element['types'],
          element['business_status'] ?? 'not available',
        );
      });
      _markersDupe = _markers;
      pressedNear = true;
      _setLocationMarker();
    });
  }

</code>```

Please help me.

I am trying to mark only soccer fields on the map, but it brings me all the places

Body:
I'm a total noob with flutter and I'm trying to create an app that shows me some markers on a map pointing the location of the soccer fields and only this.
enter image description here

Currently i have the google map marks all the places nearby. I did this using the google Nearvy places API. So I need it to only mark the nearby soccer fields, but this option does not appear in the type section.

This is the code that I use to use the google api. As u seen in the url, the word soccer in type does not work.

  Future<dynamic> getPlaceDetails(LatLng coords, int radius) async {
    var lat = coords.latitude;
    var lng = coords.longitude;

    final String url =
        'https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=$lat,$lng&radius=$radius&type=soccer&key=$key';

    var response = await http.get(Uri.parse(url));

    var json = convert.jsonDecode(response.body);

    return json;
  }

This is the method I use to mark the nearvy places

void maracaCanchas() {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(Duration(seconds: 2), () async {
      var placesResult =
          await MapServices().getPlaceDetails(tappedPoint, radiusValue.toInt());
     List<dynamic> placesWithin = placesResult['results'] as List;

    allFavoritePlaces = placesWithin;
 tokenKey = placesResult['next_page_token'] ?? 'none';

 _markers = {};

    placesWithin.forEach((element) {
        _setNearMarker(
          LatLng(element['geometry']['location']['lat'],
              element['geometry']['location']['lng']),
          element['name'],
          element['types'],
          element['business_status'] ?? 'not available',
        );
      });
      _markersDupe = _markers;
      pressedNear = true;
      _setLocationMarker();
    });
  }

Please help me.

I am trying to mark only soccer fields on the map, but it brings me all the places


问:
How do I skip checkout on docker/build-push-action in GitHub actions?
The documentation is not entirely clear to me. So, let me asks this a little more explicitly:

I am modifying my source code within the GitHub Actions pipeline. Is there a way to skip the checkout for build-push-action?

The documentation clearly states: Be careful because any file mutation in the steps that precede the build step will be ignored, ... However, you can use the Path context using the context input alongside the actions/checkout action to remove this restriction.

To me that sounds if I just set

      - name: Build and push
        uses: docker/build-push-action@v3
        with:
          context: ./frontend
```

That should do exactly that, correct? However, in my case the source code will still be overwritten by an apparent checkout. What do I miss?

Body:
The documentation is not entirely clear to me. So, let me asks this a little more explicitly:

I am modifying my source code within the GitHub Actions pipeline. Is there a way to skip the checkout for build-push-action?

The documentation clearly states: Be careful because any file mutation in the steps that precede the build step will be ignored, ... However, you can use the Path context using the context input alongside the actions/checkout action to remove this restriction.

To me that sounds if I just set

      - name: Build and push
        uses: docker/build-push-action@v3
        with:
          context: ./frontend

That should do exactly that, correct? However, in my case the source code will still be overwritten by an apparent checkout. What do I miss?


问:
Opentracing proper way to inject/extract span context
I have 2 applications communicating via grps.
When I try to send a span context, I always get null in extracted.

```<code>Map<String, String> tracingMetadata = new HashMap<>();
        tracingMetadata.put("trace-id", traceId);
        tracingMetadata.put("span-id", spanId);
SpanContext extracted = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(tracingMetadata));
</code>```

Therefore, I send it via metadata in ClientIntercaptor like that.

```<code>    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
        next.newCall(method, callOptions)) {
      @Override
      public void start(Listener<RespT> responseListener, Metadata headers) {
        headers.put(Metadata.Key.of("trace-id", Metadata.ASCII_STRING_MARSHALLER), traceId);
        headers.put(Metadata.Key.of("span-id", Metadata.ASCII_STRING_MARSHALLER), spanId);
...
</code>```

When I try to create a context span from this data, it either talks about incompatible types, or context doesn't change. In pre and after equal context.

```<code>private void injectParentContext(Span span) {
    final String traceId = HeadersServerInterceptor.getTraceIdHeader();
    final String spanId = HeadersServerInterceptor.getSpanIdHeader();

    final Map<String, String> contextValues = new HashMap<>();
    contextValues.put("x-b3-trace-id", traceId);
    contextValues.put("x-b3-spanid", spanId);

    final SpanContext pre=span.context();

    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMapAdapter(contextValues));

    final SpanContext after=  span.context();
  }
</code>```

I tried different Format.Builtin and Adapter, nothing works.

What am I doing wrong?

Body:
I have 2 applications communicating via grps.
When I try to send a span context, I always get null in extracted.

Map<String, String> tracingMetadata = new HashMap<>();
        tracingMetadata.put("trace-id", traceId);
        tracingMetadata.put("span-id", spanId);
SpanContext extracted = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(tracingMetadata));

Therefore, I send it via metadata in ClientIntercaptor like that.

    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
        next.newCall(method, callOptions)) {
      @Override
      public void start(Listener<RespT> responseListener, Metadata headers) {
        headers.put(Metadata.Key.of("trace-id", Metadata.ASCII_STRING_MARSHALLER), traceId);
        headers.put(Metadata.Key.of("span-id", Metadata.ASCII_STRING_MARSHALLER), spanId);
...

When I try to create a context span from this data, it either talks about incompatible types, or context doesn't change. In pre and after equal context.

private void injectParentContext(Span span) {
    final String traceId = HeadersServerInterceptor.getTraceIdHeader();
    final String spanId = HeadersServerInterceptor.getSpanIdHeader();

    final Map<String, String> contextValues = new HashMap<>();
    contextValues.put("x-b3-trace-id", traceId);
    contextValues.put("x-b3-spanid", spanId);

    final SpanContext pre=span.context();

    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMapAdapter(contextValues));

    final SpanContext after=  span.context();
  }

I tried different Format.Builtin and Adapter, nothing works.

What am I doing wrong?


问:
Insert a component between the search box and the drop down menu in AutoComplete (antd)
I am doing a component that will have some options that are being laid between the seach box and the drop down menu.

For now I have done this:

```<code>export default function SearchBoxEvents() {
    const [options, setOptions] = useState<
    { value: string; label: JSX.Element }[]
    >([]);
    const handleSearch = (input: string) => {
        let res: { value: string; label: JSX.Element }[] = [];
        if (!input) {
            res = [];
        } else {
            //this is just a placeholder
            res = ["event 1", "event 2", "event 3"]
            .filter((event) => true)
            .map((event) => ({
                value: event,
                label: <span>Some icon {event}</span>
            }));
        }
        setOptions(res);
    };
    return (
        <AutoComplete
        onSearch={handleSearch}
        options={options}
        >
                <Input.Search size="large" placeholder="to be replaced" />
                <p>
                    "example text"
                </p>
        </AutoComplete>
    );
}
</code>```

This is resulting in this

But imagine I want to add some text, for example "example text" between the search box and the drop down, if I do this

```<code>return (
    <AutoComplete
    onSearch={handleSearch}
    options={options}
    >
            <Input.Search size="large" placeholder="to be replaced" />
            <p>
                "example text"
            </p>
    </AutoComplete>
);
</code>```

Then it breaks :c . Does somebody knows how to add text ( not a place holder, additional text)

Body:
I am doing a component that will have some options that are being laid between the seach box and the drop down menu.

For now I have done this:

export default function SearchBoxEvents() {
    const [options, setOptions] = useState<
    { value: string; label: JSX.Element }[]
    >([]);
    const handleSearch = (input: string) => {
        let res: { value: string; label: JSX.Element }[] = [];
        if (!input) {
            res = [];
        } else {
            //this is just a placeholder
            res = ["event 1", "event 2", "event 3"]
            .filter((event) => true)
            .map((event) => ({
                value: event,
                label: Some icon {event}
            }));
        }
        setOptions(res);
    };
    return (
        <AutoComplete
        onSearch={handleSearch}
        options={options}
        >
                <Input.Search size="large" placeholder="to be replaced" />

                    "example text"

        </AutoComplete>
    );
}

This is resulting in this

But imagine I want to add some text, for example "example text" between the search box and the drop down, if I do this

return (
    <AutoComplete
    onSearch={handleSearch}
    options={options}
    >
            <Input.Search size="large" placeholder="to be replaced" />

                "example text"

    </AutoComplete>
);

Then it breaks :c . Does somebody knows how to add text ( not a place holder, additional text)


问:
How to read the ms-Exch-Mailbox-Security-Descriptor frm each Exchange Mailbox
When doing O365 migrations, part of the 'Planning' session includes an analysis of how users Share and give access to each others calendars and folders. I have this Function wrapped inside a ForEach loop which gets those permissions via native Exchange PS cmdlets:

```<code>Function Pull-MBXFolderPerms {
Param ([string]$MBXName)
    Start-Sleep -Milliseconds 600
        $Mailbox = '' + $MBXName
        $Folders = Get-MailboxFolderStatistics $Mailbox | % {$_.folderpath} | % {$_.replace("/","\")}
        Write-host "Processing folders on mailbox $Mailbox"

ForEach ($Fold in $Folders) {
            $FolderKey = $Mailbox + ":" + $Fold
            $Permissions = Get-MailboxFolderPermission -identity $FolderKey -ErrorAction silentlycontinue
            $FolderPerms += $Permissions | ? {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights -notlike "Owner" } | Select-Object @{name='Mailbox';expression={$MBXName}},FolderName,@{name='UserWithAccess';expression={$_.User -join ','}},@{name='AccessRights';expression={$_.AccessRights -join ','}}
}
    Return $FolderPerms
}
</code>```

When doing this in bulk it takes days to complete in a large environment because there is an LDAP lookup on EACH ACE on every folder so that the User's Displayname can be shown in the results.

In order to speed this process up, I want to record the Security Descriptor off of the folder in its SDDL format to bypass the lookup on each ACE. I can then do th lookup later in bulk rather than opening and closing an LDAP session on each ACE

This code can be used to 'Loop' through ACEs for file systems:

```<code>$addACL=[System.Security.AccessControl.DirectorySecurity]::new($Fold,'Access')).GetSecurityDescriptorSddlForm(('Access'))
    # Remove leading and trailing parenthesis from ACLs
        $splitFirst = $addACL.split("(")
        $splitDone = $splitFirst.TrimEnd(")")
    # Filter for explicit permissions and remove implicit deny from each ACL
    ForEach ($ACE in $splitDone) {
        If ($ACE.Contains("ID")) {
                continue
        }
    ElseIf ($FinalACE = $ACE | where {$ACE -notlike 'D:AI' -and $ACE -notlike 'D:PAI'}) {

        $Script:ACLOutput += New-Object PSObject -Property @{

        FullName = $Fold
        sddlACE = $FinalACE
        }
    }
}
</code>```

I am looking for a similar way of doing this with Exchange Mailbox folders and am at a loss as to how to get to the SDDL. We would also like to do this natively without using MFCMAPI

Any help would be appreciated!

Body:
When doing O365 migrations, part of the 'Planning' session includes an analysis of how users Share and give access to each others calendars and folders. I have this Function wrapped inside a ForEach loop which gets those permissions via native Exchange PS cmdlets:

Function Pull-MBXFolderPerms {
Param ([string]$MBXName)
    Start-Sleep -Milliseconds 600
        $Mailbox = '' + $MBXName
        $Folders = Get-MailboxFolderStatistics $Mailbox | % {$_.folderpath} | % {$_.replace("/","\")}
        Write-host "Processing folders on mailbox $Mailbox"

ForEach ($Fold in $Folders) {
            $FolderKey = $Mailbox + ":" + $Fold
            $Permissions = Get-MailboxFolderPermission -identity $FolderKey -ErrorAction silentlycontinue
            $FolderPerms += $Permissions | ? {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights -notlike "Owner" } | Select-Object @{name='Mailbox';expression={$MBXName}},FolderName,@{name='UserWithAccess';expression={$_.User -join ','}},@{name='AccessRights';expression={$_.AccessRights -join ','}}
}
    Return $FolderPerms
}

When doing this in bulk it takes days to complete in a large environment because there is an LDAP lookup on EACH ACE on every folder so that the User's Displayname can be shown in the results.

In order to speed this process up, I want to record the Security Descriptor off of the folder in its SDDL format to bypass the lookup on each ACE. I can then do th lookup later in bulk rather than opening and closing an LDAP session on each ACE

This code can be used to 'Loop' through ACEs for file systems:

$addACL=[System.Security.AccessControl.DirectorySecurity]::new($Fold,'Access')).GetSecurityDescriptorSddlForm(('Access'))
    # Remove leading and trailing parenthesis from ACLs
        $splitFirst = $addACL.split("(")
        $splitDone = $splitFirst.TrimEnd(")")
    # Filter for explicit permissions and remove implicit deny from each ACL
    ForEach ($ACE in $splitDone) {
        If ($ACE.Contains("ID")) {
                continue
        }
    ElseIf ($FinalACE = $ACE | where {$ACE -notlike 'D:AI' -and $ACE -notlike 'D:PAI'}) {

        $Script:ACLOutput += New-Object PSObject -Property @{

        FullName = $Fold
        sddlACE = $FinalACE
        }
    }
}

I am looking for a similar way of doing this with Exchange Mailbox folders and am at a loss as to how to get to the SDDL. We would also like to do this natively without using MFCMAPI

Any help would be appreciated!


问:
assets_audio_player, not working set volume
Not working set volume in this plugin.
https://pub.dev/packages/assets_audio_player

```<code>assetsAudioPlayer.setVolume(0.5);
</code>```
```<code>StreamBuilder(
    stream: assetsAudioPlayer.volume,
    builder: (context, asyncSnapshot) {
      volume = asyncSnapshot.data;
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextButton(
                onPressed: () async {
                  await assetsAudioPlayer.setVolume(0.5);
                  debugPrint('vol $volume');
                },
                child: Text('Change volume')),
            Text("volume : $volume"),
          ],
        ),
      );
    });
</code>```
```<code>StreamBuilder(
    stream: assetsAudioPlayer.volume,
    builder: (context, asyncSnapshot) {
      volume = asyncSnapshot.data;
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextButton(
                onPressed: () async {
                  await assetsAudioPlayer.setVolume(0.4);
                  debugPrint('vol $volume');
                },
                child: Text('Change volume')),
            Text("volume : $volume"),
          ],
        ),
      );
    });
</code>```

Body:
Not working set volume in this plugin.
https://pub.dev/packages/assets_audio_player

assetsAudioPlayer.setVolume(0.5);

StreamBuilder(
    stream: assetsAudioPlayer.volume,
    builder: (context, asyncSnapshot) {
      volume = asyncSnapshot.data;
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextButton(
                onPressed: () async {
                  await assetsAudioPlayer.setVolume(0.5);
                  debugPrint('vol $volume');
                },
                child: Text('Change volume')),
            Text("volume : $volume"),
          ],
        ),
      );
    });

StreamBuilder(
    stream: assetsAudioPlayer.volume,
    builder: (context, asyncSnapshot) {
      volume = asyncSnapshot.data;
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextButton(
                onPressed: () async {
                  await assetsAudioPlayer.setVolume(0.4);
                  debugPrint('vol $volume');
                },
                child: Text('Change volume')),
            Text("volume : $volume"),
          ],
        ),
      );
    });


问:
Only one axis is displayed in the graph
Want to visualise coordinates from csv file by a heatmap, but only one axis is displayed in the graph and nothing else as the  picture shows:
enter image description here

This is the code:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use('TkAgg')

data = np.genfromtxt("plik.csv", delimiter=";", dtype = float)

np.reshape(data, (-1, 2))
print(data.shape)

plt.imshow(data, cmap='hot')
plt.show()
</code>```

And data in the file is displayed like this:

```<code>0.000000; 0.045761
0.000000; 0.016499
0.000013; 0.010060
0.013995; 0.065568
0.014008; 0.060024
0.007376; 0.066706
0.020661; 0.062069
0.019254; 0.060543
0.028329; 0.079392
0.021810; 0.058398
0.025076; 0.067873
0.068878; 0.120970
</code>```

There are 9585 lines in the file.

Title: Only one axis is displayed in the graph

Body:
Want to visualise coordinates from csv file by a heatmap, but only one axis is displayed in the graph and nothing else as the  picture shows:
enter image description here

This is the code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use('TkAgg')

data = np.genfromtxt("plik.csv", delimiter=";", dtype = float)

np.reshape(data, (-1, 2))
print(data.shape)

plt.imshow(data, cmap='hot')
plt.show()

And data in the file is displayed like this:

0.000000; 0.045761
0.000000; 0.016499
0.000013; 0.010060
0.013995; 0.065568
0.014008; 0.060024
0.007376; 0.066706
0.020661; 0.062069
0.019254; 0.060543
0.028329; 0.079392
0.021810; 0.058398
0.025076; 0.067873
0.068878; 0.120970

There are 9585 lines in the file.


问:
Why does my cursor teleport while looping Robot mousePress() and mouseRelease()?
Update: it seems like this issue only affects macOS users.

I'm making an auto clicker program. I'm using a while loop that spams left click whenever the auto clicker is enabled. However, after the auto clicker clicks the first time, every subsequent click snaps to the original click location (even though I never used the mouseMove() method). I've taken a look at other auto clicker implementations and can't see why mine would result in this issue.

I reproduced the issue with the following simple code:

```<code>import java.awt.*;
import java.awt.event.InputEvent;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Robot robot;
        try {
            robot = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
        Thread.sleep(5000);
        for(int i = 0; i < 20; i++){
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            Thread.sleep(100);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            Thread.sleep(100);
        }
    }
}
</code>```

Body:
Update: it seems like this issue only affects macOS users.

I'm making an auto clicker program. I'm using a while loop that spams left click whenever the auto clicker is enabled. However, after the auto clicker clicks the first time, every subsequent click snaps to the original click location (even though I never used the mouseMove() method). I've taken a look at other auto clicker implementations and can't see why mine would result in this issue.

I reproduced the issue with the following simple code:

import java.awt.*;
import java.awt.event.InputEvent;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Robot robot;
        try {
            robot = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
        Thread.sleep(5000);
        for(int i = 0; i < 20; i++){
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            Thread.sleep(100);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            Thread.sleep(100);
        }
    }
}


问:
MySQL deadlock error while updating within a loop
I have the following piece of code updating records in a loop:

```<code>    if connection is not None:
        with connection.cursor() as cursor:
            for instrument in instruments:
                instrument_name = instrument[0]
                price = instrument[2]
                price = instrument_name.split('-')[2]
                type = instrument_name.split('-')[3]

                if option_type == 'P' and float(strike) > price:
                    label = 'ABC'
                elif option_type == 'P' and float(strike) < price:
                    label = 'NRU'
                elif option_type == 'C' and float(strike) > price:
                    label = 'NRU'
                elif option_type == 'C' and float(strike) < price:
                    label = 'ABC'
                print('Assigning for the Instrument = ', instrument_name)
                sql = 'UPDATE {} set price =%s, label=%s WHERE instrument_name=%s'.format(table_name)
                cursor.execute(sql, (price, label, instrument_name,))
                connection.commit()
</code>```

Which is giving error Deadlock found when trying to get lock; try restarting transaction at the line cursor.execute(sql, (price, label, instrument_name,))

It does not give error when running a single instance of script, it gives error when I am running multiple instances like python file.py 1, python file.py 2 etc... which I guess is locking due to once of the scripts already has a hold of the certain table.

my question is, how do I tackle this because I have to run multiple instances anyway, should I separate tables or some other hack?

Body:
I have the following piece of code updating records in a loop:

    if connection is not None:
        with connection.cursor() as cursor:
            for instrument in instruments:
                instrument_name = instrument[0]
                price = instrument[2]
                price = instrument_name.split('-')[2]
                type = instrument_name.split('-')[3]

                if option_type == 'P' and float(strike) > price:
                    label = 'ABC'
                elif option_type == 'P' and float(strike) < price:
                    label = 'NRU'
                elif option_type == 'C' and float(strike) > price:
                    label = 'NRU'
                elif option_type == 'C' and float(strike) < price:
                    label = 'ABC'
                print('Assigning for the Instrument = ', instrument_name)
                sql = 'UPDATE {} set price =%s, label=%s WHERE instrument_name=%s'.format(table_name)
                cursor.execute(sql, (price, label, instrument_name,))
                connection.commit()

Which is giving error Deadlock found when trying to get lock; try restarting transaction at the line cursor.execute(sql, (price, label, instrument_name,))

It does not give error when running a single instance of script, it gives error when I am running multiple instances like python file.py 1, python file.py 2 etc... which I guess is locking due to once of the scripts already has a hold of the certain table.

my question is, how do I tackle this because I have to run multiple instances anyway, should I separate tables or some other hack?


问:
Pubnub receiving duplicate messages in one channel, but not in another channel
Business Code:

```<code>const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Pubnub_A />
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
       <Pubnub_B />
       ......
    </>
  );
</code>```

Pubnub_A:

```<code>export default function Pubnub_A(): null {
  pubNubSub({
    namespace: "test_A",
    namespaceId: "test_namespaceId",
    event: "DONE",
    callback: () => {
      console.log('Pubnub_A')
    },
  });
  return null;
}
</code>```

Pubnub_B:

```<code>export default function Pubnub_B(): null {
  pubNubSub({
    namespace: "test_B",
    namespaceId: "test_namespaceId",
    event: "DONE",
    callback: () => {
      console.log('Pubnub_B')
    },
  });
  return null;
}
</code>```

pubNubSub:

```<code>export type Sub = {
  namespace: string,
  namespaceId?: ?string,
  event?: ?string,
  callback: EventCallback,
};

export default function pubNubSub(
  sub: Sub
) {
  const subs = useMemo(() => [sub], [sub]);

  const {client} = useContext(PubNubContext);

  useEffect(() => {
      const ids = subs.map(sub =>
        {
          return client.subscribe(
          {
            namespace: sub.namespace,
            namespaceId: sub.namespaceId,
            event: sub.event,
          },
          sub.callback
        )
        }
      );
      return function clear() {
        ids.forEach(id => {
          client.unsubscribe(id);
        });
      };
  }, [subs, client]);
}
</code>```

In Business Code, Pubnub_A receives one message, but Pubnub_B receives duplicate message when I refresh the page.
If I put Pubnub_A and Pubnub_B together, like:

```<code>const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Pubnub_A />
      <Pubnub_B />
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
       ......
    </>
  );
</code>```

or

```<code>const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
      <Pubnub_A />
      <Pubnub_B />
       ......
    </>
  );
</code>```

Both Pubnub_A and Pubnub_B receive one message.

If I delete Pubnub_A in origin Business Code, Pubnub_B receive one message.

It seems that Pubnub_A and Pubnub_B can't be in different components. Or the later will receive duplicate messages.

I want to know why it happens and how to make Pubnub_A and Pubnub_B receive one message in origin code. Thanks!

Body:
Business Code:

const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Pubnub_A />
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
       <Pubnub_B />
       ......
    </>
  );

Pubnub_A:

export default function Pubnub_A(): null {
  pubNubSub({
    namespace: "test_A",
    namespaceId: "test_namespaceId",
    event: "DONE",
    callback: () => {
      console.log('Pubnub_A')
    },
  });
  return null;
}

Pubnub_B:

export default function Pubnub_B(): null {
  pubNubSub({
    namespace: "test_B",
    namespaceId: "test_namespaceId",
    event: "DONE",
    callback: () => {
      console.log('Pubnub_B')
    },
  });
  return null;
}

pubNubSub:

export type Sub = {
  namespace: string,
  namespaceId?: ?string,
  event?: ?string,
  callback: EventCallback,
};

export default function pubNubSub(
  sub: Sub
) {
  const subs = useMemo(() => [sub], [sub]);

  const {client} = useContext(PubNubContext);

  useEffect(() => {
      const ids = subs.map(sub =>
        {
          return client.subscribe(
          {
            namespace: sub.namespace,
            namespaceId: sub.namespaceId,
            event: sub.event,
          },
          sub.callback
        )
        }
      );
      return function clear() {
        ids.forEach(id => {
          client.unsubscribe(id);
        });
      };
  }, [subs, client]);
}

In Business Code, Pubnub_A receives one message, but Pubnub_B receives duplicate message when I refresh the page.
If I put Pubnub_A and Pubnub_B together, like:

const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Pubnub_A />
      <Pubnub_B />
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
       ......
    </>
  );

or

const NodeDetails = (): React.Node => {
  ......
  return (
    <Suspense fallback={<Loader loaded={false} />}>
      <Content
        ......
      />
    </Suspense>
  );

function Content(): React.Node {
  ......
  return (
    <>
      <Pubnub_A />
      <Pubnub_B />
       ......
    </>
  );

Both Pubnub_A and Pubnub_B receive one message.

If I delete Pubnub_A in origin Business Code, Pubnub_B receive one message.

It seems that Pubnub_A and Pubnub_B can't be in different components. Or the later will receive duplicate messages.

I want to know why it happens and how to make Pubnub_A and Pubnub_B receive one message in origin code. Thanks!


问:
Resolution of Microsoft.Net.Http.Headers assembly version 2.2.0 versus 6.0.0 depends on seemingly unrelated package references
While trying to use HeaderNames.XFrameOptions, I found that it works in one of my projects and fails in another. Both are targeting .NET 6.

In my app, I need to work with the X-Frame-Options HTTP header. When possible, for maintainability reasons, I try to evade specifying constants for such standard strings myself, relying on standard constants instead. For this header's name, there is HeaderNames.XFrameOptions, available since ASP.NET Core 3.0.

By navigating to the class's implementation in VS, I found that the project where it works uses version 6.0.0.0 (.NET 6, x64) of the Microsoft.Net.Http.Headers assembly:

C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\6.0.12\Microsoft.Net.Http.Headers.dll

The project where it does not work uses version 2.2.0.0 (.NET Standard 2.0, MSIL) of the assembly:

C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.net.http.headers\2.2.0\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll

The working project is the main project of my console app and the broken project is a library in the same solution, directly referenced by the console app.

When I looked into the broken project's obj\project.assets.json, I found that Microsoft.Net.Http.Headers is really used in version 2.2.0 and it is referenced by Microsoft.AspNetCore.Http.Extensions/2.2.0, which is also used in the broken project.

I used that info to reproduce the failure:

```<code>dotnet new globaljson --sdk-version 6.0.404 --roll-forward disable
dotnet new console -f net6.0
dotnet add package Microsoft.AspNetCore.Http.Extensions --version 2.2.0
echo "Console.WriteLine(Microsoft.Net.Http.Headers.HeaderNames.XFrameOptions);" > Program.cs
dotnet run
</code>```

C:\Repos\playground\Program.cs(1,58): error CS0117: 'HeaderNames' does not contain a definition for 'XFrameOptions' [C:\Repos\playground\playground.csproj]

The build failed. Fix the build errors and run again.

I tried adding all the packages referenced by the working project to the repro project and it fixed it! By elimination and following the dependencies of the last remaining project, I found that the fix can be achieved by adding just a single package (AspNetCore.HealthChecks.UI.Client/6.0.5):

```<code>dotnet add package AspNetCore.HealthChecks.UI.Client --version 6.0.5
dotnet run
</code>```

X-Frame-Options

I see that AspNetCore.HealthChecks.UI.Client references the Microsoft.Net.Http.Headers assembly version 6.0.0.0, but directly, as an assembly, not as a NuGet package. Sadly, the latest packaged version is 2.2.0.0.

How can I make HeaderNames.XFrameOptions work in both my projects at the same time? Is installing an irrelevant package like AspNetCore.HealthChecks.UI.Client the only solution? And is there a more straightforward way to diagnose such assembly resolution issues?

Body:
While trying to use HeaderNames.XFrameOptions, I found that it works in one of my projects and fails in another. Both are targeting .NET 6.

In my app, I need to work with the X-Frame-Options HTTP header. When possible, for maintainability reasons, I try to evade specifying constants for such standard strings myself, relying on standard constants instead. For this header's name, there is HeaderNames.XFrameOptions, available since ASP.NET Core 3.0.

By navigating to the class's implementation in VS, I found that the project where it works uses version 6.0.0.0 (.NET 6, x64) of the Microsoft.Net.Http.Headers assembly:

C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\6.0.12\Microsoft.Net.Http.Headers.dll

The project where it does not work uses version 2.2.0.0 (.NET Standard 2.0, MSIL) of the assembly:

C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.net.http.headers\2.2.0\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll

The working project is the main project of my console app and the broken project is a library in the same solution, directly referenced by the console app.

When I looked into the broken project's obj\project.assets.json, I found that Microsoft.Net.Http.Headers is really used in version 2.2.0 and it is referenced by Microsoft.AspNetCore.Http.Extensions/2.2.0, which is also used in the broken project.

I used that info to reproduce the failure:

dotnet new globaljson --sdk-version 6.0.404 --roll-forward disable
dotnet new console -f net6.0
dotnet add package Microsoft.AspNetCore.Http.Extensions --version 2.2.0
echo "Console.WriteLine(Microsoft.Net.Http.Headers.HeaderNames.XFrameOptions);" > Program.cs
dotnet run

C:\Repos\playground\Program.cs(1,58): error CS0117: 'HeaderNames' does not contain a definition for 'XFrameOptions' [C:\Repos\playground\playground.csproj]

The build failed. Fix the build errors and run again.

I tried adding all the packages referenced by the working project to the repro project and it fixed it! By elimination and following the dependencies of the last remaining project, I found that the fix can be achieved by adding just a single package (AspNetCore.HealthChecks.UI.Client/6.0.5):

dotnet add package AspNetCore.HealthChecks.UI.Client --version 6.0.5
dotnet run

X-Frame-Options

I see that AspNetCore.HealthChecks.UI.Client references the Microsoft.Net.Http.Headers assembly version 6.0.0.0, but directly, as an assembly, not as a NuGet package. Sadly, the latest packaged version is 2.2.0.0.

How can I make HeaderNames.XFrameOptions work in both my projects at the same time? Is installing an irrelevant package like AspNetCore.HealthChecks.UI.Client the only solution? And is there a more straightforward way to diagnose such assembly resolution issues?


问:
Google Calendar
Is there a way to create a privilege setting in a shared calendar so that people can only add events & modify the ones they are "owners" of? We have a shared events company calendar that everyone can include events on, but sometimes they accidentally get deleted. I want to promote the shared collaboration and still allow everyone to add to it, but I'm hoping for something inbetween "Modify all events" and "see details only"

I tried to modify the privileges to "see details only" but then people couldn't contribute it the calendar.

Title: Google Calendar


问:
Can we do sort-by on the values of 100TB data in Spark
If we have 100TB of data, can we do sort-by/order-by in Apache Spark on the values of 100TB data.

I guess this will affect the performance of the job but how to perform it in optimized way without affecting performance. What are the possible optimizations to follow to perform sort-by/order-by


问:
Cant import nbconvert library in Jupyter Notebook
I’m using assistant-dialog-skill-analysis 1.2.1 version but I get the next error when import skills_util from assistant_dialog_skill_analysis.utils:
ModuleNotFoundError: No module named 'nbconvert'

I tried to install nbconvert manually and works but I get the same issue when I want import the library:
pip install nbconvert
import nbconvert

And the error: ModuleNotFoundError: No module named 'nbconvert'


问:
Do actions in python dependant on whether domain is pointing to X
I'm not very good at programming but what I'd like to do is have a Python script that would do certain actions depending on whether a domain has its nameservers pointed to X or whether it has a CNAME record pointed to X specific IP.

So basically:
if domain has CNAME pointed to X do Y
if domain has nameservers pointed to X1 and X2 do Z.

Does anyone know how that could be done?

EDIT:
I've tried the following (with proper tabs of course) only the result is always 'No' even though the CNAME does point to what I've set. I'm probably misunderstanding something somewhere.

```<code>domain = 'example.com'
answers = dns.resolver.resolve(domain,'CNAME')
for server in answers:
print(server.target)
if server.target == 'xdomain.org':
print("Yes")
else:
print("No")
</code>```

Body:
I'm not very good at programming but what I'd like to do is have a Python script that would do certain actions depending on whether a domain has its nameservers pointed to X or whether it has a CNAME record pointed to X specific IP.

So basically:
if domain has CNAME pointed to X do Y
if domain has nameservers pointed to X1 and X2 do Z.

Does anyone know how that could be done?

EDIT:
I've tried the following (with proper tabs of course) only the result is always 'No' even though the CNAME does point to what I've set. I'm probably misunderstanding something somewhere.

domain = 'example.com'
answers = dns.resolver.resolve(domain,'CNAME')
for server in answers:
print(server.target)
if server.target == 'xdomain.org':
print("Yes")
else:
print("No")


问:
Change color of the node in Pyvis Network when it gets clicked on
I'm creating a network visualization in python using Pyvis. I can create the graph as I want with no problem, but when I run my script and get the html file as output, I want the nodes to change colors when I click on them and I can't achieve that. I've tried a lot of things and nothing seems to work. The data I'm using has the following structure but with a lot more nodes than this:

```<code>import pandas as pd
from pyvis.network import Network

data = [['A','B', 1], ['A','C', 4], ['B','A', 1],
        ['D','E', 5], ['D','F', 1], ['G','J', 7],
        ['A','J', 4], ['G','F', 14], ['C','L', 4],
        ['A','F', 2], ['E','H', 12], ['I','E', 2],
        ['I','K', 4], ['L','H', 21]]

df = pd.DataFrame(data, columns=['source', 'target', 'feature_count']

# Step 1: Initialize Network
graph = Network(height='750px', width='100%', directed=True)

# Step 2: Get sources, targets and weights
sources = df['source']
targets = df['targets']
weights = df['feature_count']

edge_data = zip(sources, targets, weights)

# Step 3: Create the graph adding each node individually.
for edge in edge_data:
    source_name = edge[0]
    target_name = edge[1]
    weight = edge[2]

    graph.add_node(n_id=source_name, label=source_name, labelHighlightBold=True)
    graph.add_node(n_id=target_name, label=target_name, labelHighlightBold=True)
    graph.add_edge(source_name, target_name, value=weight, title=weight, arrowStrikethrough=False)

# Step 4: Use the Json Dictionary that sets the options to specify that I want the color of the node to change to red when clicked on
options = {
    "configure": {
         "enabled": True
     },
    "interaction": {
        "hover": True
    },
    "nodes": {
         "borderWidth": 2,
         "borderWidthSelected": 4,
         "chosen" : True,
         "color": { "highlight": { "border": "#FF4040",
                                   "background": "#EE3B3B"
                     },
                    "hover": { "border": "#DEB887",
                               "background": "#FFD39B"
                     }
         }
     }
}

# Step 5: Define the options
graph.options = options

# Step 6: Visualize the Network
graph.show('graph.html')
</code>```

For some reason this doesn't work. I've been searching for other possible solutions and I can't find them. It seems that the only thing left would be to create a function In Java that makes this and pass it to the html code. The thing is I don't know Java and I'm afraid to spend a lot of time trying that without getting to a solution or having another solution more quickly.

Any ideas ?

Thanks!

Body:
I'm creating a network visualization in python using Pyvis. I can create the graph as I want with no problem, but when I run my script and get the html file as output, I want the nodes to change colors when I click on them and I can't achieve that. I've tried a lot of things and nothing seems to work. The data I'm using has the following structure but with a lot more nodes than this:

import pandas as pd
from pyvis.network import Network

data = [['A','B', 1], ['A','C', 4], ['B','A', 1],
        ['D','E', 5], ['D','F', 1], ['G','J', 7],
        ['A','J', 4], ['G','F', 14], ['C','L', 4],
        ['A','F', 2], ['E','H', 12], ['I','E', 2],
        ['I','K', 4], ['L','H', 21]]

df = pd.DataFrame(data, columns=['source', 'target', 'feature_count']

# Step 1: Initialize Network
graph = Network(height='750px', width='100%', directed=True)

# Step 2: Get sources, targets and weights
sources = df['source']
targets = df['targets']
weights = df['feature_count']

edge_data = zip(sources, targets, weights)

# Step 3: Create the graph adding each node individually.
for edge in edge_data:
    source_name = edge[0]
    target_name = edge[1]
    weight = edge[2]

    graph.add_node(n_id=source_name, label=source_name, labelHighlightBold=True)
    graph.add_node(n_id=target_name, label=target_name, labelHighlightBold=True)
    graph.add_edge(source_name, target_name, value=weight, title=weight, arrowStrikethrough=False)

# Step 4: Use the Json Dictionary that sets the options to specify that I want the color of the node to change to red when clicked on
options = {
    "configure": {
         "enabled": True
     },
    "interaction": {
        "hover": True
    },
    "nodes": {
         "borderWidth": 2,
         "borderWidthSelected": 4,
         "chosen" : True,
         "color": { "highlight": { "border": "#FF4040",
                                   "background": "#EE3B3B"
                     },
                    "hover": { "border": "#DEB887",
                               "background": "#FFD39B"
                     }
         }
     }
}

# Step 5: Define the options
graph.options = options

# Step 6: Visualize the Network
graph.show('graph.html')

For some reason this doesn't work. I've been searching for other possible solutions and I can't find them. It seems that the only thing left would be to create a function In Java that makes this and pass it to the html code. The thing is I don't know Java and I'm afraid to spend a lot of time trying that without getting to a solution or having another solution more quickly.

Any ideas ?

Thanks!


问:
Django VSCode debugging going wrong
I'm studing some Django, mainly DRF, but some times what i do goes different of what my instructor does. Actually, i'm now facing a problem when I try to debug my code with the VSCode debugger, as he does in the classes, where, when he starts the application with the debugger, it starts normally, but when he makes a requests that passes by a certain view or serializer, the application stops at the breakpoint and wait his commands, like a normal debug. When I try the same, as the application starts, it first stops at the breakpoints, while Django is performing the system checks, and then does not stops when the request passes by the view, for example. The only step he made to configure the debugger was creating the launch.json file the VSCode recommends, here is an example of mine:

```<code>{
    // Use o IntelliSense para saber mais sobre os atributos possíveis.
    // Focalizar para exibir as descrições dos atributos existentes.
    // Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "program": "${workspaceFolder}\\src\\manage.py",
            "args": [
                "runserver",
            ],
            "django": true,
            "justMyCode": false
        }
    ],
}
</code>```

with these settings, the application starts, stops at the breakpoints when checking system, and then does not stops anymore, as i said above. Probably it's a dumb question, but what's wrong? here's an example of what happens when it starts:
enter image description here

The only thing I tryed was to add the

```<code>"stopOnEntry": false,
</code>```

at the launch.json, but it did nothing

Title: Django VSCode debugging going wrong

Body:
I'm studing some Django, mainly DRF, but some times what i do goes different of what my instructor does. Actually, i'm now facing a problem when I try to debug my code with the VSCode debugger, as he does in the classes, where, when he starts the application with the debugger, it starts normally, but when he makes a requests that passes by a certain view or serializer, the application stops at the breakpoint and wait his commands, like a normal debug. When I try the same, as the application starts, it first stops at the breakpoints, while Django is performing the system checks, and then does not stops when the request passes by the view, for example. The only step he made to configure the debugger was creating the launch.json file the VSCode recommends, here is an example of mine:

{
    // Use o IntelliSense para saber mais sobre os atributos possíveis.
    // Focalizar para exibir as descrições dos atributos existentes.
    // Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "program": "${workspaceFolder}\\src\\manage.py",
            "args": [
                "runserver",
            ],
            "django": true,
            "justMyCode": false
        }
    ],
}

with these settings, the application starts, stops at the breakpoints when checking system, and then does not stops anymore, as i said above. Probably it's a dumb question, but what's wrong? here's an example of what happens when it starts:
enter image description here

The only thing I tryed was to add the

"stopOnEntry": false,

at the launch.json, but it did nothing


问:
Launching spring-boot with some properties set
This is probably pretty basic but...

I have had this working in the past, but have completely forgotten how now.
In my code I have several lines like this:
data.setAuthURL(System.getProperty("catalystTokenServerUrl"));

On the Jboss server we set properties in the console.

How do I set these in Eclipse so when I launch my service from the boot dashboard, they are available?