问:
Problem with labeling contour line with tricontourf() in matplotlib python
I plot two contour graph in a figure with help of matplotlib library. When I try to add contour label in each line, I get a messed up graph like this: Messed up contour graph
Here is my code:

```<code>import matplotlib.pyplot as plt
import DataImportingContour as d
import matplotlib.cm as cm

def graphing_contour():
    fig, (ax1, ax2) = plt.subplots(2)
    #fig.set_size_inches(8, 5, forward=True)
    level_wallA = list(range(5, 44, 5))
    print(level_wallA)

    ax1.set_xticks(range(-5, 6))
    ax1.set_yticks([0.5, 1])
    ax1.set(xlabel='y/H', ylabel='z/H')
    ax1.set_title('Wall A')

    ax2.set_xticks(range(-5, 6))
    ax2.set_yticks([0.5, 1])
    ax2.set(xlabel='y/H', ylabel='z/H')
    ax2.set_title('Wall B')

    cs1 = ax1.tricontourf(d.dict['x0_list'], d.dict['y0_list'], d.dict['z0_list'], cmap=cm.YlOrBr, levels=8)
    cs2 = ax2.tricontourf(d.dict['x1_list'], d.dict['y1_list'], d.dict['z1_list'], cmap=cm.YlOrBr, levels=4)

    ax1.clabel(cs1, levels= level_wallA, inline=True)
    ax2.clabel(cs2, inline=True)

    fig.savefig('test.jpg')

if __name__ == "__main__":
    graphing_contour()
</code>```

I set cs1 and cs2 to ax1.tricontourf and ax2.tricontourf to get the parameter CS in clabel() in the guide of matplotlib: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.clabel.html#matplotlib.axes.Axes.clabel
For the result I do get the contour line label, but the graph is somewhat messed up and also the label is not clearly show.

Body:
I plot two contour graph in a figure with help of matplotlib library. When I try to add contour label in each line, I get a messed up graph like this: Messed up contour graph
Here is my code:

import matplotlib.pyplot as plt
import DataImportingContour as d
import matplotlib.cm as cm

def graphing_contour():
    fig, (ax1, ax2) = plt.subplots(2)
    #fig.set_size_inches(8, 5, forward=True)
    level_wallA = list(range(5, 44, 5))
    print(level_wallA)

    ax1.set_xticks(range(-5, 6))
    ax1.set_yticks([0.5, 1])
    ax1.set(xlabel='y/H', ylabel='z/H')
    ax1.set_title('Wall A')

    ax2.set_xticks(range(-5, 6))
    ax2.set_yticks([0.5, 1])
    ax2.set(xlabel='y/H', ylabel='z/H')
    ax2.set_title('Wall B')

    cs1 = ax1.tricontourf(d.dict['x0_list'], d.dict['y0_list'], d.dict['z0_list'], cmap=cm.YlOrBr, levels=8)
    cs2 = ax2.tricontourf(d.dict['x1_list'], d.dict['y1_list'], d.dict['z1_list'], cmap=cm.YlOrBr, levels=4)

    ax1.clabel(cs1, levels= level_wallA, inline=True)
    ax2.clabel(cs2, inline=True)

    fig.savefig('test.jpg')

if __name__ == "__main__":
    graphing_contour()

I set cs1 and cs2 to ax1.tricontourf and ax2.tricontourf to get the parameter CS in clabel() in the guide of matplotlib: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.clabel.html#matplotlib.axes.Axes.clabel
For the result I do get the contour line label, but the graph is somewhat messed up and also the label is not clearly show.


来源: stackexchange

问:
Multiple commands in CQRS MediatR question
I use Service - Repository pattern.

I keep all basic CRUD in all repositories and won't touch/change. Service is empty and it's only for functions that are customized. So when I want to execute few actions, I create and customize like this in service class.

HomeService.cs

```<code>public ReceiptModel Save(UserModel user, InvoiceModel invoice)
{
   BeginTransaction();
   User.Save(user);
   var invoiceId = Invoice.Save(invoice);
   Receipt.Save(...);
   Commit();
   var result = Receipt.Get(x => x.InvoiceId == invoiceId);
   return result;
}
</code>```

Now in CQRS + MediatR,

do I need to call _mediator.Send() 4 times?

HomeController.cs

```<code>[HttpPost]
public async Task<IResult> InsertInvoice([FromBody]SaveInvoiceCommand invoice)
{
   await _mediator.Send(new SaveUserCommand(user));
   var invoiceId = await _mediator.Send(invoice);
   await _mediator.Send(new SaveReceiptCommand(invoiceId));
   var result = _mediator.Send(new GetReceiptQuery(invoiceId));
   return Results.Ok(result);
}
</code>```

or create new handler to combine these 4 actions?

If no.2, doesn't it bloat abit more when I have alot of customized functions comparing with service repository pattern?

ContentLicense: CC BY-SA 4.0

Body:
I use Service - Repository pattern.

I keep all basic CRUD in all repositories and won't touch/change. Service is empty and it's only for functions that are customized. So when I want to execute few actions, I create and customize like this in service class.

HomeService.cs

public ReceiptModel Save(UserModel user, InvoiceModel invoice)
{
   BeginTransaction();
   User.Save(user);
   var invoiceId = Invoice.Save(invoice);
   Receipt.Save(...);
   Commit();
   var result = Receipt.Get(x => x.InvoiceId == invoiceId);
   return result;
}

Now in CQRS + MediatR,

do I need to call _mediator.Send() 4 times?

HomeController.cs

[HttpPost]
public async Task<IResult> InsertInvoice([FromBody]SaveInvoiceCommand invoice)
{
   await _mediator.Send(new SaveUserCommand(user));
   var invoiceId = await _mediator.Send(invoice);
   await _mediator.Send(new SaveReceiptCommand(invoiceId));
   var result = _mediator.Send(new GetReceiptQuery(invoiceId));
   return Results.Ok(result);
}

or create new handler to combine these 4 actions?

If no.2, doesn't it bloat abit more when I have alot of customized functions comparing with service repository pattern?


问:
Why do we sometimes have to use the alternate form of this.setState()?
Can someone explain this in a different or better way?  Maybe give a real-world scenario showing why the first example fails?  They say "Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state."  But then they show a way to do it that seems to clearly rely on these values to calculate state.

From the React docs:

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong

this.setState({
  counter: this.state.counter + this.props.increment,
});
```
<p>To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:</p>
<p>// Correct</p>
<pre class="lang-js prettyprint-override"><code>this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
</code>```

Body:
Can someone explain this in a different or better way?  Maybe give a real-world scenario showing why the first example fails?  They say "Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state."  But then they show a way to do it that seems to clearly rely on these values to calculate state.

From the React docs:

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong

this.setState({
  counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));


问:
Upload file in new window cypress
Try to automate upload file in new window. Use the script below. After uploading file I need to click Close button, then the file appear in my field. Close button unclickable after uploading file. Window like froze Use Firefox

enter image description here
enter image description here

```<code>`cy.get('#cgcontent').within(()=>{
  cy.get('[name="x_gs_org_link_id"]').invoke('attr','value').then((key)=>{
    cy.window().then((win) =>{
      cy.stub(win, 'open', url => {
       win.location.href = `${Cypress.env('api_root')}/lot/fam/${key}`
      }).as('newWindow')
    })
  })
  cy.get('.formRowCG1212453 > .large-8 > .formButton').click( {force:true} )
  cy.get('@newWindow').should("be.called")
 })
 cy.get('#xfileupload').attachFile('sample.pdf' , {subjectType:'drag-n-drop'}) // upload
 cy.get('#primaryAction').click( {force:true} ) // upload file button
 cy.wait(2000)
 cy.get('.stack-for-small > :nth-child(2) > .formButton').click() // close button`
</code>```

Title: Upload file in new window cypress

Body:
Try to automate upload file in new window. Use the script below. After uploading file I need to click Close button, then the file appear in my field. Close button unclickable after uploading file. Window like froze Use Firefox

enter image description here
enter image description here

`cy.get('#cgcontent').within(()=>{
  cy.get('[name="x_gs_org_link_id"]').invoke('attr','value').then((key)=>{
    cy.window().then((win) =>{
      cy.stub(win, 'open', url => {
       win.location.href = `${Cypress.env('api_root')}/lot/fam/${key}`
      }).as('newWindow')
    })
  })
  cy.get('.formRowCG1212453 > .large-8 > .formButton').click( {force:true} )
  cy.get('@newWindow').should("be.called")
 })
 cy.get('#xfileupload').attachFile('sample.pdf' , {subjectType:'drag-n-drop'}) // upload
 cy.get('#primaryAction').click( {force:true} ) // upload file button
 cy.wait(2000)
 cy.get('.stack-for-small > :nth-child(2) > .formButton').click() // close button`


问:
check if the user is enabled or not backup from google cloud in android-studio
I'm developing a program related to security in android studio. My problem is I want to make sure that the user has activated the backup feature from the Google account or no. I tried this code:(</p>
```<code>try {
    int backups_enabled = 0;
    try {
        backups_enabled = Settings.Secure.getInt(getApplicationContext().getContentResolver(), "backup_enabled");
    } catch (Settings.SettingNotFoundException ex) {
        ex.printStackTrace();
    }
    Log.i("TAG", "Backups are "+(backups_enabled == 1 ? "enabled" : "disabled"));
} catch (Settings.SettingNotFoundException e) {
    Log.e("TAG", "Setting not found", e);
}
</code>```

Body:
I'm developing a program related to security in android studio. My problem is I want to make sure that the user has activated the backup feature from the Google account or no. I tried this code:(

try {
    int backups_enabled = 0;
    try {
        backups_enabled = Settings.Secure.getInt(getApplicationContext().getContentResolver(), "backup_enabled");
    } catch (Settings.SettingNotFoundException ex) {
        ex.printStackTrace();
    }
    Log.i("TAG", "Backups are "+(backups_enabled == 1 ? "enabled" : "disabled"));
} catch (Settings.SettingNotFoundException e) {
    Log.e("TAG", "Setting not found", e);
}


问:
parser hash_value_field replaces existing field instead of adding to it
I'd like to parse a JSON message as output by Kubernetes and add the result into an existing kubernetes key instead of replacing it.

Example of what I want:

```<code># input data:  {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo"}}
# output data: {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo", "log":"some message"}}
</code>```

And, what I'm getting instead (note that I lost the container name):

```<code># input data:  {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo"}}
# output data: {"message":{"log": "some message"}, "kubernetes":{"log":"some message"}}
</code>```

Configuration:

<filter kubernetes.**>
  @type parser
  emit_invalid_record_to_error true
  hash_value_field kubernetes
  key_name message
  reserve_data true
  reserve_time true
  <parse>
    @type json
  </parse>
</filter>
```

How can I make hash_value_field add instead of replace?

Body:
I'd like to parse a JSON message as output by Kubernetes and add the result into an existing kubernetes key instead of replacing it.

Example of what I want:

# input data:  {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo"}}
# output data: {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo", "log":"some message"}}

And, what I'm getting instead (note that I lost the container name):

# input data:  {"message":{"log": "some message"}, "kubernetes":{"container_name":"foo"}}
# output data: {"message":{"log": "some message"}, "kubernetes":{"log":"some message"}}

Configuration:

<filter kubernetes.**>
  @type parser
  emit_invalid_record_to_error true
  hash_value_field kubernetes
  key_name message
  reserve_data true
  reserve_time true
  <parse>
    @type json
  </parse>
</filter>

How can I make hash_value_field add instead of replace?


问:
phpunit error php_network_getaddresses: getaddrinfo failed: Name or service not known when running composer locally
When i try to run phpUnit locally i get this error:

```<code>Runtime:       PHP 8.0.25
Configuration: /var/www/html/php-project/phpunit.xml

  Warning - The configuration file did not pass validation!
  The following problems have been detected:

  Line 22:
  - Element 'testsuites': This element is not expected.

  Test results may not be as expected.

E                                                                   1 / 1 (100%)

Time: 00:00.375, Memory: 6.00 MB

There was 1 error:

1) ShoppingCartRepositoryTest::testGetShoppingCart
PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

/var/www/html/php-project/src/Config/ConnectDb.php:17
/var/www/html/php-project/src/Config/ConnectDb.php:24
/var/www/html/php-project/src/Repository/ShoppingCartRepository.php:19
/var/www/html/php-project/test/Repository/shoppingCartRepositoryTest.php:14

Caused by
PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known
</code>```

Since im new to PHPUNIT i dont know if im missing some sort of configuration, i'll be more than grateful if someone can help.
It's plain php (no frameworks)

Body:
When i try to run phpUnit locally i get this error:

Runtime:       PHP 8.0.25
Configuration: /var/www/html/php-project/phpunit.xml

  Warning - The configuration file did not pass validation!
  The following problems have been detected:

  Line 22:
  - Element 'testsuites': This element is not expected.

  Test results may not be as expected.

E                                                                   1 / 1 (100%)

Time: 00:00.375, Memory: 6.00 MB

There was 1 error:

1) ShoppingCartRepositoryTest::testGetShoppingCart
PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

/var/www/html/php-project/src/Config/ConnectDb.php:17
/var/www/html/php-project/src/Config/ConnectDb.php:24
/var/www/html/php-project/src/Repository/ShoppingCartRepository.php:19
/var/www/html/php-project/test/Repository/shoppingCartRepositoryTest.php:14

Caused by
PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known

Since im new to PHPUNIT i dont know if im missing some sort of configuration, i'll be more than grateful if someone can help.
It's plain php (no frameworks)


问:
javascript floating point with ajax request
```<code>`function editTrans(t){
            var userid = t;
            alert(userid)
            if (userid != "") {
                $.ajax({
                    url: 'load.php?',
                    type: 'post',
                    data: {userid: userid},
                    success: function(response){
                        $('.modal-body').html(response);
                        $('#loadTransportUpadtae').modal('show');
                    }
                });
            }
        }

$idclient = 6;
$idR= 100;
$passAcross          = $idclient .'.'.$idR;

<button type="button" class="btn btn-sm btn-info userinfo" onclick="editTrans(<?php echo $passAcross; ?>)" >Edit Note</button>`

</code>```

I have a challenge, $idR is an id for a particular field, and $idclient is another value on a particular field, when I pass the values it works but I have a challenge with values that has an ending part to be o, e.g 100, 100, 40. The javascript treats it as a floating point and removes the zero.

How can I pass those values without removing the zeros?

```<code>`function editTrans(t){
            var userid = t;
            alert(userid)// expecting this to have 6.100
            if (userid != "") {
                $.ajax({
                    url: 'load.php?',
                    type: 'post',
                    data: {userid: userid},
                    success: function(response){
                        $('.modal-body').html(response);
                        $('#loadTransportUpadtae').modal('show');
                    }
                });
            }
        }

$idclient = 6;
$idR= 100;
$passAcross          = $idclient .'.'.$idR;
</code>```

I am expecting the function to pick the floating part plus the zero

Body:
`function editTrans(t){
            var userid = t;
            alert(userid)
            if (userid != "") {
                $.ajax({
                    url: 'load.php?',
                    type: 'post',
                    data: {userid: userid},
                    success: function(response){
                        $('.modal-body').html(response);
                        $('#loadTransportUpadtae').modal('show');
                    }
                });
            }
        }

$idclient = 6;
$idR= 100;
$passAcross          = $idclient .'.'.$idR;

<button type="button" class="btn btn-sm btn-info userinfo" onclick="editTrans(<?php echo $passAcross; ?>)" >Edit Note</button>`

I have a challenge, $idR is an id for a particular field, and $idclient is another value on a particular field, when I pass the values it works but I have a challenge with values that has an ending part to be o, e.g 100, 100, 40. The javascript treats it as a floating point and removes the zero.

How can I pass those values without removing the zeros?

`function editTrans(t){
            var userid = t;
            alert(userid)// expecting this to have 6.100
            if (userid != "") {
                $.ajax({
                    url: 'load.php?',
                    type: 'post',
                    data: {userid: userid},
                    success: function(response){
                        $('.modal-body').html(response);
                        $('#loadTransportUpadtae').modal('show');
                    }
                });
            }
        }

$idclient = 6;
$idR= 100;
$passAcross          = $idclient .'.'.$idR;

I am expecting the function to pick the floating part plus the zero


问:
Deploy an ingress controller using the EKS Blueprints module
I'm using the EKS Blusprints module (https://github.com/aws-ia/terraform-aws-eks-blueprints) to deploy the cluster. Now I already deployed the cluster and configured RBAC and IAM. But now I'm struggling with deploying an ingress controller to expose ArgoCD UI to the public and an ingress controller for other programs.

Here's the Terraform config I use currently for deploying add-ons.

```<code>module "kubernetes_addons" {
  source = "github.com/aws-ia/terraform-aws-eks-blueprints/modules/kubernetes-addons"

  eks_cluster_id = module.eks_blueprints.eks_cluster_id

  # ArgoCD addon
  enable_argocd         = true
  argocd_manage_add_ons = true

  argocd_applications = {
    addons = local.addon_application
    workloads = local.workload_application
  }

  enable_aws_load_balancer_controller  = true
  enable_karpenter                     = false
  enable_amazon_eks_aws_ebs_csi_driver = true
  enable_aws_for_fluentbit             = true
  enable_metrics_server                = true
  enable_kubecost                      = true

}
</code>```

Can anyone help me to understand how to archive this?

Body:
I'm using the EKS Blusprints module (https://github.com/aws-ia/terraform-aws-eks-blueprints) to deploy the cluster. Now I already deployed the cluster and configured RBAC and IAM. But now I'm struggling with deploying an ingress controller to expose ArgoCD UI to the public and an ingress controller for other programs.

Here's the Terraform config I use currently for deploying add-ons.

module "kubernetes_addons" {
  source = "github.com/aws-ia/terraform-aws-eks-blueprints/modules/kubernetes-addons"

  eks_cluster_id = module.eks_blueprints.eks_cluster_id

  # ArgoCD addon
  enable_argocd         = true
  argocd_manage_add_ons = true

  argocd_applications = {
    addons = local.addon_application
    workloads = local.workload_application
  }

  enable_aws_load_balancer_controller  = true
  enable_karpenter                     = false
  enable_amazon_eks_aws_ebs_csi_driver = true
  enable_aws_for_fluentbit             = true
  enable_metrics_server                = true
  enable_kubecost                      = true

}

Can anyone help me to understand how to archive this?


问:
Limit number of button click And insert index to id/name of element
I'm trying to upload image and if I were need to add more images, I just simply need to click the button. Now,  I have done the button and it works but the problem now is since new fields are created for uploading image, the name and id of the elements are similar. So, the javascript won't work. I think I need to insert index into the element but I can't figure it out how. Thanks!

function createGambar() {
  var newDiv = document.createElement('div');
  newDiv.setAttribute('class', 'input-group');
  newDiv.innerHTML = "
Lampiran 1
<input type='text' class='form-control bg-light' id='label_file' disabled placeholder='Gambar'><input type='file' name='lampiran1' id='file1' hidden onchange='setFileName();'>

Kapsyen Gambar 1
 <textarea class='form-control' style='resize:none' name='kapsyen' id='kapsyen' cols='20' rows='3'placeholder='e.g YM Pengarah Memberi Cenderahati Kepada Tetamu Jemputan' required></textarea>

";
  document.getElementById("newGambar").appendChild(newDiv);
}

function setFileName() {
  var fileName = document.getElementById("file1");
  document.getElementById("label_file").value = fileName.files[0].name;
  preview1();
}

function preview1() {
  thumb.src = "";
  if (event.target.files[0]['type'].split('/')[0] === 'image') {
    thumb.src = URL.createObjectURL(event.target.files[0]);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="newGambar"></div>
<div class="row">
  <div class="col-sm-3">
  </div>
  <div class="col-sm-6">
    <button type="button" id="buttonAdd" class="btn btn-success mt-1 w-100" onclick="createGambar(); "><i class="fa-solid fa-add"></i>  Tambah Perkembangan</button>
  </div>
  <div class="col-sm-3">
  </div>
</div></code>```

Body:
I'm trying to upload image and if I were need to add more images, I just simply need to click the button. Now,  I have done the button and it works but the problem now is since new fields are created for uploading image, the name and id of the elements are similar. So, the javascript won't work. I think I need to insert index into the element but I can't figure it out how. Thanks!

function createGambar() {
  var newDiv = document.createElement('div');
  newDiv.setAttribute('class', 'input-group');
  newDiv.innerHTML = "
Lampiran 1
<input type='text' class='form-control bg-light' id='label_file' disabled placeholder='Gambar'><input type='file' name='lampiran1' id='file1' hidden onchange='setFileName();'>

Kapsyen Gambar 1
 <textarea class='form-control' style='resize:none' name='kapsyen' id='kapsyen' cols='20' rows='3'placeholder='e.g YM Pengarah Memberi Cenderahati Kepada Tetamu Jemputan' required></textarea>

";
  document.getElementById("newGambar").appendChild(newDiv);
}

function setFileName() {
  var fileName = document.getElementById("file1");
  document.getElementById("label_file").value = fileName.files[0].name;
  preview1();
}

function preview1() {
  thumb.src = "";
  if (event.target.files[0]['type'].split('/')[0] === 'image') {
    thumb.src = URL.createObjectURL(event.target.files[0]);
  }
}

    <button type="button" id="buttonAdd" class="btn btn-success mt-1 w-100" onclick="createGambar(); ">  Tambah Perkembangan</button>


问:
generating typescript file(ts) from javascript file(.js) and type definition file(.d.ts)
```<code>// foo.js
const add = (a, b) => `${a}${b}`

// foo.d.ts
export declare const add: (a: string, b: number) => string

// foo.ts
export const add = (a: string, b: number) => `${a}${b}`
</code>```

or in other words: how to combine foo.js and foo.d.ts into foo.ts?
the reverse can be done via tsc -d foo.ts but i wasn't able to do it this way.

use cases: convert javascript project with type definition into typescript project

Body:
// foo.js
const add = (a, b) => `${a}${b}`

// foo.d.ts
export declare const add: (a: string, b: number) => string

// foo.ts
export const add = (a: string, b: number) => `${a}${b}`

or in other words: how to combine foo.js and foo.d.ts into foo.ts?
the reverse can be done via tsc -d foo.ts but i wasn't able to do it this way.

use cases: convert javascript project with type definition into typescript project


问:
How can I break a while loop with ServerSocket.accept() inside without throwing exception?
I connect multiple clients to a server using Sockets and a ServerSocket. Currently my servers run() method has a while(bool) loop that creates a new socket whenever a client tries to connect but I want to break the loop from another method. Sounds easy but simply changing the boolean to false won't do since something waits on serverSocket.accept() for it to, well, accept.

Using setSoTimeout didn't work for me, as it throws an exception. I need the thread to loop and wait for new clients until one of them sends a "CLOSE" String via Stream, not for a set period of time, but I could be doing something wrong. I would like to keep serverSocket in try-with-resources so that everything closes when I close the JFrame with mouseclick, still I need it to close from code too. I also tried creating a "Ghost" client that should break the cycle but I think it's not an elegant solution and now I get socket closed exception in ClientThread first line ine while loop. I am so lost please help me.

the code:

```<code>class ClientThread implements Runnable{
    private Socket socket;
    private String name;
    private boolean running;
    private PhoneBookServer server;

    private ObjectOutputStream outputStream = null;

    ClientThread(PhoneBookServer server, Socket socket){
        this.server = server;
        this.socket = socket;
        new Thread(this).start();
    }

    public String getName(){
        return name;
    }

    public void disconnect(){
        try {
            outputStream.writeObject("OK BYE");
            server.printMessage("OK BYE");
            running = false;
            socket.close();
            socket = null;
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        String message;
        try(ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());){
            outputStream = output;
            name = (String) input.readObject();
            running = true;
            server.addClient(this);
            while(running){
                message = (String) input.readObject();
                server.printMessage(this, message);

                if(message.equals("BYE")){
                    disconnect();
                    server.removeClient(this);
                }
                if(message.equals("CLOSE")){
                    server.disconnectAll();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
</code>```

interesting methods from the Server class:

```<code>    synchronized void disconnectAll(){
        for(ClientThread c : connectedClients){
            c.disconnect();
        }
        running = false;
    }

    public void run(){
        boolean socket_created = false;

        try(ServerSocket serverSocket = new ServerSocket(SERVER_PORT)){
            String host = InetAddress.getLocalHost().getHostName();
            System.out.println("Serwer został uruchomiony na hoście " + host);
            socket_created = true;

            while(running){
                Socket socket = serverSocket.accept();
                if (socket != null){
                    new ClientThread(this, socket);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
            }
        }
    }
</code>```

Body:
I connect multiple clients to a server using Sockets and a ServerSocket. Currently my servers run() method has a while(bool) loop that creates a new socket whenever a client tries to connect but I want to break the loop from another method. Sounds easy but simply changing the boolean to false won't do since something waits on serverSocket.accept() for it to, well, accept.

Using setSoTimeout didn't work for me, as it throws an exception. I need the thread to loop and wait for new clients until one of them sends a "CLOSE" String via Stream, not for a set period of time, but I could be doing something wrong. I would like to keep serverSocket in try-with-resources so that everything closes when I close the JFrame with mouseclick, still I need it to close from code too. I also tried creating a "Ghost" client that should break the cycle but I think it's not an elegant solution and now I get socket closed exception in ClientThread first line ine while loop. I am so lost please help me.

the code:

class ClientThread implements Runnable{
    private Socket socket;
    private String name;
    private boolean running;
    private PhoneBookServer server;

    private ObjectOutputStream outputStream = null;

    ClientThread(PhoneBookServer server, Socket socket){
        this.server = server;
        this.socket = socket;
        new Thread(this).start();
    }

    public String getName(){
        return name;
    }

    public void disconnect(){
        try {
            outputStream.writeObject("OK BYE");
            server.printMessage("OK BYE");
            running = false;
            socket.close();
            socket = null;
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        String message;
        try(ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());){
            outputStream = output;
            name = (String) input.readObject();
            running = true;
            server.addClient(this);
            while(running){
                message = (String) input.readObject();
                server.printMessage(this, message);

                if(message.equals("BYE")){
                    disconnect();
                    server.removeClient(this);
                }
                if(message.equals("CLOSE")){
                    server.disconnectAll();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

interesting methods from the Server class:

    synchronized void disconnectAll(){
        for(ClientThread c : connectedClients){
            c.disconnect();
        }
        running = false;
    }

    public void run(){
        boolean socket_created = false;

        try(ServerSocket serverSocket = new ServerSocket(SERVER_PORT)){
            String host = InetAddress.getLocalHost().getHostName();
            System.out.println("Serwer został uruchomiony na hoście " + host);
            socket_created = true;

            while(running){
                Socket socket = serverSocket.accept();
                if (socket != null){
                    new ClientThread(this, socket);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
            }
        }
    }


问:
How to apply Batchnorm and Temporal Convolutions To Temporarly Variant Data?
My task is to implement the architecture discussed here. I am currently implementing a sub-network, where the input tensor is of shape (N, T/4, 832), where T is time. The sub-network consists of "Temporal Linear Layer -> Batch Norm -> Relu -> Temporal Convolution. My issue lies in implementation, how can I apply a temporal batchnorm & temporal convolution to a variable T?

My current implementation of the sub-network in Pytorch is as follows:

```<code>nn.Sequential(
nn.Linear(832, 832), # Input: N x T/4 x 832
nn.BatchNorm1d(832), # Input : N x 832 x T/4
nn.ReLU(),
nn.Conv1d(832,832) # Input: N x 832 x T/4
# Output: N x 832 x T/4 - 2
)
</code>```

The issue is that Conv1d is downsampling the T dimension. Which is not, correct hence my question. It's hard to find any resources on what precisely a temporal convolution is.

Body:
My task is to implement the architecture discussed here. I am currently implementing a sub-network, where the input tensor is of shape (N, T/4, 832), where T is time. The sub-network consists of "Temporal Linear Layer -> Batch Norm -> Relu -> Temporal Convolution. My issue lies in implementation, how can I apply a temporal batchnorm & temporal convolution to a variable T?

My current implementation of the sub-network in Pytorch is as follows:

nn.Sequential(
nn.Linear(832, 832), # Input: N x T/4 x 832
nn.BatchNorm1d(832), # Input : N x 832 x T/4
nn.ReLU(),
nn.Conv1d(832,832) # Input: N x 832 x T/4
# Output: N x 832 x T/4 - 2
)

The issue is that Conv1d is downsampling the T dimension. Which is not, correct hence my question. It's hard to find any resources on what precisely a temporal convolution is.


问:
Assign formatting with an extension to a keyboard shortcut
I have the Prettier extension for Visual Studio Code installed. All the documentation goes over how to make Prettier the default formatter. However, in my case, I need to use Prettier for a class, but I don't want to use it at work. Given that my settings are synced, I know that I can do Ctrl + Shift + P and select Format Document With... and then select Prettier. My question is, is there a way to assign a shortcut to formatting a document with a certain formatter so that I don't have to navigate my way through the VS Code menus?

I did assign Format Document With... to Ctrl + Shift + Alt + F but I'm just wondering if there is a better way. Thanks!


问:
Same strings in python aren't matching in web scraping
Hi I am trying to scrape gujarat rera using selenium python.

main.py:

```<code>import csv
import os
import time
import chromedriver_autoinstaller
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
WORK_DONE = False
chromedriver_autoinstaller.install()

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://gujrerar1.gujarat.gov.in/home")
time.sleep(3)

close = driver.find_elements(By.CSS_SELECTOR,".close") # click close on popup.
for i in close:
    try:
        i.click()
        time.sleep(0.5)
    except:
        pass
close = driver.find_elements(By.CSS_SELECTOR,".close") # click close on popup.
for i in close:
    try:
        i.click()
        time.sleep(0.5)
    except:
        pass

search_bar = driver.find_element(By.ID,"password")

data=["031218"]

for reg_no in data:
    last_thing_of_reg_no = reg_no.split("/")[5]
    search_bar.send_keys(Keys.CONTROL + "A")
    search_bar.send_keys(last_thing_of_reg_no)

    driver.find_element(By.NAME,"btn1").click()   # click on search button.
    time.sleep(1.5)
    driver.find_element(By.TAG_NAME,"body").send_keys(Keys.END) # scroll the page to end
    time.sleep(1.5)
    total_projects = driver.find_elements(By.CSS_SELECTOR,".search_result_list")
    for projects in total_projects:
        all_paragraphs = projects.find_elements(By.TAG_NAME,"p")
        for i in all_paragraphs:
            text = i.text.replace("Reg No. : ","")
            print(text)
            print(reg_no)
            if reg_no == text:
                print("yes")

    print("done")
    time.sleep(100)
print("done")
time.sleep(50)
</code>```

First, it opens the website, closes the pop-ups, finds a search bar, and sends reg_no. Then it gets all the paragraph tags in the website, iterates through each of them, and the error is there. Both statements are exactly same but it is not going inside if statement, I don't know why it is so.

I want to print yes in this code and iterate inside it, but I don't know why it is not printing yes, even though both the strings are exactly the same.

I don't know what else to write but feel free to ask more questions,
Many thanks for considering my request.

Body:
Hi I am trying to scrape gujarat rera using selenium python.

main.py:

import csv
import os
import time
import chromedriver_autoinstaller
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
WORK_DONE = False
chromedriver_autoinstaller.install()

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://gujrerar1.gujarat.gov.in/home")
time.sleep(3)

close = driver.find_elements(By.CSS_SELECTOR,".close") # click close on popup.
for i in close:
    try:
        i.click()
        time.sleep(0.5)
    except:
        pass
close = driver.find_elements(By.CSS_SELECTOR,".close") # click close on popup.
for i in close:
    try:
        i.click()
        time.sleep(0.5)
    except:
        pass

search_bar = driver.find_element(By.ID,"password")

data=["031218"]

for reg_no in data:
    last_thing_of_reg_no = reg_no.split("/")[5]
    search_bar.send_keys(Keys.CONTROL + "A")
    search_bar.send_keys(last_thing_of_reg_no)

    driver.find_element(By.NAME,"btn1").click()   # click on search button.
    time.sleep(1.5)
    driver.find_element(By.TAG_NAME,"body").send_keys(Keys.END) # scroll the page to end
    time.sleep(1.5)
    total_projects = driver.find_elements(By.CSS_SELECTOR,".search_result_list")
    for projects in total_projects:
        all_paragraphs = projects.find_elements(By.TAG_NAME,"p")
        for i in all_paragraphs:
            text = i.text.replace("Reg No. : ","")
            print(text)
            print(reg_no)
            if reg_no == text:
                print("yes")

    print("done")
    time.sleep(100)
print("done")
time.sleep(50)

First, it opens the website, closes the pop-ups, finds a search bar, and sends reg_no. Then it gets all the paragraph tags in the website, iterates through each of them, and the error is there. Both statements are exactly same but it is not going inside if statement, I don't know why it is so.

I want to print yes in this code and iterate inside it, but I don't know why it is not printing yes, even though both the strings are exactly the same.

I don't know what else to write but feel free to ask more questions,
Many thanks for considering my request.


问:
How do I fix this illegal offset type error on php?
I'm trying to get the post of the title from an array where the post id it's equal to post_id on second array, but i get this error:

Fatal error: Uncaught TypeError: Illegal offset type on line $array[$week][$days][$day]['post_title'] = $post_data['post_title'];

```<code>$posts = Array ( [0] => Array ( [post_id] => 3 [0] => 3 [post_title] => Task 1 );

$array = [{"week1":{"day1":[{"post_id":"3","post_type":"timebased","post_reps":"","post_sets":"","post_time":"60","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"12","post_sets":"4","post_time":"","post_rest":"35"}],"day2":[{"post_id":"1","post_type":"repsbased","post_reps":"8","post_sets":"4","post_time":"","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"8","post_sets":"5","post_time":"","post_rest":"60"}],"day3":[],"day4":[],"day5":[],"day6":[],"day7":[]}}];

function getTitle($array, $posts){
    if(is_array($array)) {
    foreach($array as $week){
    foreach($week as $days){
        foreach($days as $day => $post){
        foreach($post as $data){
            foreach($posts as $post_data){
            if($data['post_id'] == $post_data['post_id']){
                $array[$week][$days][$day]['post_title'] = $post_data['post_title'];
                                }
                            }
                        }
                    }
                }
            }
        return $array;
        }
    return false;
}
</code>```

Body:
I'm trying to get the post of the title from an array where the post id it's equal to post_id on second array, but i get this error:

Fatal error: Uncaught TypeError: Illegal offset type on line $array[$week][$days][$day]['post_title'] = $post_data['post_title'];

$posts = Array ( [0] => Array ( [post_id] => 3 [0] => 3 [post_title] => Task 1 );

$array = [{"week1":{"day1":[{"post_id":"3","post_type":"timebased","post_reps":"","post_sets":"","post_time":"60","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"12","post_sets":"4","post_time":"","post_rest":"35"}],"day2":[{"post_id":"1","post_type":"repsbased","post_reps":"8","post_sets":"4","post_time":"","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"8","post_sets":"5","post_time":"","post_rest":"60"}],"day3":[],"day4":[],"day5":[],"day6":[],"day7":[]}}];

function getTitle($array, $posts){
    if(is_array($array)) {
    foreach($array as $week){
    foreach($week as $days){
        foreach($days as $day => $post){
        foreach($post as $data){
            foreach($posts as $post_data){
            if($data['post_id'] == $post_data['post_id']){
                $array[$week][$days][$day]['post_title'] = $post_data['post_title'];
                                }
                            }
                        }
                    }
                }
            }
        return $array;
        }
    return false;
}


问:
Pytest - Mock and Testing Django url with call to external package
HI I need to test my endpoint, it is expecting a json from another call to external library

url

```<code>path("check-services", views.check_services, name="check_services"),
</code>```

views

```<code>from api.services import Services
services = Services()

def check_services(request):
    payload = json.loads(request.GET.get("the_params"))
    error, message, response = services.check_services(payload)
    if error:
       return JsonResponse({"res": [], 'error': True, 'message': message})
     return JsonResponse({"res": response, 'error': False, "message": "Success"})
</code>```

tests

```<code>import pytest
from api.services import Services

@patch('api.services.Services', side_effect=[True, 'Success', []])
   def test_check_services(client):
       payload = {}
       url = reverse('check_services')
       res = client.get(url)
       //really dont know how to mock the external service here
       error,message, response = Services().check_services(payload)
       print(response)
       //assertion
       assert error ==True
</code>```

Got error

```<code>    AssertionError: assert <MagicMock name='Services.get().status_code' id='140222676793616'> == 200
    E        +  where <MagicMock name='Services.get().status_code' id='140222676793616'> = <MagicMock name='Services.get()' id='140222676785840'>.status_code

</code>```

But it is still actually calling the external package when I commented the line that says `res=client.get(url).
Inspecting the package Service class

```<code>   class Services:
        def __init__(self):
            //

         def check_services(payload: dict):
             try
                 response = //some manipulation here ex calling another api
                 return False, 'success', response

             except Exception as e:
                  return True,e.message,[]

</code>```

Update ,

Ok so I updated my test using unittest.mock

```<code>  class SimpleTestCase(TestCase):

     def setUp(self):
        self.client = Client()

     @patch('Courier.views.check_services')
     def test_mocked_test_case_should_succeed(self, mocked_check_services):
        """
           This is a simple testcase using mock feature.
           1 - Decorate the method with path.
           2 - Reference the mock in test method as param (mocked_check_services).
           3 - Define a value of the return of method (sub method or property) to mock.
            4 - Call the mocked method and compare.
          """
           mocked_check_services.get.content.return_value = b'{"res": [], "error": true, "messages": "Invalid service"}'
            test_address = '{"name": "37 Jamaica Drive"}'
            url = f'{reverse("check_services")}?the_params={test_address}'
             response = self.client.get(url)
             self.assertEqual(response.status_code, 200)
             self.assertEqual(
             response.content, b'{"res": [], "error": true, "message": "Invalid service"}')

</code>```

Bu still it keeps calling the Services class directly.

How to test in this scenario without actually running the imported external method from a library?

Body:
HI I need to test my endpoint, it is expecting a json from another call to external library

url

path("check-services", views.check_services, name="check_services"),

views

from api.services import Services
services = Services()

def check_services(request):
    payload = json.loads(request.GET.get("the_params"))
    error, message, response = services.check_services(payload)
    if error:
       return JsonResponse({"res": [], 'error': True, 'message': message})
     return JsonResponse({"res": response, 'error': False, "message": "Success"})

tests

import pytest
from api.services import Services

@patch('api.services.Services', side_effect=[True, 'Success', []])
   def test_check_services(client):
       payload = {}
       url = reverse('check_services')
       res = client.get(url)
       //really dont know how to mock the external service here
       error,message, response = Services().check_services(payload)
       print(response)
       //assertion
       assert error ==True

Got error

    AssertionError: assert <MagicMock name='Services.get().status_code' id='140222676793616'> == 200
    E        +  where <MagicMock name='Services.get().status_code' id='140222676793616'> = <MagicMock name='Services.get()' id='140222676785840'>.status_code

But it is still actually calling the external package when I commented the line that says `res=client.get(url).
Inspecting the package Service class

   class Services:
        def __init__(self):
            //

         def check_services(payload: dict):
             try
                 response = //some manipulation here ex calling another api
                 return False, 'success', response

             except Exception as e:
                  return True,e.message,[]

Update ,

Ok so I updated my test using unittest.mock

  class SimpleTestCase(TestCase):

     def setUp(self):
        self.client = Client()

     @patch('Courier.views.check_services')
     def test_mocked_test_case_should_succeed(self, mocked_check_services):
        """
           This is a simple testcase using mock feature.
           1 - Decorate the method with path.
           2 - Reference the mock in test method as param (mocked_check_services).
           3 - Define a value of the return of method (sub method or property) to mock.
            4 - Call the mocked method and compare.
          """
           mocked_check_services.get.content.return_value = b'{"res": [], "error": true, "messages": "Invalid service"}'
            test_address = '{"name": "37 Jamaica Drive"}'
            url = f'{reverse("check_services")}?the_params={test_address}'
             response = self.client.get(url)
             self.assertEqual(response.status_code, 200)
             self.assertEqual(
             response.content, b'{"res": [], "error": true, "message": "Invalid service"}')

Bu still it keeps calling the Services class directly.

How to test in this scenario without actually running the imported external method from a library?


问:
trying to get current user using session flask, but variable returns an empty list
Im creating an event manager web app.. and right now I'm trying to query the events that the current user is in.

```<code>@classmethod
    def getevent(cls, id):
        cursor = mysql.connection.cursor()

        sql = f"SELECT name, description FROM event Where p_id = {id} Order by id"
        cursor.execute(sql)
        result = cursor.fetchall()
        return result
</code>```

this is the function that gets the event name and description where Participant ID (p_id) is equal to the current user (session['userID']

```<code>@routes.route("/listofevents", methods = ['POST', 'GET'])
def Levents():
    id = session['userID']
    events = models.Event.getevent(id)

    print(id)
    print(events)
    return render_template("index_ListofEvents.html", events = events)
</code>```

the route. This works fine but nothing shows up in the webpage.. when i try to print the the events it returns an empty list []

Can anybody help me please. What am I missing?

EDIT:
when I run the query in phpmyadmin it works but I need to replace {id} in string format e.g. '2020-6969' but when I print session it just returns int
2020-6969

Body:
Im creating an event manager web app.. and right now I'm trying to query the events that the current user is in.

@classmethod
    def getevent(cls, id):
        cursor = mysql.connection.cursor()

        sql = f"SELECT name, description FROM event Where p_id = {id} Order by id"
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

this is the function that gets the event name and description where Participant ID (p_id) is equal to the current user (session['userID']

@routes.route("/listofevents", methods = ['POST', 'GET'])
def Levents():
    id = session['userID']
    events = models.Event.getevent(id)

    print(id)
    print(events)
    return render_template("index_ListofEvents.html", events = events)

the route. This works fine but nothing shows up in the webpage.. when i try to print the the events it returns an empty list []

Can anybody help me please. What am I missing?

EDIT:
when I run the query in phpmyadmin it works but I need to replace {id} in string format e.g. '2020-6969' but when I print session it just returns int
2020-6969


问:
Failover cluster manager for Analysis Services
I have SSAS running on Primary node (secondary node as well) and a failover cluster manager running and have the nodes added. Now I need to make sure if the SSAS service stops, it'll failover to the secondary server. (Active - Passive)

I added the SSAS as a generic service to the role, I can see the owner of the role switches to secondary when the service stops, but the current host server stays on Primary.

Should I add the service as Resource type to the cluster as well? If so, it seems to require the DLL file. any idea which SSAS DLL file should I add?


问:
Aggregate multiple "OR" coditions inside the where clause using Entity Framework and SQL Server
I'm using SQL Server and Entity Framework Core. My table has multiple primary keys and I have to filter many rows at the same time. I'd like to known what's the best approach. I'm trying to aggregate multiple or statements at the where clause, but it's not working. Either it fails to filter or Entity Framework says it cannot convert the LINQ expression to a valid SQL.

To make it simple, let's say my entity has two primary keys.

// WORKS BUT ONLY FOR INPUTS OF LENGTH 2!
public async Task<IList<MyEntity>> GetById(IList<MyEntity> entities)
{
    var query = from entity in Context.MyEntity
                where (entity.PkNumberOne == entities[0].PkNumberOne && entity.PkNumberTwo == entities[0].PkNumberTwo) ||
                       (entity.PkNumberOne == entities[1].PkNumberOne && entity.PkNumberTwo == entities[1].PkNumberTwo)
                select entity;

    return await query.AsNoTracking().ToListAsync();
}
```
<p>This approach works, but I need to iterate over the entities list.</p>
<p>I have also tried using the method <code>.Any</code>, but the Entity Framework could not translate the expression to valid SQL.</p>
<pre class="lang-cs prettyprint-override"><code>// DOES NOT WORK!
var query = from entity in Context.MyEntity
            where entities.Any(e => (entity.PkNumberOne == e.PkNumberOne) && (entity.PkNumberTwo == e.PkNumberTwo))
            select entity;
</code>```

Somehow, I need to programmatically create the fallowing SQL statement for N elements.

SELECT *
FROM MyEntity
WHERE
  (PkNumberOne = "Obj1Pk1" AND PkNumberTwo = "Obj1Pk2") OR
  (PkNumberOne = "Obj2Pk1" AND PkNumberTwo = "Obj2Pk2") OR
  ...
  (PkNumberOne = "ObjNPk1" AND PkNumberTwo = "ObjNPk2")
```

Maybe this is not the best approach. If so, please, what should I be doing differently? Is there a better way to filter rows of tables containing composed primary keys?

Body:
I'm using SQL Server and Entity Framework Core. My table has multiple primary keys and I have to filter many rows at the same time. I'd like to known what's the best approach. I'm trying to aggregate multiple or statements at the where clause, but it's not working. Either it fails to filter or Entity Framework says it cannot convert the LINQ expression to a valid SQL.

To make it simple, let's say my entity has two primary keys.

// WORKS BUT ONLY FOR INPUTS OF LENGTH 2!
public async Task<IList<MyEntity>> GetById(IList<MyEntity> entities)
{
    var query = from entity in Context.MyEntity
                where (entity.PkNumberOne == entities[0].PkNumberOne && entity.PkNumberTwo == entities[0].PkNumberTwo) ||
                       (entity.PkNumberOne == entities[1].PkNumberOne && entity.PkNumberTwo == entities[1].PkNumberTwo)
                select entity;

    return await query.AsNoTracking().ToListAsync();
}

This approach works, but I need to iterate over the entities list.

I have also tried using the method .Any, but the Entity Framework could not translate the expression to valid SQL.

// DOES NOT WORK!
var query = from entity in Context.MyEntity
            where entities.Any(e => (entity.PkNumberOne == e.PkNumberOne) && (entity.PkNumberTwo == e.PkNumberTwo))
            select entity;

Somehow, I need to programmatically create the fallowing SQL statement for N elements.

SELECT *
FROM MyEntity
WHERE
  (PkNumberOne = "Obj1Pk1" AND PkNumberTwo = "Obj1Pk2") OR
  (PkNumberOne = "Obj2Pk1" AND PkNumberTwo = "Obj2Pk2") OR
  ...
  (PkNumberOne = "ObjNPk1" AND PkNumberTwo = "ObjNPk2")

Maybe this is not the best approach. If so, please, what should I be doing differently? Is there a better way to filter rows of tables containing composed primary keys?


问:
Setting up Apache Atlas
I am trying to setup Apache Atlas on my Windows 10 machine.  I have the following prereqs:

Maven Version 3.8.6

JDK Version 1.8.0

Python 2.7.7

I then pull Apache Atlas and I am using tags/release-2.3.0.  Once downloaded, I run the following commands in Powershell:

```<code>set MAVEN_OPTS="-Xms2g -Xmx2g
mvn clean install
</code>```

This starts running a set of tests, which fail.  I get the following error:

in org.apache.atlas.kafka.KafkaNotificationTest [ERROR]
org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages
Time elapsed: 8.178 s  <<< FAILURE! java.lang.NoClassDefFoundError:
org/apache/atlas/kafka/AtlasKafkaMessage
at org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages(KafkaNotificationTest.java:63)
Caused by: java.lang.ClassNotFoundException:
org.apache.atlas.kafka.AtlasKafkaMessage
at org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages(KafkaNotificationTest.java:63)

How can I resolve this issue to install Atlas?

Title: Setting up Apache Atlas

Body:
I am trying to setup Apache Atlas on my Windows 10 machine.  I have the following prereqs:

Maven Version 3.8.6

JDK Version 1.8.0

Python 2.7.7

I then pull Apache Atlas and I am using tags/release-2.3.0.  Once downloaded, I run the following commands in Powershell:

set MAVEN_OPTS="-Xms2g -Xmx2g
mvn clean install

This starts running a set of tests, which fail.  I get the following error:

in org.apache.atlas.kafka.KafkaNotificationTest [ERROR]
org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages
Time elapsed: 8.178 s  <<< FAILURE! java.lang.NoClassDefFoundError:
org/apache/atlas/kafka/AtlasKafkaMessage
at org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages(KafkaNotificationTest.java:63)
Caused by: java.lang.ClassNotFoundException:
org.apache.atlas.kafka.AtlasKafkaMessage
at org.apache.atlas.kafka.KafkaNotificationTest.testReceiveKafkaMessages(KafkaNotificationTest.java:63)

How can I resolve this issue to install Atlas?


问:
Android Jetpack Compose using same elevation value

Hi, I want to migrate my apps to android jetpack compose and create custom card like this. But, when I try to using my trick on xml (using same elevation value) to create shadow around the card, I can't generate the same result.

How can this be achieved using jetpack compose?


问:
Need to align UIDs between 2 books (2 diff languages)
I work with translations, and the translated version UID must match the original version in English.

Each section (chapter, subsection, etc) has a Unique ID number in English, and they must match to the translated version. If both versions are aligned, it gets ingested easily in our CMS. I have a vague idea on how to start, but am sure this is not a unique problem, and that other folks here may have gone through something similar. The language used for the CMS is XML. If there are UIDs that show up in one language but not the other, it needs to be identified and spat out on a csv file. thanks!

This is new for me, I just finished a Python course and could use some help.


问:
Restrict MongoDB schema to particular subset of types
I am using, TypeScript, express and mongoose;

I am was just wondering how one could restrict MongoDB a schema with mongoose to just a particular subset of types?

for example here something like this is what I am trying to do

```<code>const exampleSchema = new mongoose.Schema(
  {
    example: { type: String || Number }
  },
  { timestamps: true }
);
</code>```

Body:
I am using, TypeScript, express and mongoose;

I am was just wondering how one could restrict MongoDB a schema with mongoose to just a particular subset of types?

for example here something like this is what I am trying to do

const exampleSchema = new mongoose.Schema(
  {
    example: { type: String || Number }
  },
  { timestamps: true }
);


问:
TDengine memory leakage introduced by tmq_consumer_poll
there seems existence of memory leakage introduced by tmq_consumer_poll

If anyone is willing to help, there're the steps to reproduce the behavior:

attached below is the test code to demonstrate, which is based on <TDengine>/docs/examples/c/tmq_example.c better compile with -g and use valgrind to test and get the leak report, otherwise leak might not be clearly discovered, because leak is so small(312 bytes for each call of tmq_consume_poll), you have to run long time to get OOM

Environment:

OS: [Linux xxh-VirtualBox 5.15.0-56-generic 62~20.04.1-Ubuntu SMP Tue Nov 22 21:24:20 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux]
TDengine Version [3.0.2.2]

I expect no memory leakage


问:
How can I resolve the exception reported by rocksdb when using NebulaGraph Exchange?
I want to export data from NebulaGraph and used the configuration file provided by the official documentation.

The core content of the configuration file used in this example is as follows:

```<code>  # Processing tags
  # There are tag config examples for different dataSources.
  tags: [
    # export NebulaGraph tag data to csv, only support export to CSV for now.
    {
      name: player
      type: {
        source: Nebula
        sink: CSV
      }
      # the path to save the NebulaGrpah data, make sure the path doesn't exist.
      path:"hdfs://192.168.12.177:9000/vertex/player"
      # if no need to export any properties when export NebulaGraph tag data
      # if noField is configured true, just export vertexId
      noField:false
      # define properties to export from NebulaGraph tag data
      # if return.fields is configured as empty list, then export all properties
      return.fields:[]
      # nebula space partition number
      partition:10
    }
</code>```

Then I executed the spark task as follows:

```<code>./spark-submit --master "local" --class com.vesoft.nebula.exchange.Exchange ~/exchange-ent/nebula-exchange-ent-3.3.0.jar -c ~/exchange-ent/export_application.conf
</code>```

However, the task fails to be executed, and the following error message is displayed:

```<code>org.rocksdb.RocksDBException: While open a file for appending: /path/sst/1-102.sst: No such file or directory
</code>```

I checked the path and /path/sst/ exists, and I have checked that the permission of this folder also belongs to NebulaGraph.

Could anyone help hint at where I could be wrong?

Body:
I want to export data from NebulaGraph and used the configuration file provided by the official documentation.

The core content of the configuration file used in this example is as follows:

  # Processing tags
  # There are tag config examples for different dataSources.
  tags: [
    # export NebulaGraph tag data to csv, only support export to CSV for now.
    {
      name: player
      type: {
        source: Nebula
        sink: CSV
      }
      # the path to save the NebulaGrpah data, make sure the path doesn't exist.
      path:"hdfs://192.168.12.177:9000/vertex/player"
      # if no need to export any properties when export NebulaGraph tag data
      # if noField is configured true, just export vertexId
      noField:false
      # define properties to export from NebulaGraph tag data
      # if return.fields is configured as empty list, then export all properties
      return.fields:[]
      # nebula space partition number
      partition:10
    }

Then I executed the spark task as follows:

./spark-submit --master "local" --class com.vesoft.nebula.exchange.Exchange ~/exchange-ent/nebula-exchange-ent-3.3.0.jar -c ~/exchange-ent/export_application.conf

However, the task fails to be executed, and the following error message is displayed:

org.rocksdb.RocksDBException: While open a file for appending: /path/sst/1-102.sst: No such file or directory

I checked the path and /path/sst/ exists, and I have checked that the permission of this folder also belongs to NebulaGraph.

Could anyone help hint at where I could be wrong?


问:
django function call class and return template to show result issue
I now have a function in views.py that determines the user input options and uses multi-threaded new a class

views.py

```<code>try:
poc_instance = None

                upload_file = request.FILES['file']
                ext = upload_file.name.split('.')[-1]
                poc = request.POST.get('poc_list')
                input_payload = request.POST.get('input_payload')

                if upload_file.size != 0 and poc != "" and input_payload != "":
                    if ext in ['txt']:
                        uuid_str = uuid.uuid4().hex
                        upload_file.name = uuid_str + '.txt'
                        filename = os.path.join('upload/',upload_file.name)
                        saveFile(upload_file,filename)

                        with open(filename,'r') as f:
                            line = f.read().split()

                        if poc == "test":
                            poc_instance = test(line,input_payload)

                        poc_t = Thread(target=run_test,args=(poc_instance,))
                        poc_t.start()

                        result = poc_instance.get_data()
</code>```

Suppose I have a test class that returns a response after url requests and sends it back to the front-end template, but since the thread is running in the background, I can't use get_data to return the result of the response, what can I do to solve this problem?

```<code>class test:

    def __init__(self,ip,payload):
        self.ip = ip
        self.payload = payload
        self.result = []

    def entry(self):
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
        }
        url = "https://xxxxx.com"
        res = requests.get(url=url,headers=headers,verify=False,proxies=proxies)

    def get_data(self):
        return self.result
</code>```

I tried not to use thread when calling the class, but this causes the current user to use it while other users have to wait, so I have to use multi-thread to call the class, but this in turn causes the result that my front-end cannot receive the response

Body:
I now have a function in views.py that determines the user input options and uses multi-threaded new a class

views.py

try:
poc_instance = None

                upload_file = request.FILES['file']
                ext = upload_file.name.split('.')[-1]
                poc = request.POST.get('poc_list')
                input_payload = request.POST.get('input_payload')

                if upload_file.size != 0 and poc != "" and input_payload != "":
                    if ext in ['txt']:
                        uuid_str = uuid.uuid4().hex
                        upload_file.name = uuid_str + '.txt'
                        filename = os.path.join('upload/',upload_file.name)
                        saveFile(upload_file,filename)

                        with open(filename,'r') as f:
                            line = f.read().split()

                        if poc == "test":
                            poc_instance = test(line,input_payload)

                        poc_t = Thread(target=run_test,args=(poc_instance,))
                        poc_t.start()

                        result = poc_instance.get_data()

Suppose I have a test class that returns a response after url requests and sends it back to the front-end template, but since the thread is running in the background, I can't use get_data to return the result of the response, what can I do to solve this problem?

class test:

    def __init__(self,ip,payload):
        self.ip = ip
        self.payload = payload
        self.result = []

    def entry(self):
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
        }
        url = "https://xxxxx.com"
        res = requests.get(url=url,headers=headers,verify=False,proxies=proxies)

    def get_data(self):
        return self.result

I tried not to use thread when calling the class, but this causes the current user to use it while other users have to wait, so I have to use multi-thread to call the class, but this in turn causes the result that my front-end cannot receive the response


问:
Modified AR(1) model in Python
It is $ X_t = \frac{S_t^{\alpha}-1}{\alpha} $

How can i analyse the process: $$ X_t = b + \phi X_{t-1} + \sigma^{1/2} \epsilon_t $$ in Python, where $ S_t $ is a datapoint at time $ t $.
Im using the statsmodel and fit with Autoreg.

mod = AutoReg(dataframe[], 1, old_names=False)
res = mod.fit()
```

How can I modify these frameworks by including the formula of $X_t$?

Title: Modified AR(1) model in Python

Body:
It is $ X_t = \frac{S_t^{\alpha}-1}{\alpha} $

How can i analyse the process: $$ X_t = b + \phi X_{t-1} + \sigma^{1/2} \epsilon_t $$ in Python, where $ S_t $ is a datapoint at time $ t $.
Im using the statsmodel and fit with Autoreg.

mod = AutoReg(dataframe[], 1, old_names=False)
res = mod.fit()

How can I modify these frameworks by including the formula of $X_t$?


问:
Why won't the scheduler execute at the specified time?
I don't understand why my scheduler won't execute the task at the given time when running php artisan schedule:work.  Anyone know what the issue could be?  For reference, I'm in the EST timezone.

Kernel.php

```<code>protected function schedule(Schedule $schedule)
{
    $schedule->command('weekly:winners')->timezone('America/New_York')->weeklyOn(2, '08:53');
}

public function scheduleTimezone()
{
    return 'America/New_York';
}
</code>```

app.php

```<code>'timezone' => 'UTC'
</code>```

Body:
I don't understand why my scheduler won't execute the task at the given time when running php artisan schedule:work.  Anyone know what the issue could be?  For reference, I'm in the EST timezone.

Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('weekly:winners')->timezone('America/New_York')->weeklyOn(2, '08:53');
}

public function scheduleTimezone()
{
    return 'America/New_York';
}

app.php

'timezone' => 'UTC'


问:
How to fix issues with wrong layer order for a custom waterfall plot in Python?
So I found a custom script to make a waterfall plot from a dataframe, which I customized for my purposes. When I run the function for small number of columns, each layer plots accordingly with the subsequent plot properly placed behind the previous plot. When I keep including a larger number of the columns, it starts plotting subsequent plots over the previous ones.

I tried using PolyCollections, and LineCollections and I can't seem to fix this. Is it a bug? Is there a work-around?

```<code>def waterfall(X, numTrials):

  # Function to generate formats for facecolors
  cc = lambda arg: colorConverter.to_rgba(arg, alpha=1)
  # This is just wrong. There must be some way to use the meshgrid or why bother.
  verts = []
  for i in np.arange(numTrials)+1:
    verts.append(list(zip(X['Time'].values, X['Trial #'+str(i)].values)))

  xmin = np.floor(np.min(X['Time'].values))
  xmax = np.ceil(np.max(X['Time'].values))
  ymin = -1
  ymax = numTrials+1
  zmin = np.floor(np.min(X.drop(columns=['Time']).values))
  zmax = np.ceil(np.max(X.drop(columns=['Time']).values))

  fig=plt.figure()
  fig.set_size_inches(15,10)
  ax = Axes3D(fig)

  poly = PolyCollection(verts,closed='True',edgecolors=[cc('k')],facecolors=[cc('w')])
  ax.add_collection3d(poly, zs=np.arange(numTrials)+1, zdir='y')
  ax.set_xlim(xmin,xmax)
  ax.set_ylim(ymin,ymax)
  ax.set_zlim(zmin,zmax)
  ax.view_init(25, -110)
  plt.show()

for x in np.arange(5,100,20):
  waterfall(CRresponse, x)
</code>```

This is an example of a proper output, for low number of columns:
enter image description here

This is an example of a messed up output for higher number of columns:
enter image description here

Thank you for any help on the matter, and I appreciate your patience for a first time poster

Body:
So I found a custom script to make a waterfall plot from a dataframe, which I customized for my purposes. When I run the function for small number of columns, each layer plots accordingly with the subsequent plot properly placed behind the previous plot. When I keep including a larger number of the columns, it starts plotting subsequent plots over the previous ones.

I tried using PolyCollections, and LineCollections and I can't seem to fix this. Is it a bug? Is there a work-around?

def waterfall(X, numTrials):

  # Function to generate formats for facecolors
  cc = lambda arg: colorConverter.to_rgba(arg, alpha=1)
  # This is just wrong. There must be some way to use the meshgrid or why bother.
  verts = []
  for i in np.arange(numTrials)+1:
    verts.append(list(zip(X['Time'].values, X['Trial #'+str(i)].values)))

  xmin = np.floor(np.min(X['Time'].values))
  xmax = np.ceil(np.max(X['Time'].values))
  ymin = -1
  ymax = numTrials+1
  zmin = np.floor(np.min(X.drop(columns=['Time']).values))
  zmax = np.ceil(np.max(X.drop(columns=['Time']).values))

  fig=plt.figure()
  fig.set_size_inches(15,10)
  ax = Axes3D(fig)

  poly = PolyCollection(verts,closed='True',edgecolors=[cc('k')],facecolors=[cc('w')])
  ax.add_collection3d(poly, zs=np.arange(numTrials)+1, zdir='y')
  ax.set_xlim(xmin,xmax)
  ax.set_ylim(ymin,ymax)
  ax.set_zlim(zmin,zmax)
  ax.view_init(25, -110)
  plt.show()

for x in np.arange(5,100,20):
  waterfall(CRresponse, x)

This is an example of a proper output, for low number of columns:
enter image description here

This is an example of a messed up output for higher number of columns:
enter image description here

Thank you for any help on the matter, and I appreciate your patience for a first time poster


问:
generate CoreML Encryption key when signed in with ANOTHER iCloud account
I have a mac where I am signed in with my own iCloud account. One of my projects is on a team to which I was granted access via a DIFFERENT apple id. I sign in to Xcode with that second account and everything works fine, I can see the apps in Organizer windows, upload archives, get distribution profiles and signing certificates etc. just fine.

Now I need to generate a CoreML encryption key (.mlmodelkey) file.

This is failing with the following error:

Failed to Generate Encryption Key

Sign in with your iCloud account in the System Preferences
and retry.

Now I don't actually want to do that because my mac is setup with my iCloud account.

Is there a way to generate mlmodelkey without signing out of my other iCloud account on macOS?

Here's a screenshot of that error message:


问:
djongo JSONField rename causes "Cannot alter field" error
I have a Django application with djongo as a database engine. There's a JSONField in one for the models:

```<code>my_field = JSONField(default=list)
</code>```

I modified the model and renamed my_field in Database like this

```<code>my_field = JSONField(default=list, db_column="myField")
</code>```

Now when I create migrations:

```<code>makemigrations
</code>```

I got an error:

```<code>ValueError: Cannot alter field my_app.MyModel.my_field into my_app.MyModel.my_field - they do not properly define db_type (are you using a badly-written custom field?)
</code>```

Djongo version: "^1.3.6"

Django version: "^4.1.1"

How to fix the error?

Body:
I have a Django application with djongo as a database engine. There's a JSONField in one for the models:

my_field = JSONField(default=list)

I modified the model and renamed my_field in Database like this

my_field = JSONField(default=list, db_column="myField")

Now when I create migrations:

makemigrations

I got an error:

ValueError: Cannot alter field my_app.MyModel.my_field into my_app.MyModel.my_field - they do not properly define db_type (are you using a badly-written custom field?)

Djongo version: "^1.3.6"

Django version: "^4.1.1"

How to fix the error?


问:
How to connect two brokers in nodejs?
I am creating a logic that preprocesses incoming data from mqtt broker A and then publishes it to broker B.

```<code>const client: MqttClientType = {
    publish: null,
    subscribe: null,
};
</code>```
```<code>const mqttClient = mqtt.connect(mqttConnectOptions);
</code>```

I created a new client by changing the Client ID and Broker ID of the Client Option.

However, I don't know if it's because only one mqtt library is used, but when the pub client is called, the sub's client information remains intact and published as a sub client.

This is part of the log.

```<code>{"level":30,"time":1673401661860,"pid":78,"hostname":"90489ad744e6","name":"maq-server","options":{"clientId":"maq-broker","host":"maq-broker","port":1883,"protocol":"mqtt","clean":true,"defaultProtocol":"mqtt","keepalive":60,"reschedulePings":true,"protocolId":"MQTT","protocolVersion":4,"reconnectPeriod":1000,"connectTimeout":30000,"resubscribe":true,"hostname":"main-broker"},"messageIdProvider":{"nextId":63626},"outgoingStore":{"options":{"clean":true},"_inflights":{}},"incomingStore":{"options":{"clean":true},"_inflights":{}},"queueQoSZero":true,"_resubscribeTopics":{}
</code>```

I want to be published as maq-broker, but main-broker information remains inside.

I've looked elsewhere, but I haven't found a case of using the broker client twice.

Each mqtt client is created as an intermediary and requests are made, but the client created first is called.

Title: How to connect two brokers in nodejs?

Body:
I am creating a logic that preprocesses incoming data from mqtt broker A and then publishes it to broker B.

const client: MqttClientType = {
    publish: null,
    subscribe: null,
};

const mqttClient = mqtt.connect(mqttConnectOptions);

I created a new client by changing the Client ID and Broker ID of the Client Option.

However, I don't know if it's because only one mqtt library is used, but when the pub client is called, the sub's client information remains intact and published as a sub client.

This is part of the log.

{"level":30,"time":1673401661860,"pid":78,"hostname":"90489ad744e6","name":"maq-server","options":{"clientId":"maq-broker","host":"maq-broker","port":1883,"protocol":"mqtt","clean":true,"defaultProtocol":"mqtt","keepalive":60,"reschedulePings":true,"protocolId":"MQTT","protocolVersion":4,"reconnectPeriod":1000,"connectTimeout":30000,"resubscribe":true,"hostname":"main-broker"},"messageIdProvider":{"nextId":63626},"outgoingStore":{"options":{"clean":true},"_inflights":{}},"incomingStore":{"options":{"clean":true},"_inflights":{}},"queueQoSZero":true,"_resubscribeTopics":{}

I want to be published as maq-broker, but main-broker information remains inside.

I've looked elsewhere, but I haven't found a case of using the broker client twice.

Each mqtt client is created as an intermediary and requests are made, but the client created first is called.


问:
How can I have multiple embeds with buttons receiving user interactions at the same time? (Discord py)
edit(update): thanks for the help, I'm just new to oop and cogs, so I have now made just one cog containing the quickpoll timer command, and regular class files for the Timer, NoMoreButtons, and QuickPollButtons classes. The only remaining thing I'm trying to understand is how to deal with the some_callback callback in the Timer class, because it needs to access the react_message(the one with the view), so that it can edit it to show the remaining time. Will update more soon

Hey all,
I'm brand new to stack overflow (first post) and also pretty new to discord py and coding in general. I made a /quickpoll cog for discord that contains an embeded message with two buttons attached (yes/no). One issue I've come across happens when I want to have two separate polls operating simultaneously. If I run /quickpoll twice to create two separate polls, the older poll's buttons are interacting with the newer poll. So no matter how many polls I create, the older poll's buttons will only apply to the newest poll.

Edit: How would you recommend going about solving this issue? Thanks in advance

Background info on the code:
Because I have the Timer class with a callback function that needs to access variables from the QuickPoll class (with the buttons), I made a few variables into QuickPoll class attributes (i.e. embededMsg, view, react_message).

Also, the NoMoreButtons class is just I used to make the buttons disappear once the poll timer ends.

Here's my cog (I deleted as much extraneous code as could. Apologies if its too long):

```<code>class QuickPoll(commands.Cog, discord.ui.View):
    def __init__(self, bot: commands.Bot):
        super().__init__(timeout=None)
        self.bot = bot
        self.value = None
        self.noCount = 0
        self.yesCount = 0
        self.userNamesOfAlreadyVoted = []
        self.embededMsg = None
        self.view = None
        self.react_message = None

    @app_commands.command(name="quickpoll", description="Creates a yes/no poll for others to vote on")
    @app_commands.describe(question='example: Yes or no?')
    @app_commands.describe(duration='seconds')
    async def quickpoll(self, interaction: discord.Interaction, question: str, duration: str):
            await interaction.response.send_message(content="Command received", ephemeral=True, delete_after=0)
            QuickPoll.view = QuickPoll(bot=commands.Bot)
            pprint(QuickPoll.view.id)
            QuickPoll.view.embededMsg = discord.Embed(type='rich', color=discord.Color.random(), title=question )
            QuickPoll.view.embededMsg.set_author(name=f'{interaction.user}\'s Poll')
            QuickPoll.view.embededMsg.add_field(name="Yes:", value=f"{QuickPoll.view.yesCount}", inline=True)
            QuickPoll.view.embededMsg.add_field(name='No:', value=f'{QuickPoll.view.noCount}', inline=True)
            QuickPoll.view.embededMsg.set_footer(text=f'Poll ID: {QuickPoll.view.id}')
            QuickPoll.view.react_message = await interaction.channel.send(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            timer1 = Timer(bot=commands.Bot, interval=5, first_immediately=True, timer_name="Timer 1", context={'count': (int(duration))}, callback=Timer.some_callback)

    @discord.ui.button(label="Yes", style=discord.ButtonStyle.green, custom_id='1')
    async def button1(self, interaction: discord.Interaction, button: discord.ui.Button):
        if f'{interaction.user.display_name}' not in self.userNamesOfAlreadyVoted:
            print(f"Voted Yes: {interaction.user}")
            QuickPoll.view.yesCount = QuickPoll.view.yesCount + 1
            self.userNamesOfAlreadyVoted += [f'{interaction.user.display_name}']
            QuickPoll.view.embededMsg.set_field_at(index=0,name="Yes:",value=f"{QuickPoll.view.yesCount}",inline=True)
            QuickPoll.view.embededMsg.set_field_at(index=3,name="Who has voted:",value=f"{', '.join(self.userNamesOfAlreadyVoted)}",inline=False)
            await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            await interaction.response.defer()
        else:
            await interaction.response.defer()

    @discord.ui.button(label="No", style=discord.ButtonStyle.red, custom_id='2')
    async def button2(self, interaction: discord.Interaction, button: discord.ui.Button ):
        if f'{interaction.user.display_name}' not in self.userNamesOfAlreadyVoted and QuickPoll.view.buttonIdJoin == QuickPoll.view.react_message.id:
            print(f"Voted No: {interaction.user}")
            QuickPoll.view.noCount = QuickPoll.view.noCount + 1
            self.userNamesOfAlreadyVoted += [f'{interaction.user.display_name}']
            QuickPoll.view.embededMsg.set_field_at(index=1,name="No:",value=f"{QuickPoll.view.noCount}",inline=True)
            QuickPoll.view.embededMsg.set_field_at(index=3,name="Who has voted:",value=f"{', '.join(self.userNamesOfAlreadyVoted)}",inline=False)
            await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            await interaction.response.defer()
        else:
            await interaction.response.defer()

class Timer(QuickPoll, commands.Cog):
    def __init__(self, bot: commands.Bot, interval, first_immediately, timer_name, context, callback):
        super().__init__(bot)
        self.bot = bot
        self._interval = interval
        self._first_immediately = first_immediately
        self._name = timer_name
        self._context = context
        self._callback = callback
        self._is_first_call = True
        self._ok = True
        self._task = asyncio.ensure_future(self._job())

    async def _job(self):
        try:
            while self._ok:
                if not self._is_first_call or not self._first_immediately:
                    await asyncio.sleep(self._interval)
                await self._callback(self._name, self._context, self)
                self._is_first_call = False
        except Exception as ex:
            print(ex)

    def cancel(self):
        self._ok = False
        self._task.cancel()

    async def some_callback(timer_name, context, timer):
        print('callback: ' + timer_name + ", count: ", context['count'])
        if context['count'] <= 0:
            print(f"Timer is up on the poll!")
            timer.cancel()
            QuickPoll.view.embededMsg.set_field_at(index=2,name="**Ends In:**",value="Ended!",inline=True)
            if QuickPoll.view.yesCount < QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"NO!!!!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
            if QuickPoll.view.yesCount > QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"YES!!!!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
            if QuickPoll.view.yesCount == QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"ITS A TIE!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
        context['count'] -= 5

class NoMoreButtons(commands.Cog, discord.ui.View):
    def __init__(self, bot: commands.Bot):
        super().__init__(timeout=None)
        self.bot = bot
</code>```

So far I've been trying to find some sort of ID or anything that the Bot's channel.send message shares with the buttons. I tried experimenting with the QuickPoll.view.id to get the actual id of the instance itself, but then I ran into the issue of the fact that when a button is pressed, it creates a brand new interaction id.

Any advice as to how to approach this problem would be much appreciated. Also feel free to (kindly please) critique my code (or even my question) if there is a better way to approach all of what I've done so far

Body:
edit(update): thanks for the help, I'm just new to oop and cogs, so I have now made just one cog containing the quickpoll timer command, and regular class files for the Timer, NoMoreButtons, and QuickPollButtons classes. The only remaining thing I'm trying to understand is how to deal with the some_callback callback in the Timer class, because it needs to access the react_message(the one with the view), so that it can edit it to show the remaining time. Will update more soon

Hey all,
I'm brand new to stack overflow (first post) and also pretty new to discord py and coding in general. I made a /quickpoll cog for discord that contains an embeded message with two buttons attached (yes/no). One issue I've come across happens when I want to have two separate polls operating simultaneously. If I run /quickpoll twice to create two separate polls, the older poll's buttons are interacting with the newer poll. So no matter how many polls I create, the older poll's buttons will only apply to the newest poll.

Edit: How would you recommend going about solving this issue? Thanks in advance

Background info on the code:
Because I have the Timer class with a callback function that needs to access variables from the QuickPoll class (with the buttons), I made a few variables into QuickPoll class attributes (i.e. embededMsg, view, react_message).

Also, the NoMoreButtons class is just I used to make the buttons disappear once the poll timer ends.

Here's my cog (I deleted as much extraneous code as could. Apologies if its too long):

class QuickPoll(commands.Cog, discord.ui.View):
    def __init__(self, bot: commands.Bot):
        super().__init__(timeout=None)
        self.bot = bot
        self.value = None
        self.noCount = 0
        self.yesCount = 0
        self.userNamesOfAlreadyVoted = []
        self.embededMsg = None
        self.view = None
        self.react_message = None

    @app_commands.command(name="quickpoll", description="Creates a yes/no poll for others to vote on")
    @app_commands.describe(question='example: Yes or no?')
    @app_commands.describe(duration='seconds')
    async def quickpoll(self, interaction: discord.Interaction, question: str, duration: str):
            await interaction.response.send_message(content="Command received", ephemeral=True, delete_after=0)
            QuickPoll.view = QuickPoll(bot=commands.Bot)
            pprint(QuickPoll.view.id)
            QuickPoll.view.embededMsg = discord.Embed(type='rich', color=discord.Color.random(), title=question )
            QuickPoll.view.embededMsg.set_author(name=f'{interaction.user}\'s Poll')
            QuickPoll.view.embededMsg.add_field(name="Yes:", value=f"{QuickPoll.view.yesCount}", inline=True)
            QuickPoll.view.embededMsg.add_field(name='No:', value=f'{QuickPoll.view.noCount}', inline=True)
            QuickPoll.view.embededMsg.set_footer(text=f'Poll ID: {QuickPoll.view.id}')
            QuickPoll.view.react_message = await interaction.channel.send(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            timer1 = Timer(bot=commands.Bot, interval=5, first_immediately=True, timer_name="Timer 1", context={'count': (int(duration))}, callback=Timer.some_callback)

    @discord.ui.button(label="Yes", style=discord.ButtonStyle.green, custom_id='1')
    async def button1(self, interaction: discord.Interaction, button: discord.ui.Button):
        if f'{interaction.user.display_name}' not in self.userNamesOfAlreadyVoted:
            print(f"Voted Yes: {interaction.user}")
            QuickPoll.view.yesCount = QuickPoll.view.yesCount + 1
            self.userNamesOfAlreadyVoted += [f'{interaction.user.display_name}']
            QuickPoll.view.embededMsg.set_field_at(index=0,name="Yes:",value=f"{QuickPoll.view.yesCount}",inline=True)
            QuickPoll.view.embededMsg.set_field_at(index=3,name="Who has voted:",value=f"{', '.join(self.userNamesOfAlreadyVoted)}",inline=False)
            await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            await interaction.response.defer()
        else:
            await interaction.response.defer()

    @discord.ui.button(label="No", style=discord.ButtonStyle.red, custom_id='2')
    async def button2(self, interaction: discord.Interaction, button: discord.ui.Button ):
        if f'{interaction.user.display_name}' not in self.userNamesOfAlreadyVoted and QuickPoll.view.buttonIdJoin == QuickPoll.view.react_message.id:
            print(f"Voted No: {interaction.user}")
            QuickPoll.view.noCount = QuickPoll.view.noCount + 1
            self.userNamesOfAlreadyVoted += [f'{interaction.user.display_name}']
            QuickPoll.view.embededMsg.set_field_at(index=1,name="No:",value=f"{QuickPoll.view.noCount}",inline=True)
            QuickPoll.view.embededMsg.set_field_at(index=3,name="Who has voted:",value=f"{', '.join(self.userNamesOfAlreadyVoted)}",inline=False)
            await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=QuickPoll.view)
            await interaction.response.defer()
        else:
            await interaction.response.defer()

class Timer(QuickPoll, commands.Cog):
    def __init__(self, bot: commands.Bot, interval, first_immediately, timer_name, context, callback):
        super().__init__(bot)
        self.bot = bot
        self._interval = interval
        self._first_immediately = first_immediately
        self._name = timer_name
        self._context = context
        self._callback = callback
        self._is_first_call = True
        self._ok = True
        self._task = asyncio.ensure_future(self._job())

    async def _job(self):
        try:
            while self._ok:
                if not self._is_first_call or not self._first_immediately:
                    await asyncio.sleep(self._interval)
                await self._callback(self._name, self._context, self)
                self._is_first_call = False
        except Exception as ex:
            print(ex)

    def cancel(self):
        self._ok = False
        self._task.cancel()

    async def some_callback(timer_name, context, timer):
        print('callback: ' + timer_name + ", count: ", context['count'])
        if context['count'] <= 0:
            print(f"Timer is up on the poll!")
            timer.cancel()
            QuickPoll.view.embededMsg.set_field_at(index=2,name="**Ends In:**",value="Ended!",inline=True)
            if QuickPoll.view.yesCount < QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"NO!!!!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
            if QuickPoll.view.yesCount > QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"YES!!!!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
            if QuickPoll.view.yesCount == QuickPoll.view.noCount:
                QuickPoll.view.embededMsg.add_field(name="Result: ", value=f"ITS A TIE!", inline=True)
                await QuickPoll.view.react_message.edit(content="", embed=QuickPoll.view.embededMsg, view=NoMoreButtons(bot=commands.Bot))
        context['count'] -= 5

class NoMoreButtons(commands.Cog, discord.ui.View):
    def __init__(self, bot: commands.Bot):
        super().__init__(timeout=None)
        self.bot = bot

So far I've been trying to find some sort of ID or anything that the Bot's channel.send message shares with the buttons. I tried experimenting with the QuickPoll.view.id to get the actual id of the instance itself, but then I ran into the issue of the fact that when a button is pressed, it creates a brand new interaction id.

Any advice as to how to approach this problem would be much appreciated. Also feel free to (kindly please) critique my code (or even my question) if there is a better way to approach all of what I've done so far