问:
Show this custom text in one specific category
How to alter this custom text, so it will only be shown in one specific category, let's say: ONLY in category: tables?

add_action( 'woocommerce_after_shop_loop_item', 'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop() { ?>

✓ Meer varianten

    <?php
}
```
<p>in css:</p>
<pre class="lang-php prettyprint-override"><code>.products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}
</code>```

答:
You are using WooCommerce so check your body classes.
There should be some class that references that category like category_tables or term-01.

You can manage your CSS like this:

```<code>body:not(.category_tables) .products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}
</code>```

It's not the best option, but it's a quick and effective solution for those who don't know how to work with WP Functions.

Body:
How to alter this custom text, so it will only be shown in one specific category, let's say: ONLY in category: tables?

add_action( 'woocommerce_after_shop_loop_item', 'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop() { ?>

✓ Meer varianten

    <?php
}

in css:

.products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}

Body:
You are using WooCommerce so check your body classes.
There should be some class that references that category like category_tables or term-01.

You can manage your CSS like this:

body:not(.category_tables) .products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}

It's not the best option, but it's a quick and effective solution for those who don't know how to work with WP Functions.


来源: stackexchange

问:
I'm trying to get first 3 results from MySQL database in Node.js and I'm getting this error
Here's the code I'm using

```<code>con.query('SELECT * FROM tables', function(err, results) {
                if (err) throw err
                console.log(results[0].rawname)
                for(var i= 0; i <= 3; i++) {
                    eval("var " + 'name_' + i + ' = ' + "'" + results[i].rawname + "'" + ";")
                    eval("var " + 'url_' + i + ' = ' + "'" + results[i].url + "'" + ";")
                    eval("var " + 'creator_' + i + ' = ' + "'" + results[i].creator + "'" + ';' )
                }
</code>```

I'm getting this error:

TypeError: Cannot read property 'rawname' of undefined

Now I know it's a problem with the i variable since I tried logging it outside the loop with a 0 in the place of the i and it seems to work fine, how can I do it with the i variable?

答: You are counting from zero till 3 included. So you try to loop over 4 results instead of the intended 3 results.</p>

ContentLicense: CC BY-SA 4.0

Body:
Here's the code I'm using

con.query('SELECT * FROM tables', function(err, results) {
                if (err) throw err
                console.log(results[0].rawname)
                for(var i= 0; i <= 3; i++) {
                    eval("var " + 'name_' + i + ' = ' + "'" + results[i].rawname + "'" + ";")
                    eval("var " + 'url_' + i + ' = ' + "'" + results[i].url + "'" + ";")
                    eval("var " + 'creator_' + i + ' = ' + "'" + results[i].creator + "'" + ';' )
                }

I'm getting this error:

TypeError: Cannot read property 'rawname' of undefined

Now I know it's a problem with the i variable since I tried logging it outside the loop with a 0 in the place of the i and it seems to work fine, how can I do it with the i variable?


问:
[DART]- Check if a value exists in a list of objects
I've got an Abstract class named QuizzAnswer and I've a class named QuizzAnswerMCQ which extends QuizzAnswer class.

```<code>abstract class QuizzAnswer extends Equatable {}

 class QuizzAnswerMCQ extends QuizzAnswer {
  String optionId;
  bool isSelected;

 QuizzAnswerMCQ({required this.optionId, required this.isSelected});

   @override
   List<Object?> get props => [optionId, isSelected];

   Map<String, dynamic> toJson() => {
      "option_id": optionId,
       "is_selected": isSelected,
    };
 }
</code>```

and I've got a list which is of type QuizzAnswerMCQ

```<code>List<QuizzAnswerMCQ> quizAnswerList=[];
</code>```

and I add items to the list

```<code>quizAnswerList.add(QuizzAnswerMCQ(
      optionId: event.optionId, isSelected: event.optionValue));
</code>```

what I want to do is to check if the optionId is already there in the list or not so I wrote this,

```<code>if(quizAnswerList.map((item) => item.optionId).contains(event.optionId)){
    print ('EXISTTTTSSSSS');
  }else{
    print('DOESNT EXISTTTT');
  }
</code>```

Even though the optionId is there,I still get the output 'DOESNT EXISTTTT'.Please help!!!

答:
You can use firstWhere like this

```<code>result = quizAnswerList.firstWhere((item) => item.optionId == your_id);
</code>```

or checking from other List

```<code>result = quizAnswerList.firstWhere((item) => otherList.contains(item));
</code>```

then

```<code>    if(result.length > 0){
      print ('');
    }else{
      print(');
    }
</code>```

Official doc here

Body:
I've got an Abstract class named QuizzAnswer and I've a class named QuizzAnswerMCQ which extends QuizzAnswer class.

abstract class QuizzAnswer extends Equatable {}

 class QuizzAnswerMCQ extends QuizzAnswer {
  String optionId;
  bool isSelected;

 QuizzAnswerMCQ({required this.optionId, required this.isSelected});

   @override
   List<Object?> get props => [optionId, isSelected];

   Map<String, dynamic> toJson() => {
      "option_id": optionId,
       "is_selected": isSelected,
    };
 }

and I've got a list which is of type QuizzAnswerMCQ

List<QuizzAnswerMCQ> quizAnswerList=[];

and I add items to the list

quizAnswerList.add(QuizzAnswerMCQ(
      optionId: event.optionId, isSelected: event.optionValue));

what I want to do is to check if the optionId is already there in the list or not so I wrote this,

if(quizAnswerList.map((item) => item.optionId).contains(event.optionId)){
    print ('EXISTTTTSSSSS');
  }else{
    print('DOESNT EXISTTTT');
  }

Even though the optionId is there,I still get the output 'DOESNT EXISTTTT'.Please help!!!

Body:
You can use firstWhere like this

result = quizAnswerList.firstWhere((item) => item.optionId == your_id);

or checking from other List

result = quizAnswerList.firstWhere((item) => otherList.contains(item));

then

    if(result.length > 0){
      print ('');
    }else{
      print(');
    }

Official doc here


问:
c# editing sql table data without loosing the existing

Possible Duplicate:

  C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?

I have a sql datatable, and I don't want the users to delete or modify anything, they can only add new rows if they want.

My solution was to use datagridview to show the existing data, but I'm stuck, because I cannot deny editing or deleting without denying adding a new row, so this is not a good way. Otherwise using update method will override all the data the user has changed (later on maybe I can give overriding permissions for that).

I could make a read-only dgw to show the existing data, and allow the user to enter the new data one by one with textboxes, but that's a bigger work and maybe unnecessary.

Is there a simple way to allow adding new row without letting editing the existing data? Maybe manipulating the datatable?

Thank you.

答:
As an alternative you could provide the user with a new Form in order for them to add a new record like a lot of new forms. I liked the idea of a user being able to add a row to a DataGridView but in the end gave up fighting with it. You just have far easier control in a Form as opposed to a row in a DGV.

In answer to your question - Rather than fight the source, perhaps ask the DataGridView to officiate:

```<code>dataGridView1.DataSource = bs;
dataGridView1.ReadOnly = true;
dataGridView1.CurrentCellChanged += delegate
{
    DataGridViewRow row = dataGridView1.CurrentRow;
    bool readOnly = row == null ||
        row.Index != dataGridView1.NewRowIndex;
    dataGridView1.ReadOnly = readOnly;
};
</code>```

(and don't set AllowEdit on the list)

Source: C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?

ContentLicense: CC BY-SA 3.0

Body:
As an alternative you could provide the user with a new Form in order for them to add a new record like a lot of new forms. I liked the idea of a user being able to add a row to a DataGridView but in the end gave up fighting with it. You just have far easier control in a Form as opposed to a row in a DGV.

In answer to your question - Rather than fight the source, perhaps ask the DataGridView to officiate:

dataGridView1.DataSource = bs;
dataGridView1.ReadOnly = true;
dataGridView1.CurrentCellChanged += delegate
{
    DataGridViewRow row = dataGridView1.CurrentRow;
    bool readOnly = row == null ||
        row.Index != dataGridView1.NewRowIndex;
    dataGridView1.ReadOnly = readOnly;
};

(and don't set AllowEdit on the list)

Source: C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?


问:
Why are my firebase storage security rules are not enforcing and letting users upload images over the limit?
I have setup my storage security rules to only allow authenticated users to post images that are less than 3mb with the following rule:

```<code>rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
          // Only allow uploads of any image file that's less than 3MB
      allow write: if request.resource.size < 3 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

However, I just tested from my client and I was able to upload a picture that is 14mb. I have given plenty of time for security rules to set.

How did I bypass this rule?

答:
While the other answers provided you with security rules you could use, it’s also good to add that you can test your security rules using the Firebase rules playground. Using this tool, you can tell exactly the resolution of each of your rules when tested against an event (create, read, update, delete).

I tested your security rules and received this output:

As you can see, while your file size limit rule is working fine, the broader allow write: if request.auth != null; rule is still letting your request go through. This is what the other answers pointed out and what is included in the documentation:

If any of the “allow” rules for the method are satisfied, the request is allowed. Additionally, if a broader rule grants access, rules grant access and ignore any more granular rules that might limit access.

Body:
I have setup my storage security rules to only allow authenticated users to post images that are less than 3mb with the following rule:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
          // Only allow uploads of any image file that's less than 3MB
      allow write: if request.resource.size < 3 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
      allow read, write: if request.auth != null;
    }
  }
}

However, I just tested from my client and I was able to upload a picture that is 14mb. I have given plenty of time for security rules to set.

How did I bypass this rule?


问:
Auto run python scripts on pycharm while opening
I want to auto run the python script when I open it from the terminal so that I won't have to press the run button
From the terminal I want to open the file as :
pycharm-community main.py

How do I auto run it while it opens?

答:
Preferences > Tools > Startup Tasks, <+ Add> and select your main.py

Then anytime you open the project the script will run and display results.

I wanted main.py to run daily at a certain time, so used Keyboard Maestro. Keyboard Maestro is also able to control the running of main.py, eliminating the step above. That way my script runs only at the desired time of day, not every time I open the project.


问:
Use CoreMLTools to generate models for iOS 11/12
We have a model trained using Keras, using the MobileNetV2 architecture.

We can use CoreMLTools to convert from the .H5 file to a .MLModel CoreML model.

However, with latest CoreMLTools (5.x) the resulting model only runs on iOS 13 and later, but our app supports iOS 11.

Is there a way to generate a iOS 11/12 compatible model with latest CoreMLTools?

We thought of trying to install older CoreMLTools (like 2.x) but for other reasons have had dependency issues installing that. But it feels there should be a way to specify CoreML version when converting the model?

答:
I would highly recommend working through your version dependencies and get an older version of coremltools working. I understand the difficulty there but I promise you all other paths will be more difficult.

Now the good news. CoreML models are just protocol buffers that you can easily load and manipulate yourself without coremltools. I keep a compiled version of their protocol spec in a library just for these kinds of tasks. You can get the PB spec here: https://github.com/apple/coremltools/tree/f19052c7f113740069bfac7b0291c5c6c9571ca6/mlmodel/format

Load up your iOS 11 model in a PB viewer, load up the iOS 13 version, and remove everything in the 13 version that’s not in 11. :-)

Thankfully CoreML models are pretty simple and I can guess that there’s just one version flag set that you need to reset.


问:
Getting 1 testcase wrong using this method
There are three Hill Stations named A, B, and C. There are flights between each pair of Hill Stations. A one-way flight between the Hill Stations A and B (and vice versa) takes a hours, a one-way flight between Hill Stations B and C (and vice versa) takes b hours, a one-way flight between the Hill Stations C and A (and vice versa) takes c hours.

You are a tourist and you want to visit each of the hill stations exactly once. You can start at any of the stations. Find the minimum time taken to visit each Hill Station exactly once.

And this is the code I wrote:

from itertools import combinations
ipl = [int(i) for i in input().split()]
l = combinations(ipl,2)
for i in l:
    print(i)
print(sum(min(l)))
```

Can someone help me with the reason which leads me to get one test case wrong?

答:
This only works because there are only 3 cities
You don't need combinations.</p>
```<code>ipl = [int(i) for i in input().split()]
print(sorted(ipl)[:2])
</code>```

Body:
There are three Hill Stations named A, B, and C. There are flights between each pair of Hill Stations. A one-way flight between the Hill Stations A and B (and vice versa) takes a hours, a one-way flight between Hill Stations B and C (and vice versa) takes b hours, a one-way flight between the Hill Stations C and A (and vice versa) takes c hours.

You are a tourist and you want to visit each of the hill stations exactly once. You can start at any of the stations. Find the minimum time taken to visit each Hill Station exactly once.

And this is the code I wrote:

from itertools import combinations
ipl = [int(i) for i in input().split()]
l = combinations(ipl,2)
for i in l:
    print(i)
print(sum(min(l)))

Can someone help me with the reason which leads me to get one test case wrong?

Body:
This only works because there are only 3 cities
You don't need combinations.

ipl = [int(i) for i in input().split()]
print(sorted(ipl)[:2])


问:
Invalid public key when trying to upload a key for a service account using Python Google API client
I am using the Google API Explorer in Python to manage service accounts and push new keys. That would be the method documented here: https://developers.google.com/resources/api-libraries/documentation/iam/v1/python/latest/iam_v1.projects.serviceAccounts.keys.html#upload

After I generated a key following the required convention (X509_PEM format) I call the method upload() like in the sample below.

```<code>import googleapiclient.discovery
from google.oauth2 import service_account

if __name__ == "__main__":

    credentials = service_account.Credentials.from_service_account_file(
        filename="path/to/credentials.json",
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    iam_service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    public_key = "-----BEGIN CERTIFICATE-----\nMIIFDDCCAvQCCQD3eTyPcnYUejANBgkqhkiG9w0BAQUFADBIMUYwRAYDVQQDDD10\nYW5ndXktYWJlbC1zYUBhaWdueC10ZXN0LWNsb3VkLXNldHVwLmlhbS5nc2Vydmlj\nZWFjY291bnQuY29tMB4XDTIyMDIwOTE2MzkyMFoXDTIzMDIwOTE2MzkyMFowSDFG\nMEQGA1UEAww9dGFuZ3V5LWFiZWwtc2FAYWlnbngtdGVzdC1jbG91ZC1zZXR1cC5p\nYW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\nAgoCggIBAJimPN7VYTGikobRD6E29crjdKgB1H3uSh+ViHHGLVjuwMtBVafXeiEB\nBAes/IXWUCOosLOG0HKi253+xqZAAleX5g9zFOvUMjhpdJydCVLOxVEs6EfjgikD\nU8eiaUJig4sO6VWMFLxELOkMPmKfQN8ASE0ZG/j20tez4/Refo5YqN3Fkt6WNeiO\nrQ69KpcGRGPgpo1oT0TViopkeQD+yNBfesXrrPpGYfzQxGKFzkVE5zTRiIBRAAhf\nrjfZnLK1rOUPp8ZMfrapZja5xT4sL7Ug2fKVtmULtJK5k9X36bpY6JbwTSPhyi/m\ncLw49XOpqfoBe03fxQJMes8VH1dwifBRi5wL2Q0s6Kq6s9ZFT3aWAO6WP+l1pVMA\nB605edOjgauMsdc/0Fky+IOrwnGTrAyekEfxb7zd1yr9t4d5x/WYQlRnhp9JjuS6\nvA5ZGmtn2NaqADWSJ4MuVY7j6Fn9WWQVokRnyb3DgbqhaDuLHN3H6wbgA8U+k0ou\nmEwOx4VllDkGzFw9xfZdU8jDJu7uM+00s/MHxX30wzdJwnWspBFIpmHhaQQOp2D6\nbsggo1Lzn4Xe94ozrhG6mFaoLopL+2SpjBK3LO1L3zMiH65VK3K/CDxZdrBfT5CC\nkOJzcBNQxc8a3bQFauZQ9ZAbx1/bFtALXYF/tDNwYh4TUAJuWj01AgMBAAEwDQYJ\nKoZIhvcNAQEFBQADggIBAHq9SlyKIJwEy5okpXBpKPm7oq+W4Sud7eQNoq+Vg95f\nr4R0crHjayj3GaFF5IC1NSq2WRoPqMVZ76uFHRZwnGTOqjIyty4fq8NSe7HJ2jak\nRdKBBdnxND+VJrsx8ACGA+GZcNw/s5huekduD22iU3dkDYhERDZUHHcTlakoJxTO\ndOpLcTzPtTcGOn/cerIpHS2Sdb05qnUicDuOCuD6sz7KufLAEzjKPfve7S7sUtGq\n7aqaGjZpR3xf5LkmQCYKwuaFoK3Vz96l3MgHzf2+dxezcDTfUnwU48es04PObasE\noeTlRGvlhkP2QZdlXaXcOZ83sDhgoYcqqaf2EoUm/ycYJ1QjKMw+mlCawx7I4HFi\n1cDt+xQXOlzI/0eEKhNSM7Vh7wZtzsedga5Pye+i3FqxK/tdoa3jCDmwLdoNps+W\nyrf7JdzSYqHILVSYt3CiUzKsgpyvtK/GDrhHsrIZM2oLQK+4auRSOrfW5x13v9pk\nlTUlkLEW0F3V5dhiToccYX+d/WG2pKEB/at8MSwTAvj/ZLhD7Q0oqrpAVSP0K4Lo\nhSkTRJov3fyWWfrsEsg7BEWy9iCJYbymy8NupFf6VJxBFdcME9F/pPI18v0hKa8T\nmA1ZcJLjPsZE0zmXtDfozlmZIXT2/wP+BKV8p2Rt7dZToMdBLbHc3wL3B9CpoiAM\n-----END CERTIFICATE-----"

    iam_service.projects().serviceAccounts().keys().upload(
        name="projects/my-cloud-project/serviceAccounts/my-sa@my-cloud-project.iam.gserviceaccount.com",
        body={
            "publicKeyData": public_key
        }).execute()
</code>```

This call returns the following error:

```<code><HttpError 400 when requesting https://iam.googleapis.com/v1/projects/aignx-test-cloud-setup/serviceAccounts/tanguy-abel-sa@aignx-test-cloud-setup.iam.gserviceaccount.com/keys:upload?alt=json returned "Invalid value at 'public_key_data' (TYPE_BYTES), Base64 decoding failed for public_key = "-----BEGIN CERTIFICATE-----\nMIIFDDCCAvQCCQD3eTyPcnYUejANBgkqhkiG9w0BAQUFADBIMUYwRAYDVQQDDD10\nYW5ndXktYWJlbC1zYUBhaWdueC10ZXN0LWNsb3VkLXNldHVwLmlhbS5nc2Vydmlj\nZWFjY291bnQuY29tMB4XDTIyMDIwOTE2MzkyMFoXDTIzMDIwOTE2MzkyMFowSDFG\nMEQGA1UEAww9dGFuZ3V5LWFiZWwtc2FAYWlnbngtdGVzdC1jbG91ZC1zZXR1cC5p\nYW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\nAgoCggIBAJimPN7VYTGikobRD6E29crjdKgB1H3uSh+ViHHGLVjuwMtBVafXeiEB\nBAes/IXWUCOosLOG0HKi253+xqZAAleX5g9zFOvUMjhpdJydCVLOxVEs6EfjgikD\nU8eiaUJig4sO6VWMFLxELOkMPmKfQN8ASE0ZG/j20tez4/Refo5YqN3Fkt6WNeiO\nrQ69KpcGRGPgpo1oT0TViopkeQD+yNBfesXrrPpGYfzQxGKFzkVE5zTRiIBRAAhf\nrjfZnLK1rOUPp8ZMfrapZja5xT4sL7Ug2fKVtmULtJK5k9X36bpY6JbwTSPhyi/m\ncLw49XOpqfoBe03fxQJMes8VH1dwifBRi5wL2Q0s6Kq6s9ZFT3aWAO6WP+l1pVMA\nB605edOjgauMsdc/0Fky+IOrwnGTrAyekEfxb7zd1yr9t4d5x/WYQlRnhp9JjuS6\nvA5ZGmtn2NaqADWSJ4MuVY7j6Fn9WWQVokRnyb3DgbqhaDuLHN3H6wbgA8U+k0ou\nmEwOx4VllDkGzFw9xfZdU8jDJu7uM+00s/MHxX30wzdJwnWspBFIpmHhaQQOp2D6\nbsggo1Lzn4Xe94ozrhG6mFaoLopL+2SpjBK3LO1L3zMiH65VK3K/CDxZdrBfT5CC\nkOJzcBNQxc8a3bQFauZQ9ZAbx1/bFtALXYF/tDNwYh4TUAJuWj01AgMBAAEwDQYJ\nKoZIhvcNAQEFBQADggIBAHq9SlyKIJwEy5okpXBpKPm7oq+W4Sud7eQNoq+Vg95f\nr4R0crHjayj3GaFF5IC1NSq2WRoPqMVZ76uFHRZwnGTOqjIyty4fq8NSe7HJ2jak\nRdKBBdnxND+VJrsx8ACGA+GZcNw/s5huekduD22iU3dkDYhERDZUHHcTlakoJxTO\ndOpLcTzPtTcGOn/cerIpHS2Sdb05qnUicDuOCuD6sz7KufLAEzjKPfve7S7sUtGq\n7aqaGjZpR3xf5LkmQCYKwuaFoK3Vz96l3MgHzf2+dxezcDTfUnwU48es04PObasE\noeTlRGvlhkP2QZdlXaXcOZ83sDhgoYcqqaf2EoUm/ycYJ1QjKMw+mlCawx7I4HFi\n1cDt+xQXOlzI/0eEKhNSM7Vh7wZtzsedga5Pye+i3FqxK/tdoa3jCDmwLdoNps+W\nyrf7JdzSYqHILVSYt3CiUzKsgpyvtK/GDrhHsrIZM2oLQK+4auRSOrfW5x13v9pk\nlTUlkLEW0F3V5dhiToccYX+d/WG2pKEB/at8MSwTAvj/ZLhD7Q0oqrpAVSP0K4Lo\nhSkTRJov3fyWWfrsEsg7BEWy9iCJYbymy8NupFf6VJxBFdcME9F/pPI18v0hKa8T\nmA1ZcJLjPsZE0zmXtDfozlmZIXT2/wP+BKV8p2Rt7dZToMdBLbHc3wL3B9CpoiAM\n-----END CERTIFICATE-----"".
</code>```

I am able to upload the same certificate using the gcloud cli:

```<code>gcloud iam service-accounts keys upload certificate.pem  --iam-account my-cloud-project@my-cloud-project.iam.gserviceaccount.com  --project my-cloud-project --format json
</code>```

I tried to adjust the format of the key I send within the payload in my Python code, but nothing goes through; I tried to strip the line breaks, with and without the wrapper. The documentation I linked above does not specify the excepted format in the payload. This documentation seems to describe the same format as the one I use: https://cloud.google.com/iot/docs/concepts/device-security#public_key_format

Any idea how I could fix my call? Thanks!

答:
After analysing the payload sent by the gcloud command, I understood that the field publicKeyData must be base64-encoded. When looking at the error this actually makes sense. So that simply fixed it:

```<code>import base64
...

iam_service.projects().serviceAccounts().keys().upload(
        name="projects/my-cloud-project/serviceAccounts/my-sa@my-cloud-project.iam.gserviceaccount.com",
        body={
            "publicKeyData": base64.b64encode(public_key.encode("utf-8")).decode("utf-8")
        }).execute()
</code>```

Note that the string is encoded, base64-encoded, then decoded again to be sent as a string and not bytes.

Body:
I am using the Google API Explorer in Python to manage service accounts and push new keys. That would be the method documented here: https://developers.google.com/resources/api-libraries/documentation/iam/v1/python/latest/iam_v1.projects.serviceAccounts.keys.html#upload

After I generated a key following the required convention (X509_PEM format) I call the method upload() like in the sample below.

import googleapiclient.discovery
from google.oauth2 import service_account

if __name__ == "__main__":

    credentials = service_account.Credentials.from_service_account_file(
        filename="path/to/credentials.json",
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    iam_service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    public_key = "-----BEGIN CERTIFICATE-----\nMIIFDDCCAvQCCQD3eTyPcnYUejANBgkqhkiG9w0BAQUFADBIMUYwRAYDVQQDDD10\nYW5ndXktYWJlbC1zYUBhaWdueC10ZXN0LWNsb3VkLXNldHVwLmlhbS5nc2Vydmlj\nZWFjY291bnQuY29tMB4XDTIyMDIwOTE2MzkyMFoXDTIzMDIwOTE2MzkyMFowSDFG\nMEQGA1UEAww9dGFuZ3V5LWFiZWwtc2FAYWlnbngtdGVzdC1jbG91ZC1zZXR1cC5p\nYW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\nAgoCggIBAJimPN7VYTGikobRD6E29crjdKgB1H3uSh+ViHHGLVjuwMtBVafXeiEB\nBAes/IXWUCOosLOG0HKi253+xqZAAleX5g9zFOvUMjhpdJydCVLOxVEs6EfjgikD\nU8eiaUJig4sO6VWMFLxELOkMPmKfQN8ASE0ZG/j20tez4/Refo5YqN3Fkt6WNeiO\nrQ69KpcGRGPgpo1oT0TViopkeQD+yNBfesXrrPpGYfzQxGKFzkVE5zTRiIBRAAhf\nrjfZnLK1rOUPp8ZMfrapZja5xT4sL7Ug2fKVtmULtJK5k9X36bpY6JbwTSPhyi/m\ncLw49XOpqfoBe03fxQJMes8VH1dwifBRi5wL2Q0s6Kq6s9ZFT3aWAO6WP+l1pVMA\nB605edOjgauMsdc/0Fky+IOrwnGTrAyekEfxb7zd1yr9t4d5x/WYQlRnhp9JjuS6\nvA5ZGmtn2NaqADWSJ4MuVY7j6Fn9WWQVokRnyb3DgbqhaDuLHN3H6wbgA8U+k0ou\nmEwOx4VllDkGzFw9xfZdU8jDJu7uM+00s/MHxX30wzdJwnWspBFIpmHhaQQOp2D6\nbsggo1Lzn4Xe94ozrhG6mFaoLopL+2SpjBK3LO1L3zMiH65VK3K/CDxZdrBfT5CC\nkOJzcBNQxc8a3bQFauZQ9ZAbx1/bFtALXYF/tDNwYh4TUAJuWj01AgMBAAEwDQYJ\nKoZIhvcNAQEFBQADggIBAHq9SlyKIJwEy5okpXBpKPm7oq+W4Sud7eQNoq+Vg95f\nr4R0crHjayj3GaFF5IC1NSq2WRoPqMVZ76uFHRZwnGTOqjIyty4fq8NSe7HJ2jak\nRdKBBdnxND+VJrsx8ACGA+GZcNw/s5huekduD22iU3dkDYhERDZUHHcTlakoJxTO\ndOpLcTzPtTcGOn/cerIpHS2Sdb05qnUicDuOCuD6sz7KufLAEzjKPfve7S7sUtGq\n7aqaGjZpR3xf5LkmQCYKwuaFoK3Vz96l3MgHzf2+dxezcDTfUnwU48es04PObasE\noeTlRGvlhkP2QZdlXaXcOZ83sDhgoYcqqaf2EoUm/ycYJ1QjKMw+mlCawx7I4HFi\n1cDt+xQXOlzI/0eEKhNSM7Vh7wZtzsedga5Pye+i3FqxK/tdoa3jCDmwLdoNps+W\nyrf7JdzSYqHILVSYt3CiUzKsgpyvtK/GDrhHsrIZM2oLQK+4auRSOrfW5x13v9pk\nlTUlkLEW0F3V5dhiToccYX+d/WG2pKEB/at8MSwTAvj/ZLhD7Q0oqrpAVSP0K4Lo\nhSkTRJov3fyWWfrsEsg7BEWy9iCJYbymy8NupFf6VJxBFdcME9F/pPI18v0hKa8T\nmA1ZcJLjPsZE0zmXtDfozlmZIXT2/wP+BKV8p2Rt7dZToMdBLbHc3wL3B9CpoiAM\n-----END CERTIFICATE-----"

    iam_service.projects().serviceAccounts().keys().upload(
        name="projects/my-cloud-project/serviceAccounts/my-sa@my-cloud-project.iam.gserviceaccount.com",
        body={
            "publicKeyData": public_key
        }).execute()

This call returns the following error:

<HttpError 400 when requesting https://iam.googleapis.com/v1/projects/aignx-test-cloud-setup/serviceAccounts/tanguy-abel-sa@aignx-test-cloud-setup.iam.gserviceaccount.com/keys:upload?alt=json returned "Invalid value at 'public_key_data' (TYPE_BYTES), Base64 decoding failed for public_key = "-----BEGIN CERTIFICATE-----\nMIIFDDCCAvQCCQD3eTyPcnYUejANBgkqhkiG9w0BAQUFADBIMUYwRAYDVQQDDD10\nYW5ndXktYWJlbC1zYUBhaWdueC10ZXN0LWNsb3VkLXNldHVwLmlhbS5nc2Vydmlj\nZWFjY291bnQuY29tMB4XDTIyMDIwOTE2MzkyMFoXDTIzMDIwOTE2MzkyMFowSDFG\nMEQGA1UEAww9dGFuZ3V5LWFiZWwtc2FAYWlnbngtdGVzdC1jbG91ZC1zZXR1cC5p\nYW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\nAgoCggIBAJimPN7VYTGikobRD6E29crjdKgB1H3uSh+ViHHGLVjuwMtBVafXeiEB\nBAes/IXWUCOosLOG0HKi253+xqZAAleX5g9zFOvUMjhpdJydCVLOxVEs6EfjgikD\nU8eiaUJig4sO6VWMFLxELOkMPmKfQN8ASE0ZG/j20tez4/Refo5YqN3Fkt6WNeiO\nrQ69KpcGRGPgpo1oT0TViopkeQD+yNBfesXrrPpGYfzQxGKFzkVE5zTRiIBRAAhf\nrjfZnLK1rOUPp8ZMfrapZja5xT4sL7Ug2fKVtmULtJK5k9X36bpY6JbwTSPhyi/m\ncLw49XOpqfoBe03fxQJMes8VH1dwifBRi5wL2Q0s6Kq6s9ZFT3aWAO6WP+l1pVMA\nB605edOjgauMsdc/0Fky+IOrwnGTrAyekEfxb7zd1yr9t4d5x/WYQlRnhp9JjuS6\nvA5ZGmtn2NaqADWSJ4MuVY7j6Fn9WWQVokRnyb3DgbqhaDuLHN3H6wbgA8U+k0ou\nmEwOx4VllDkGzFw9xfZdU8jDJu7uM+00s/MHxX30wzdJwnWspBFIpmHhaQQOp2D6\nbsggo1Lzn4Xe94ozrhG6mFaoLopL+2SpjBK3LO1L3zMiH65VK3K/CDxZdrBfT5CC\nkOJzcBNQxc8a3bQFauZQ9ZAbx1/bFtALXYF/tDNwYh4TUAJuWj01AgMBAAEwDQYJ\nKoZIhvcNAQEFBQADggIBAHq9SlyKIJwEy5okpXBpKPm7oq+W4Sud7eQNoq+Vg95f\nr4R0crHjayj3GaFF5IC1NSq2WRoPqMVZ76uFHRZwnGTOqjIyty4fq8NSe7HJ2jak\nRdKBBdnxND+VJrsx8ACGA+GZcNw/s5huekduD22iU3dkDYhERDZUHHcTlakoJxTO\ndOpLcTzPtTcGOn/cerIpHS2Sdb05qnUicDuOCuD6sz7KufLAEzjKPfve7S7sUtGq\n7aqaGjZpR3xf5LkmQCYKwuaFoK3Vz96l3MgHzf2+dxezcDTfUnwU48es04PObasE\noeTlRGvlhkP2QZdlXaXcOZ83sDhgoYcqqaf2EoUm/ycYJ1QjKMw+mlCawx7I4HFi\n1cDt+xQXOlzI/0eEKhNSM7Vh7wZtzsedga5Pye+i3FqxK/tdoa3jCDmwLdoNps+W\nyrf7JdzSYqHILVSYt3CiUzKsgpyvtK/GDrhHsrIZM2oLQK+4auRSOrfW5x13v9pk\nlTUlkLEW0F3V5dhiToccYX+d/WG2pKEB/at8MSwTAvj/ZLhD7Q0oqrpAVSP0K4Lo\nhSkTRJov3fyWWfrsEsg7BEWy9iCJYbymy8NupFf6VJxBFdcME9F/pPI18v0hKa8T\nmA1ZcJLjPsZE0zmXtDfozlmZIXT2/wP+BKV8p2Rt7dZToMdBLbHc3wL3B9CpoiAM\n-----END CERTIFICATE-----"".

I am able to upload the same certificate using the gcloud cli:

gcloud iam service-accounts keys upload certificate.pem  --iam-account my-cloud-project@my-cloud-project.iam.gserviceaccount.com  --project my-cloud-project --format json

I tried to adjust the format of the key I send within the payload in my Python code, but nothing goes through; I tried to strip the line breaks, with and without the wrapper. The documentation I linked above does not specify the excepted format in the payload. This documentation seems to describe the same format as the one I use: https://cloud.google.com/iot/docs/concepts/device-security#public_key_format

Any idea how I could fix my call? Thanks!

Body:
After analysing the payload sent by the gcloud command, I understood that the field publicKeyData must be base64-encoded. When looking at the error this actually makes sense. So that simply fixed it:

import base64
...

iam_service.projects().serviceAccounts().keys().upload(
        name="projects/my-cloud-project/serviceAccounts/my-sa@my-cloud-project.iam.gserviceaccount.com",
        body={
            "publicKeyData": base64.b64encode(public_key.encode("utf-8")).decode("utf-8")
        }).execute()

Note that the string is encoded, base64-encoded, then decoded again to be sent as a string and not bytes.


问:
Redshift drop user with special character
I created by mistake in Redshift the user mario.maria and I'm struggling to drop it.

Usual syntax would be

```<code>drop user mario.maria
</code>```

for which I get [42601] ERROR: syntax error at or near ".". So I try

```<code>drop user "mario.maria"
</code>```

to escape the special character . but then I get [42704] ERROR: User "mario.maria" does not exist.

So here I'm asking what is the right syntax to drop user with special characters (e.g. .) in their name?

答:
A solution that worked for me in the past was to run the query from the Redshift Query Editor with double-quotes so:

```<code>drop user "mario.maria"
</code>```

Running it from my local SQL Client (DataGrip) didn't work and raised the reported issue.

Body:
I created by mistake in Redshift the user mario.maria and I'm struggling to drop it.

Usual syntax would be

drop user mario.maria

for which I get [42601] ERROR: syntax error at or near ".". So I try

drop user "mario.maria"

to escape the special character . but then I get [42704] ERROR: User "mario.maria" does not exist.

So here I'm asking what is the right syntax to drop user with special characters (e.g. .) in their name?

Body:
A solution that worked for me in the past was to run the query from the Redshift Query Editor with double-quotes so:

drop user "mario.maria"

Running it from my local SQL Client (DataGrip) didn't work and raised the reported issue.


问:
How can I grant privilege's for file formats?
I'm trying to grant privileges for file formats in an automated way, I just need to basic structure in how to do so. Based on the research I've done so far I think it should look like this:

```<code>GRANT ALL PRIVILEGES ON myformat IN mydb.myschema TO myrole;
</code>```

But I'm getting an error. Any help would be appreciated.

Error : "SQL compilation error: syntax error line 1 at position 34 unexpected 'in'."

thanks

答:
You need to use the following syntax</p>
```<code>GRANT ALL PRIVILEGES ON FILE FORMAT mydb.myschema.myformat TO myrole;

</code>```

Body:
I'm trying to grant privileges for file formats in an automated way, I just need to basic structure in how to do so. Based on the research I've done so far I think it should look like this:

GRANT ALL PRIVILEGES ON myformat IN mydb.myschema TO myrole;

But I'm getting an error. Any help would be appreciated.

Error : "SQL compilation error: syntax error line 1 at position 34 unexpected 'in'."

thanks

Body:
You need to use the following syntax

GRANT ALL PRIVILEGES ON FILE FORMAT mydb.myschema.myformat TO myrole;


问:
How to map a PostgreSQL view with Panache in Quarkus
I want to map an entity to an existing PostgreSQL view on my DB. This article explains how to do it with Hibernate and it seems pretty straightforward: add @Immutable to the entity and make sure sur @Table name match the view name.

So, here is my entity in Panache :

```<code>@Entity
@Immutable
@Table(name = "test_view")
public class TestView extends PanacheEntityBase {

  @Id
  public Long id;

  @ManyToOne
  @JoinColumn(name = "other_test_view_id")
  public OtherTestView otherTestView;

}
</code>```

This actually works, and I can get my views data without any problem. But it looks like Panache is ignoring the @Immutable annotation, because if I start my Quarkus app with this parameter :

```<code>quarkus.hibernate-orm.database.generation=update
</code>```

then I get this error :

```<code>Error executing DDL "alter table if exists test_view add constraint FKs1taqbpciifj90ycsy164ofpw foreign key (other_test_view_id) references other_test_view"
</code>```

Which makes me think Quarkus is actually treating my Entity as any other, and not as a view. If it were treating it as a view, it should not try to alter a table.

答:
The @SubSelect annotation works and the table is ignored by Panache when creating/updating the db schema :

```<code>@Entity
@Immutable
@SubSelect(select * from test_view)
@Table(name = "test_view")
public class TestView extends PanacheEntityBase {

  @Id
  public Long id;

  @ManyToOne
  @JoinColumn(name = "other_test_view_id")
  public OtherTestView otherTestView;

}

</code>```

Body:
I want to map an entity to an existing PostgreSQL view on my DB. This article explains how to do it with Hibernate and it seems pretty straightforward: add @Immutable to the entity and make sure sur @Table name match the view name.

So, here is my entity in Panache :

@Entity
@Immutable
@Table(name = "test_view")
public class TestView extends PanacheEntityBase {

  @Id
  public Long id;

  @ManyToOne
  @JoinColumn(name = "other_test_view_id")
  public OtherTestView otherTestView;

}

This actually works, and I can get my views data without any problem. But it looks like Panache is ignoring the @Immutable annotation, because if I start my Quarkus app with this parameter :

quarkus.hibernate-orm.database.generation=update

then I get this error :

Error executing DDL "alter table if exists test_view add constraint FKs1taqbpciifj90ycsy164ofpw foreign key (other_test_view_id) references other_test_view"

Which makes me think Quarkus is actually treating my Entity as any other, and not as a view. If it were treating it as a view, it should not try to alter a table.

Body:
The @SubSelect annotation works and the table is ignored by Panache when creating/updating the db schema :

@Entity
@Immutable
@SubSelect(select * from test_view)
@Table(name = "test_view")
public class TestView extends PanacheEntityBase {

  @Id
  public Long id;

  @ManyToOne
  @JoinColumn(name = "other_test_view_id")
  public OtherTestView otherTestView;

}


问:
How to update local tags to match remote?
I fixed it for my repo by deleting the local tag and then doing a git fetch. This brought the updated tag.

Is there are "right" way to update tags that may have changed on the remote? This is a simple tag, not signed or anything, created with "git tag "

答:
Short cheat sheet with example below for tag XTAGX and commit ID 339f42b to whom, who are using tags only to mark specific commits for yourself (it might be okay to do re-tagging) and not for an opened to wide audience releases. Otherwise it is not good idea and @dannysauer already put a link with great explanation and use case.

```<code>remove locally: git tag -d XTAGX
remove on remote: git push -d origin XTAGX
create locally: git tag -a XTAGX -m "My XTAGX git tag" 339f42b
push to remote: git push origin --tags
list locally: git tags --list
list on remote: git ls-remote --tags origin
additional check to see tags in all history: git log --oneline
</code>```

Good reference with explanations: https://stackoverflow.com/a/5480292/2957102

Body:
Short cheat sheet with example below for tag XTAGX and commit ID 339f42b to whom, who are using tags only to mark specific commits for yourself (it might be okay to do re-tagging) and not for an opened to wide audience releases. Otherwise it is not good idea and @dannysauer already put a link with great explanation and use case.

remove locally: git tag -d XTAGX
remove on remote: git push -d origin XTAGX
create locally: git tag -a XTAGX -m "My XTAGX git tag" 339f42b
push to remote: git push origin --tags
list locally: git tags --list
list on remote: git ls-remote --tags origin
additional check to see tags in all history: git log --oneline

Good reference with explanations: https://stackoverflow.com/a/5480292/2957102


问:
C# Rotate a Polygon(Triangle)
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

```<code>Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);
</code>```

Thanks in advance.

答:
http://msdn.microsoft.com/en-us/library/s0s56wcf.aspx#Y609

```<code>public void RotateExample(PaintEventArgs e)
{
    Pen myPen = new Pen(Color.Blue, 1);
    Pen myPen2 = new Pen(Color.Red, 1);

    // Draw the rectangle to the screen before applying the transform.
    e.Graphics.DrawRectangle(myPen, 150, 50, 200, 100);

    // Create a matrix and rotate it 45 degrees.
    Matrix myMatrix = new Matrix();
    myMatrix.Rotate(45, MatrixOrder.Append);

    // Draw the rectangle to the screen again after applying the

    // transform.
    e.Graphics.Transform = myMatrix;
    e.Graphics.DrawRectangle(myPen2, 150, 50, 200, 100);
}
</code>```

You can use TransformPoints method of Matrix class to just rotate the points

Title: C# Rotate a Polygon(Triangle)

Body:
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);

Thanks in advance.

Body:
http://msdn.microsoft.com/en-us/library/s0s56wcf.aspx#Y609

public void RotateExample(PaintEventArgs e)
{
    Pen myPen = new Pen(Color.Blue, 1);
    Pen myPen2 = new Pen(Color.Red, 1);

    // Draw the rectangle to the screen before applying the transform.
    e.Graphics.DrawRectangle(myPen, 150, 50, 200, 100);

    // Create a matrix and rotate it 45 degrees.
    Matrix myMatrix = new Matrix();
    myMatrix.Rotate(45, MatrixOrder.Append);

    // Draw the rectangle to the screen again after applying the

    // transform.
    e.Graphics.Transform = myMatrix;
    e.Graphics.DrawRectangle(myPen2, 150, 50, 200, 100);
}

You can use TransformPoints method of Matrix class to just rotate the points


问:
Multiple Section Hide & Show with HTML & CSS
I have html button that show/hide the inner sections (Not main section) of my page, I have main section inside main section I five inner sections the details of problem and goals are mentioned in detail with code in below.

1. Details about my goal

I want to achieve the hide/show event on the same (single button) without changing its label when user click the button all inner sections should be hidden on the page and again when the user click same button it should show all sections including the one have html button.

2. Expected and actual results

Expected results is same as my goal above and actual result in my code is not giving the idea to put the all 5 section to hide.

What I have tried so far

document.getElementById("Ayat-3").classList.add("hide-section");
document.getElementById("Ayat-4").classList.add("hide-section");
document.getElementById("Ayat-5").classList.add("hide-section");
document.getElementById("Ayat-6").classList.add("hide-section");
document.getElementById("Ayat-7").classList.add("hide-section");

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');
  section.forEach(el => el.classList.toggle('d-none'));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button {
  color: white;
  background-color: green;
  padding: 12px;
  font-size: 14px;
  width: 25px;
  height: 25px;
  border: 5px;
  border-color: blue;
  cursor: pointer;
  border-radius: 150px;
}

.button:hover,
.button:focus {
  background-color: white;
}

.d-none {
  .display: none;
}</code>```

<button onclick="toggleHide()">Hide/Show Sections</button>```

4. Errors that I am facing

In the above code there is error to hide all mentioned five sections and click on first time its hiding only three sections and same when click second time the different three sections being hidden, i want to hide all five and show up all on second click.

答:
Here is the final working code, I expected some help from the experts here to identify the errors but anyways its done now.</p>
```<code> <!DOCTYPE html>
<html>

<button id="Mybutton" onclick='hideSections()'>[1:2]</button>

<style>
#Mybutton  {
    background-color: green;
    color: white;
    width: 50px;
    text-align: center;
    border-radius: 8px;
    height: 35px;
    border-style: solid;
    border-color: blue;
    border-width: 1px;

}

#Mybutton:hover {
    background-color: grey;

}

.hide {
  display: none;
}

.hideWithOpacity {
  visibility: hidden;
  opacity: 0;
}

.section {
  margin: 10px;
  padding: 10px;
  border: 1px dashed red;
  max-width: 150px;
  transition: all .3s linear;
}

</style>

<section id="Ayat-1"></section>
<section id="Ayat-2"></section>
<section id="Ayat-3"></section>
<section id="Ayat-4"></section>
<section id="Ayat-5"></section>
<section id="Ayat-6"></section>
<section id="Ayat-7"></section>

<script>

    function hideSections() {
  const otherSections = document.querySelectorAll('[id^=Ayat-]:not(#Ayat-2)')

  otherSections.forEach((section) => section.classList.toggle('hide'))
}

</script>

</html>
</code>```

Body:
I have html button that show/hide the inner sections (Not main section) of my page, I have main section inside main section I five inner sections the details of problem and goals are mentioned in detail with code in below.

1. Details about my goal

I want to achieve the hide/show event on the same (single button) without changing its label when user click the button all inner sections should be hidden on the page and again when the user click same button it should show all sections including the one have html button.

2. Expected and actual results

Expected results is same as my goal above and actual result in my code is not giving the idea to put the all 5 section to hide.

What I have tried so far

document.getElementById("Ayat-3").classList.add("hide-section");
document.getElementById("Ayat-4").classList.add("hide-section");
document.getElementById("Ayat-5").classList.add("hide-section");
document.getElementById("Ayat-6").classList.add("hide-section");
document.getElementById("Ayat-7").classList.add("hide-section");

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');
  section.forEach(el => el.classList.toggle('d-none'));
}

#button {
  color: white;
  background-color: green;
  padding: 12px;
  font-size: 14px;
  width: 25px;
  height: 25px;
  border: 5px;
  border-color: blue;
  cursor: pointer;
  border-radius: 150px;
}

.button:hover,
.button:focus {
  background-color: white;
}

.d-none {
  .display: none;
}

<button onclick="toggleHide()">Hide/Show Sections</button>

4. Errors that I am facing

In the above code there is error to hide all mentioned five sections and click on first time its hiding only three sections and same when click second time the different three sections being hidden, i want to hide all five and show up all on second click.

Body:
Here is the final working code, I expected some help from the experts here to identify the errors but anyways its done now.

 <!DOCTYPE html>
<html>

<button id="Mybutton" onclick='hideSections()'>[1:2]</button>

<style>
#Mybutton  {
    background-color: green;
    color: white;
    width: 50px;
    text-align: center;
    border-radius: 8px;
    height: 35px;
    border-style: solid;
    border-color: blue;
    border-width: 1px;

}

#Mybutton:hover {
    background-color: grey;

}

.hide {
  display: none;
}

.hideWithOpacity {
  visibility: hidden;
  opacity: 0;
}

.section {
  margin: 10px;
  padding: 10px;
  border: 1px dashed red;
  max-width: 150px;
  transition: all .3s linear;
}

</style>

<section id="Ayat-1"></section>
<section id="Ayat-2"></section>
<section id="Ayat-3"></section>
<section id="Ayat-4"></section>
<section id="Ayat-5"></section>
<section id="Ayat-6"></section>
<section id="Ayat-7"></section>

<script>

    function hideSections() {
  const otherSections = document.querySelectorAll('[id^=Ayat-]:not(#Ayat-2)')

  otherSections.forEach((section) => section.classList.toggle('hide'))
}

</script>

</html>


问:
How to plot spheres in 3d with plotly (or another library)?
I am struggling with plotting something, that I thought should be really simple. I have a dataframe/table df that contains the coordinates x,y,z of spheres. Additionally, in a separate column, it contains the radius of these spheres. How can I make with plotly a 3d plot of the spheres in space with their correct radius being used?

The closest I have come to making this plot reality is this code:

```<code>import plotly.express as px
import plotly.graph_objects as go

x =y=z = np.arange(1,4)

fig = go.Figure()
fig.add_trace(go.Scatter3d(
        mode='markers',
        x=x,
        y=y,
        z=z,
        marker=dict(color=px.colors.qualitative.D3,size=[50, 5, 25],sizemode='diameter'
        )
    )
)
</code>```

This produces almost what I want (see below), but notice that the sizes of the spheres are not correct - the ratios between the sphere sizes are correct, but I want size to provide the absolute size of the spheres in the plot. How can I make this plot work with plotly (or worst case with another library)? Tnx!

答:
Based on azelcer's answer I managed to produce the following code that plots spheres with plotly:

```<code>import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

def ms(x, y, z, radius, resolution=20):
    """Return the coordinates for plotting a sphere centered at (x,y,z)"""
    u, v = np.mgrid[0:2*np.pi:resolution*2j, 0:np.pi:resolution*1j]
    X = radius * np.cos(u)*np.sin(v) + x
    Y = radius * np.sin(u)*np.sin(v) + y
    Z = radius * np.cos(v) + z
    return (X, Y, Z)

df = pd.read_csv('xyzr_sphere_coordinates.txt')

data = []
for index, row in df.iterrows():
    (x_pns_surface, y_pns_surface, z_pns_suraface) = ms(row.x, row.y, row.z, row.r)
    data.append(go.Surface(x=x_pns_surface, y=y_pns_surface, z=z_pns_suraface, opacity=0.5))

fig = go.Figure(data=data)
fig.show()
</code>```

It leads to this 3d interactive figure:

Body:
I am struggling with plotting something, that I thought should be really simple. I have a dataframe/table df that contains the coordinates x,y,z of spheres. Additionally, in a separate column, it contains the radius of these spheres. How can I make with plotly a 3d plot of the spheres in space with their correct radius being used?

The closest I have come to making this plot reality is this code:

import plotly.express as px
import plotly.graph_objects as go

x =y=z = np.arange(1,4)

fig = go.Figure()
fig.add_trace(go.Scatter3d(
        mode='markers',
        x=x,
        y=y,
        z=z,
        marker=dict(color=px.colors.qualitative.D3,size=[50, 5, 25],sizemode='diameter'
        )
    )
)

This produces almost what I want (see below), but notice that the sizes of the spheres are not correct - the ratios between the sphere sizes are correct, but I want size to provide the absolute size of the spheres in the plot. How can I make this plot work with plotly (or worst case with another library)? Tnx!

Body:
Based on azelcer's answer I managed to produce the following code that plots spheres with plotly:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

def ms(x, y, z, radius, resolution=20):
    """Return the coordinates for plotting a sphere centered at (x,y,z)"""
    u, v = np.mgrid[0:2*np.pi:resolution*2j, 0:np.pi:resolution*1j]
    X = radius * np.cos(u)*np.sin(v) + x
    Y = radius * np.sin(u)*np.sin(v) + y
    Z = radius * np.cos(v) + z
    return (X, Y, Z)

df = pd.read_csv('xyzr_sphere_coordinates.txt')

data = []
for index, row in df.iterrows():
    (x_pns_surface, y_pns_surface, z_pns_suraface) = ms(row.x, row.y, row.z, row.r)
    data.append(go.Surface(x=x_pns_surface, y=y_pns_surface, z=z_pns_suraface, opacity=0.5))

fig = go.Figure(data=data)
fig.show()

It leads to this 3d interactive figure:


问:
How to access the files in bin/debug within the project folder in Visual studio 2010?
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

```<code> WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();
</code>```

Please Guide me to put correct valid path to access docx.xsl file...

答:
Application.StartupPath gives you the full path upto bin/debug.

So what you need to do is:

```<code>string xsltFile =Application.StartupPath + @"\\docx.xsl";
</code>```

Body:
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

 WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();

Please Guide me to put correct valid path to access docx.xsl file...

Body:
Application.StartupPath gives you the full path upto bin/debug.

So what you need to do is:

string xsltFile =Application.StartupPath + @"\\docx.xsl";


问:
Can't access the website via Postman but on chrome without any issue
Problem 1: (resolved - Thanks @Ranjith Thangaraju)

I tried to access this website via postman, but I can't do this because I got an error: https://i.stack.imgur.com/Dmfj8.png

Then when I try to access it on chrome - there's no restriction at all - I can access it: https://finance.vietstock.vn/

Could someone please help me to explain or help with this?

I'm sorry if someone else had the same issue and it is fixed, if you see some other similar, please point me the direction on that

Problem 2:

When I access this page [https://finance.vietstock.vn/CEO/phan-tich-ky-thuat.htm],
there is one of the APIs that I've tried to call from the postman but I couldn't, could you please point me a solution for this?

Chrome: https://i.stack.imgur.com/RTfsM.png

Postman: https://i.stack.imgur.com/2P2Qe.png

答:
Go to Headers -> Click on Bulk Edit

Add the Following Lines

Host: finance.vietstock.vn

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Then Hit Send!! ;)


答:
You need use the three-part qualifier instead of IN. You also need to specify that it's a file format, otherwise it will complain that it can't find the table with that name.</p>
```<code>GRANT ALL PRIVILEGES ON FILE FORMAT mydb.myschema.myformat TO myrole;
</code>```

Title: How can I grant privilege's for file formats?

Body:
You need use the three-part qualifier instead of IN. You also need to specify that it's a file format, otherwise it will complain that it can't find the table with that name.

GRANT ALL PRIVILEGES ON FILE FORMAT mydb.myschema.myformat TO myrole;


问:
In Twitter, how to filter the results of a list?
I have created a list - LL (for linguistics list) - containing 2 members :

languagelog (http://languagelog.ldc.upenn.edu/nll/)

languagehat (http://languagehat.comBut i

The list, of course, works fine. But suppose I would like to :

exclude languagelog's tweets containing "chinese"

include languagehat's tweets only if they contain "russian"

I know how to do that with one search operator :

```<code>(from:language log -chinese) OR (from:languagehat russian)
</code>```

but it seems it could be interesting to do that via lists, which would allow longer and more complex searches (it might even become a sort of substitute for yahoo pipes, although a very simple one).

Is it possible to include search operators in lists ?

Thanks in advance

答:
This is the correct search query for the separate accounts:

```<code>(from:languagehat OR from:languagelog) lang:ru -lang:zh
</code>```

If you'd like to do similar with a list:

create a Twitter list and add the accounts you need into it.

click on your list and copy the list ID from the browser's URL line the list ID.

in the query below, replace [list_id] with your copied list ID
list:[list_id] lang:ru -lang:zh

paste the query in Twitter's search box

Of course, as you suggested, you can build longer and more complex searches on that list.

Body:
I have created a list - LL (for linguistics list) - containing 2 members :

languagelog (http://languagelog.ldc.upenn.edu/nll/)

languagehat (http://languagehat.comBut i

The list, of course, works fine. But suppose I would like to :

exclude languagelog's tweets containing "chinese"

include languagehat's tweets only if they contain "russian"

I know how to do that with one search operator :

(from:language log -chinese) OR (from:languagehat russian)

but it seems it could be interesting to do that via lists, which would allow longer and more complex searches (it might even become a sort of substitute for yahoo pipes, although a very simple one).

Is it possible to include search operators in lists ?

Thanks in advance

Body:
This is the correct search query for the separate accounts:

(from:languagehat OR from:languagelog) lang:ru -lang:zh

If you'd like to do similar with a list:

create a Twitter list and add the accounts you need into it.

click on your list and copy the list ID from the browser's URL line the list ID.

in the query below, replace [list_id] with your copied list ID
list:[list_id] lang:ru -lang:zh

paste the query in Twitter's search box

Of course, as you suggested, you can build longer and more complex searches on that list.


问:
PhoneGap issue with returning to the application
I have developed an iphone App using Phonegap.Its working fine.One issue on my app, if i have visited any page in the App and return to the application menu, again i click the app icon it show the last visit page, not show the start up page.

Anybody know how i solve this isuue, Help is highly appreciated.

答:
I too faced the same issue. To start the App from start do this:

open your -info.plist.

Add 'Application does not run in background' to a field.

check the check box beside it.

Hope it helped you.

ContentLicense: CC BY-SA 2.5


问:
Get day of week using NSDate
I created a method that is supposed to take in a string in "YYYY-MM-DD" form and spit out an int that represents the dates position in relation to the week it is in (regardless if it overlaps between months). So e.g sunday=1 monday=2 and so on.

Here is my code:

```<code>    func getDayOfWeek(today:String)->Int{

    var formatter:NSDateFormatter = NSDateFormatter()
    formatter.dateFormat = "YYYY-MM-DD"
    var todayDate:NSDate = formatter.dateFromString(today)!
    var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
    var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate)
    var weekDay = myComponents.weekdayOrdinal
    return weekDay
}
</code>```

I know that NSCalendarUnit.WeekdayOrdinalCalendar is wrong but I have tried I think most logical combinations. And have also messed around with myComponents.weekdayOrdinal e.g used mycomponents.day or .weekday.

Here are my options in what to use:

```<code>static var EraCalendarUnit: NSCalendarUnit { get }
static var YearCalendarUnit: NSCalendarUnit { get }
static var MonthCalendarUnit: NSCalendarUnit { get }
static var DayCalendarUnit: NSCalendarUnit { get }
static var HourCalendarUnit: NSCalendarUnit { get }
static var MinuteCalendarUnit: NSCalendarUnit { get }
static var SecondCalendarUnit: NSCalendarUnit { get }
static var WeekCalendarUnit: NSCalendarUnit { get }
static var WeekdayCalendarUnit: NSCalendarUnit { get }
static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get }
static var QuarterCalendarUnit: NSCalendarUnit { get }
static var WeekOfMonthCalendarUnit: NSCalendarUnit { get }
static var WeekOfYearCalendarUnit: NSCalendarUnit { get }
static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get }
static var CalendarCalendarUnit: NSCalendarUnit { get }
static var TimeZoneCalendarUnit: NSCalendarUnit { get }
</code>```

It is not clear to me since there is no DayOfWeekUnit option (or something similar).

答:
```<code>extension Date {

    enum Weekday: CaseIterable {
        case sunday
        case monday
        case tuesday
        case wednesday
        case thursday
        case friday
        case saturday
    }

    var isWednesday: Bool { dayOfTheWeek == .wednesday } //

    var dayOfTheWeek: Date.Weekday {
        let dayNumber = Calendar.current.component(.weekday, from: self)
        return Weekday.allCases[dayNumber - 1]
    }
 }
</code>```

Title: Get day of week using NSDate

Body:
I created a method that is supposed to take in a string in "YYYY-MM-DD" form and spit out an int that represents the dates position in relation to the week it is in (regardless if it overlaps between months). So e.g sunday=1 monday=2 and so on.

Here is my code:

    func getDayOfWeek(today:String)->Int{

    var formatter:NSDateFormatter = NSDateFormatter()
    formatter.dateFormat = "YYYY-MM-DD"
    var todayDate:NSDate = formatter.dateFromString(today)!
    var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
    var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate)
    var weekDay = myComponents.weekdayOrdinal
    return weekDay
}

I know that NSCalendarUnit.WeekdayOrdinalCalendar is wrong but I have tried I think most logical combinations. And have also messed around with myComponents.weekdayOrdinal e.g used mycomponents.day or .weekday.

Here are my options in what to use:

static var EraCalendarUnit: NSCalendarUnit { get }
static var YearCalendarUnit: NSCalendarUnit { get }
static var MonthCalendarUnit: NSCalendarUnit { get }
static var DayCalendarUnit: NSCalendarUnit { get }
static var HourCalendarUnit: NSCalendarUnit { get }
static var MinuteCalendarUnit: NSCalendarUnit { get }
static var SecondCalendarUnit: NSCalendarUnit { get }
static var WeekCalendarUnit: NSCalendarUnit { get }
static var WeekdayCalendarUnit: NSCalendarUnit { get }
static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get }
static var QuarterCalendarUnit: NSCalendarUnit { get }
static var WeekOfMonthCalendarUnit: NSCalendarUnit { get }
static var WeekOfYearCalendarUnit: NSCalendarUnit { get }
static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get }
static var CalendarCalendarUnit: NSCalendarUnit { get }
static var TimeZoneCalendarUnit: NSCalendarUnit { get }

It is not clear to me since there is no DayOfWeekUnit option (or something similar).


问:
Synchronicity problem: Wait until multiple fs.readFile calls complete
I want to read columns from different CSV files, and combine those columns into an array. I'm using fs.readFile to read the CSV files and a callback which processes the data and pushed a new element onto the array of columns. This array of columns is then sent on to another part of the software (I'm building an electron app, so it's sent to the render process).

The issue I'm having is that 'fs.readFile' is asynchronous, so my columns array is sent off before any of the fs.readFile calls finish, resulting in an empty array.

What's the best way to solve this issue? It is to simply use fs.readFileSync? Is there a way to do it without blocking execution?

Minimal example code below:

```<code>//Process each column, reading the file and extracting the data one at a time
let columns: (number[] | undefined)[] = []; //Somewhere to store the processed columns
for (const dataHandle of dataHandles)
{
  //read the file as a raw string
  fs.readFile(dataHandle.filePath, (error: any, data: any) => {
    if (error) {
      console.log("Error reading file:", error);
    } else {
      data = data.toString();
      const newColumn = parseColumnFromStringDataframe(data, dataHandle.columnName);
      columns.push(newColumn);
    }
  })
}
//Finished processing each column, so send response.
//BUT... readfile is non-blocking! Sends the response before anything is pushed to columns! How can we wait in a smart way?
console.log(columns); // []
mainWindow?.webContents.send("readDataProductColumnsResponse", columns); //Sends response
</code>```

答:
This was answered here: https://stackoverflow.com/a/34642827/7603434

Basically you have to create an array of promises and then call Promise.all(promises);

const fs = require("fs");
const files = ["app.js", "index.html", "script.js"];

const readAllFiles = async () => {
  let promises = [];
  for (const f of files) {
    promises.push(fs.promises.readFile(f, "utf8"));
  }
  return Promise.all(promises);
};

async function run() {
  readAllFiles()
    .then((fileContents) => {
      console.log("done", fileContents);
      // fileContents is an array that contains all the file contents as strings
    })
    .catch((err) => {
      console.error(err);
    });
}

run();
```

Body:
I want to read columns from different CSV files, and combine those columns into an array. I'm using fs.readFile to read the CSV files and a callback which processes the data and pushed a new element onto the array of columns. This array of columns is then sent on to another part of the software (I'm building an electron app, so it's sent to the render process).

The issue I'm having is that 'fs.readFile' is asynchronous, so my columns array is sent off before any of the fs.readFile calls finish, resulting in an empty array.

What's the best way to solve this issue? It is to simply use fs.readFileSync? Is there a way to do it without blocking execution?

Minimal example code below:

//Process each column, reading the file and extracting the data one at a time
let columns: (number[] | undefined)[] = []; //Somewhere to store the processed columns
for (const dataHandle of dataHandles)
{
  //read the file as a raw string
  fs.readFile(dataHandle.filePath, (error: any, data: any) => {
    if (error) {
      console.log("Error reading file:", error);
    } else {
      data = data.toString();
      const newColumn = parseColumnFromStringDataframe(data, dataHandle.columnName);
      columns.push(newColumn);
    }
  })
}
//Finished processing each column, so send response.
//BUT... readfile is non-blocking! Sends the response before anything is pushed to columns! How can we wait in a smart way?
console.log(columns); // []
mainWindow?.webContents.send("readDataProductColumnsResponse", columns); //Sends response


问:
Swapping day and month for a date column in SQL
I need your help.
I would like to transform (re-calculate) a date column by randomly changing only the month and day and keeping only the year.
This task aims to anonymize the date of birth for certain people.

For example:
For this original date: '1996-07-04' to be '1996-12-01'. (let's say. it could be anything else instead of day and month).

OriginalDateBirth
AnonymDatebirth

1996-07-04
1996-12-01

1955-01-01
1955-04-09

Do you think you can help me with a sql statement, function that can implement it?

Thanks :)

答:
Here's one method you can try. This doesn't try to cater for varying days in a month but perhaps it might be "good enough" for your use-case.

(If you really wanted to cater for days 29-31 you could apply the months and then use a case expression on the result to control the mod value for the day)

```<code>with sampledata as (
  select Convert(date, '19960704') DOB union all
  select Convert(date, '19550101') DOB
)
select dob,
  DateFromParts( Year(dob), (Abs(Checksum(NewId())) % 12)+1, (Abs(Checksum(NewId())) % 28)+1) AnonDob,
from sampledata
</code>```

DB Fiddle

Body:
Here's one method you can try. This doesn't try to cater for varying days in a month but perhaps it might be "good enough" for your use-case.

(If you really wanted to cater for days 29-31 you could apply the months and then use a case expression on the result to control the mod value for the day)

with sampledata as (
  select Convert(date, '19960704') DOB union all
  select Convert(date, '19550101') DOB
)
select dob,
  DateFromParts( Year(dob), (Abs(Checksum(NewId())) % 12)+1, (Abs(Checksum(NewId())) % 28)+1) AnonDob,
from sampledata

DB Fiddle


问:
how to read large YAML file in golang?
Is there any memory-efficient way to read large YAML files in Golang, like is there any way to read YAML file in chunks in go lang

答: I used Viper. Worked well for me.</p>

Title: how to read large YAML file in golang?

Body: I used Viper. Worked well for me.


问:
Overlapping Rounded Rectangles causes error in FPDF
I am creating a PDF using the script 35 version of the Rounded rectangle function (Author: Christophe Prugnaud) and it works fine.

However, I require a filled rounded rectangle to be drawn inside an outline rounded rectangle and this causes an error e.g.

```<code>$this->pdf->RoundedRect($this->myleftmargin, $this->currenty, $this->mywidth, $totalheight, 8, '1234', 'D');
$this->pdf->RoundedRect($this->myleftmargin+2, $this->currenty+2, $this->mywidth-4, $totalheight-4, 8, '1234', 'DF');
</code>```

In investigating the problem I find that if the top and left edges move in, but the right and bottom do not, there is no problem.

```<code>$this->pdf->RoundedRect($this->myleftmargin, $this->currenty, $this->mywidth, $totalheight, 8, '1234', 'D');
$this->pdf->RoundedRect($this->myleftmargin+2, $this->currenty+2, $this->mywidth-2, $totalheight-2, 8, '1234', 'DF');
</code>```

Is this solvable?

=====

Addendum: This may not be the problem I thought it was, but it is still a problem. Running the code via Insomnia appears to return a PDF without problems - for either of the two sets of code above. BUT using the same URL via an Axios call (in Vue) causes an error in the first case but not in the second.

=====

Oliver (below), fairly, asked what the error is. Unfortunately I am not getting back anything useful for this. From the php error log I know that the problem is with the call ... $this->pdf->Output('a.pdf','I'); ... which create the error that a header has already been sent - but there is no other error before this in the log to know where that header is coming from. Logically the header must come from a error but (as you can see from the code) the difference in the working and failing code is just the value of a number.

答:
Whilst I don't know why the code that worked, worked ... I now have a generic solution. The problem was that the Yii2 code that the PDF code was part of was trying to return a header from the controller. So rather than...

```<code>$this->pdf->Output('I');
</code>```

which returned a PDF to Insomnia, used...

```<code>return Yii::$app->response->sendContentAsFile($this->pdf->Output('S'), 'a.pdf');
</code>```

which returned the data in a form that the axios call could then use to download.

Body:
I am creating a PDF using the script 35 version of the Rounded rectangle function (Author: Christophe Prugnaud) and it works fine.

However, I require a filled rounded rectangle to be drawn inside an outline rounded rectangle and this causes an error e.g.

$this->pdf->RoundedRect($this->myleftmargin, $this->currenty, $this->mywidth, $totalheight, 8, '1234', 'D');
$this->pdf->RoundedRect($this->myleftmargin+2, $this->currenty+2, $this->mywidth-4, $totalheight-4, 8, '1234', 'DF');

In investigating the problem I find that if the top and left edges move in, but the right and bottom do not, there is no problem.

$this->pdf->RoundedRect($this->myleftmargin, $this->currenty, $this->mywidth, $totalheight, 8, '1234', 'D');
$this->pdf->RoundedRect($this->myleftmargin+2, $this->currenty+2, $this->mywidth-2, $totalheight-2, 8, '1234', 'DF');

Is this solvable?

=====

Addendum: This may not be the problem I thought it was, but it is still a problem. Running the code via Insomnia appears to return a PDF without problems - for either of the two sets of code above. BUT using the same URL via an Axios call (in Vue) causes an error in the first case but not in the second.

=====

Oliver (below), fairly, asked what the error is. Unfortunately I am not getting back anything useful for this. From the php error log I know that the problem is with the call ... $this->pdf->Output('a.pdf','I'); ... which create the error that a header has already been sent - but there is no other error before this in the log to know where that header is coming from. Logically the header must come from a error but (as you can see from the code) the difference in the working and failing code is just the value of a number.

Body:
Whilst I don't know why the code that worked, worked ... I now have a generic solution. The problem was that the Yii2 code that the PDF code was part of was trying to return a header from the controller. So rather than...

$this->pdf->Output('I');

which returned a PDF to Insomnia, used...

return Yii::$app->response->sendContentAsFile($this->pdf->Output('S'), 'a.pdf');

which returned the data in a form that the axios call could then use to download.


问:
Unable to enable GD with JPEG support in PHP8 container running in Docker
Tried many ways, but still unable to get GD enabled with JPEG support in PHP8 container running in Docker. Here's the fragment of my Docker file:

```<code>FROM php:8.0.10-apache

RUN apt-get -y update && apt-get -y install \
apt-utils \
vim \
rsync \
curl \
openssl \
openssh-server \
mariadb-client \
git \
zlib1g-dev \
libicu-dev \
libfreetype6-dev \
libjpeg62-turbo-dev \
libzip-dev \
libpng-dev \
g++ \
zip \
unzip \
gnupg \
gnupg2 \
unixodbc-dev

RUN docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg
RUN docker-php-ext-install gd
</code>```

As you see the JPEG Support is missing. What am I missing here? Thanks!

答:
I'm using Nginx (not Apache like you) but ran into a similar issue with GD. I got GD running with jpg, png and webp by using the following lines:

```<code>FROM php:8.0-fpm-alpine

# Install dependencies for GD and install GD with support for jpeg, png webp and freetype
# Info about installing GD in PHP https://www.php.net/manual/en/image.installation.php
RUN apk add --no-cache \
        libjpeg-turbo-dev \
        libpng-dev \
        libwebp-dev \
        freetype-dev

# As of PHP 7.4 we don't need to add --with-png
RUN docker-php-ext-configure gd --with-jpeg --with-webp --with-freetype
RUN docker-php-ext-install gd
</code>```

Looking at your RUN apt-get statement, I noticed that you are using another libjpeg library: libjpeg62-turbo-dev \. Could you check if that is the correct version?
And/or try to change the name to libjpeg-turbo-dev \ (without the 62 in the name).

Body:
Tried many ways, but still unable to get GD enabled with JPEG support in PHP8 container running in Docker. Here's the fragment of my Docker file:

FROM php:8.0.10-apache

RUN apt-get -y update && apt-get -y install \
apt-utils \
vim \
rsync \
curl \
openssl \
openssh-server \
mariadb-client \
git \
zlib1g-dev \
libicu-dev \
libfreetype6-dev \
libjpeg62-turbo-dev \
libzip-dev \
libpng-dev \
g++ \
zip \
unzip \
gnupg \
gnupg2 \
unixodbc-dev

RUN docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg
RUN docker-php-ext-install gd

As you see the JPEG Support is missing. What am I missing here? Thanks!

Body:
I'm using Nginx (not Apache like you) but ran into a similar issue with GD. I got GD running with jpg, png and webp by using the following lines:

FROM php:8.0-fpm-alpine

# Install dependencies for GD and install GD with support for jpeg, png webp and freetype
# Info about installing GD in PHP https://www.php.net/manual/en/image.installation.php
RUN apk add --no-cache \
        libjpeg-turbo-dev \
        libpng-dev \
        libwebp-dev \
        freetype-dev

# As of PHP 7.4 we don't need to add --with-png
RUN docker-php-ext-configure gd --with-jpeg --with-webp --with-freetype
RUN docker-php-ext-install gd

Looking at your RUN apt-get statement, I noticed that you are using another libjpeg library: libjpeg62-turbo-dev \. Could you check if that is the correct version?
And/or try to change the name to libjpeg-turbo-dev \ (without the 62 in the name).


问:
Value Accessor issues on a radio button component
So I'm trying to make just a really simple and clean radio button component that can be used with value accessor to be used in the common angular forms scenarios with FormsModule, ReactiveFormsModule and using changeDetectionStrategy.OnPush but I've ran into the issue(s) you can see ON THIS Stackblitz where I'm getting unexpected results which I understand is probably me missing something since it's been a long time since I've done a custom radio.

When it first loads, you get the radio outlines but no labels until you click something and writeValue and onModelChange are undefined while I get a  No value accessor for form control with name: error. So could use another pair of eyes so I can use the instance with good 'ol ngModel, formControlName, FormBuilder.

You'll see in the Stackblitz the value accessor is there and implementing ControlValueAccessor so I'm a bit confused since I've done the same approach with another component recently just fine. I could copy/paste parts of the blitz here but figured the example should be enough however if not just let me know.

答:
I have made few changes to your code on Stackblitz, please check and let me know if it resolves your issue.

Below is the summary of the changes done:

Introduced a new RadioButtonComponent property named internalValue and used it to bind to [ngModel]. Also updating it's value within writeValue() method.

Commented the code within writeValue related to this.checked and manual update to input element's checked property. That should automatically be handled by Angular Forms API.

Within RadioButtonComponent html template removed [attr.checked] binding and instead of using attribute binding for name and value, simply used property binding.

In app.component.html instead of using property binding, used two-way binding [(ngModel)] syntax, so that the value gets reflected when you print it using ngModel: {{testing}}

You may change/tweak other things too, but hopefully the above changes will help you get going.


问:
Pyspark Cumulative sum within Partition for moving last 2 (N) rows
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

```<code>df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))
</code>```

答:
What you want is to sum the last 2 rows (current row included), so simply specify the rowsBetween like this:

```<code>from pyspark.sql import functions as F, Window

w = Window.partitionBy('Period').orderBy('Month').rowsBetween(-1, Window.currentRow)

df = df.withColumn('CustLast2', F.sum('Cust').over(w))
</code>```

You inverted the lower and upper bounds of the window frame in your attempt.

Body:
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))

Body:
What you want is to sum the last 2 rows (current row included), so simply specify the rowsBetween like this:

from pyspark.sql import functions as F, Window

w = Window.partitionBy('Period').orderBy('Month').rowsBetween(-1, Window.currentRow)

df = df.withColumn('CustLast2', F.sum('Cust').over(w))

You inverted the lower and upper bounds of the window frame in your attempt.


问:
CDI: 2 Producers with different qualifiers
I have 2 producer-methods, one has only 1 qualifier and one has 2 qualifiers, the one from the first producer and an additional one:

```<code>@ApplicationScoped
public class MyProducer {

  @Produces
  @Qualifier1
  MyBean produce1(InjectionPoint injectionPoint) {
    ...
  }

  @Produces
  @Qualifier1
  @Qualifier2
  MyBean produce2(InjectionPoint injectionPoint) {
    ...
  }
}
</code>```

If I try to @Inject MyBean with both qualifiers, everything works fine, produce2 is called. But when injecting MyBean with only @Qualifier1, I get an AmbiguousResolutionException. In my opinion, produce2 should only be called when injection point has both qualifiers. Why isn't that the case and what can I do to make it work?

Unfortunately I can not change producer-method 1, because it is in a library. The basic plan is to call my own producer if the injection point has my additional qualifier and if not, call the one from the library.

答:
I think the observed behavior is clearly specified in CDI 2.0, ch.2.3.4 "Specifying qualifiers of an injected field":

A bean may only be injected to an injection point if it has all the qualifiers of the injection point.

Assuming an injection point:

@Inject @Qualifier1 MyBean myBean;
```

Then the beans produced by both produce1 and produce1 "have all the qualifiers of the injection point", i.e. @Qualifier1, so both are eligible for injection there, resulting in the AmbiguousResolutionException.

In fact, the spec gives an example exactly as the one in the question in ch.2.3.6 "Repeating qualifiers".

So what can you do?

For starters, do you really need to qualify produce2 with @Qualifier1? If you have no good reason, just drop @Qualifier1 from produce2 and you are done - injection points with @Qualifier1 select MyBean from the library, injection points with @Qualifier2 select the one from your code. Your injection points cannot have both @Qualifier1 and @Qualifier2.

If you still want to inject MyBean from produce2 to injection points that have both @Qualifier1 and @Qualifier2, you can still do it [DISCLAIMER: Haven't actually tried this, it will probably need tweaking]. It's a bit more involved: You have to write a portable extension, which is not a hard thing at all. Brief implementation points:

The producer2 must be annotated ONLY with @Qualifier2

In you extension, observe the ProcessInjectionPoint event

If event.getInjectionPoint().getQualifiers() contains both @Qualifier1 and @Qualifier2

Use event.configureInjectionPoint().qualifiers(...) to remove @Qualifier1 from the set of qualifiers.

The effect is that you remove the @Qualifier1 when it is present together with @Qualifier2 at runtime.

Body:
I have 2 producer-methods, one has only 1 qualifier and one has 2 qualifiers, the one from the first producer and an additional one:

@ApplicationScoped
public class MyProducer {

  @Produces
  @Qualifier1
  MyBean produce1(InjectionPoint injectionPoint) {
    ...
  }

  @Produces
  @Qualifier1
  @Qualifier2
  MyBean produce2(InjectionPoint injectionPoint) {
    ...
  }
}

If I try to @Inject MyBean with both qualifiers, everything works fine, produce2 is called. But when injecting MyBean with only @Qualifier1, I get an AmbiguousResolutionException. In my opinion, produce2 should only be called when injection point has both qualifiers. Why isn't that the case and what can I do to make it work?

Unfortunately I can not change producer-method 1, because it is in a library. The basic plan is to call my own producer if the injection point has my additional qualifier and if not, call the one from the library.

Body:
I think the observed behavior is clearly specified in CDI 2.0, ch.2.3.4 "Specifying qualifiers of an injected field":

A bean may only be injected to an injection point if it has all the qualifiers of the injection point.

Assuming an injection point:

@Inject @Qualifier1 MyBean myBean;

Then the beans produced by both produce1 and produce1 "have all the qualifiers of the injection point", i.e. @Qualifier1, so both are eligible for injection there, resulting in the AmbiguousResolutionException.

In fact, the spec gives an example exactly as the one in the question in ch.2.3.6 "Repeating qualifiers".

So what can you do?

For starters, do you really need to qualify produce2 with @Qualifier1? If you have no good reason, just drop @Qualifier1 from produce2 and you are done - injection points with @Qualifier1 select MyBean from the library, injection points with @Qualifier2 select the one from your code. Your injection points cannot have both @Qualifier1 and @Qualifier2.

If you still want to inject MyBean from produce2 to injection points that have both @Qualifier1 and @Qualifier2, you can still do it [DISCLAIMER: Haven't actually tried this, it will probably need tweaking]. It's a bit more involved: You have to write a portable extension, which is not a hard thing at all. Brief implementation points:

The producer2 must be annotated ONLY with @Qualifier2

In you extension, observe the ProcessInjectionPoint event

If event.getInjectionPoint().getQualifiers() contains both @Qualifier1 and @Qualifier2

Use event.configureInjectionPoint().qualifiers(...) to remove @Qualifier1 from the set of qualifiers.

The effect is that you remove the @Qualifier1 when it is present together with @Qualifier2 at runtime.


问:
How to increase the tabindex in React ul-li search result?
I used ul li to implement search result:

```<code><ul className="search-result">
  <li tabindex="1">title here...</li>
  <li tabindex="2">title here...</li>
  <li tabindex="3">title here...</li>
.
.
.
</ul>
</code>```

and this is the style for each item:

```<code>.search-result{
 li:active, li:focuse {
  font-weight: bold;
  background: #f0f0f0;
 }
}
</code>```

but I'm trying to add a feature which client navigate between result items by using key-down or key-up buttons on the keyboard. but how can I access to current active tabindex in document to increase or decrease that by JavaScript and not tab button?

答:
Do you want to tab to each
 (search result) and use the up/down arrow keys to navigate through the list?

You have to be careful when using positive values for tabindex.  It should rarely be used because it changes the default browser focus order which most users are used to.  The default focus order is DOM order.  In your case, if you want the user to tab to each
 in order, you don't need a positive value for tabindex because your
 elements are already in the order you want them tabbed to.  Just set them all to 0.  A value of 0 means that the DOM element should be inserted into the tab order in the normal DOM order.

```<code><ul className="search-result">
  <li tabindex="0">title here...</li>
  <li tabindex="0">title here...</li>
  <li tabindex="0">title here...</li>
.
.
.
</ul>
</code>```

Now, having said that, elements should only have tabindex="0" if they are interactive elements. An
 is not normally an interactive element so it'll be confusing to tab to it.  What can the user do once they tab to the
?  Can they press enter or space to select it?  If the user can't interact with that element, then it should not be a tab stop.

Typically, the
 contains things that are interactive, such as links, buttons, checkboxes, etc.  Those elements are already tab stops by default and don't need a tabindex.

As far as using up/down arrow keys for navigation, again, you should only be able to arrow to elements that are interactive.  I normally have an onkeydown handler on the
 and it listens for the arrow keys and adjusts the tabindex for each item.  But I only do this when I want my entire list to be one tab stop and the user must arrow up/down to go between each list item.  In your case, it sounds like you want both behaviors which is why I asked the question at the beginning of my answer.

If the list is treated as one tab stop, then all
 elements will have a tabindex="-1" except for the
 that has focus.  It will have tabindex="0".  That way the user can tab to the list as a whole and the focus will go to the list item that last had focus.  The user can then up/down through the list.

When the user presses up/down, all you have to do is change tabindex from 0 to -1 for the currently focused list item and change tabindex from -1 to 0 for the list item you're moving focus to, and then call focus() on the newly focused element.

Body:
I used ul li to implement search result:

title here...

title here...

title here...

.
.
.

and this is the style for each item:

.search-result{
 li:active, li:focuse {
  font-weight: bold;
  background: #f0f0f0;
 }
}

but I'm trying to add a feature which client navigate between result items by using key-down or key-up buttons on the keyboard. but how can I access to current active tabindex in document to increase or decrease that by JavaScript and not tab button?

Body:
Do you want to tab to each <li> (search result) and use the up/down arrow keys to navigate through the list?

You have to be careful when using positive values for tabindex.  It should rarely be used because it changes the default browser focus order which most users are used to.  The default focus order is DOM order.  In your case, if you want the user to tab to each <li> in order, you don't need a positive value for tabindex because your <li> elements are already in the order you want them tabbed to.  Just set them all to 0.  A value of 0 means that the DOM element should be inserted into the tab order in the normal DOM order.

<ul className="search-result">
  <li tabindex="0">title here...</li>
  <li tabindex="0">title here...</li>
  <li tabindex="0">title here...</li>
.
.
.
</ul>

Now, having said that, elements should only have tabindex="0" if they are interactive elements. An <li> is not normally an interactive element so it'll be confusing to tab to it.  What can the user do once they tab to the <li>?  Can they press enter or space to select it?  If the user can't interact with that element, then it should not be a tab stop.

Typically, the <li> contains things that are interactive, such as links, buttons, checkboxes, etc.  Those elements are already tab stops by default and don't need a tabindex.

As far as using up/down arrow keys for navigation, again, you should only be able to arrow to elements that are interactive.  I normally have an onkeydown handler on the <ul> and it listens for the arrow keys and adjusts the tabindex for each item.  But I only do this when I want my entire list to be one tab stop and the user must arrow up/down to go between each list item.  In your case, it sounds like you want both behaviors which is why I asked the question at the beginning of my answer.

If the list is treated as one tab stop, then all <li> elements will have a tabindex="-1" except for the <li> that has focus.  It will have tabindex="0".  That way the user can tab to the list as a whole and the focus will go to the list item that last had focus.  The user can then up/down through the list.

When the user presses up/down, all you have to do is change tabindex from 0 to -1 for the currently focused list item and change tabindex from -1 to 0 for the list item you're moving focus to, and then call focus() on the newly focused element.


问:
How to return text with line break with Grape API?
I am trying to create an endpoint where the response body is just a string with line breaks, but the response keeps showing the \n character.

My endpoint code:

```<code>get '' do
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end
</code>```

And this is the response I see in Postman:

What am I missing here?

Thank you

答:
\n is a new line character for UNIX systems, and in RFC2046 is specified that new line characters in text/plain format should use \r\n (Windows style new line).

So In Your case server should return "Hello\r\nWorld"

For more verbose answer check this one here

Body:
I am trying to create an endpoint where the response body is just a string with line breaks, but the response keeps showing the \n character.

My endpoint code:

get '' do
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end

And this is the response I see in Postman:

What am I missing here?

Thank you


问:
Interaction between a single variable and a macro in Stata
I'm trying to run a regression with a bunch of interactions. Specifically, I have a macro and one interaction variable, but want the interaction variable to interact with everything in the macro.

So far, what I have looks like

```<code>local example "covariate1 covariate2"

reg outcome_var `example' `example'#interaction_var
</code>```

The problem is that

```<code>`example'#interaction_var
</code>```

only has interaction_var interacting with one of the covariates in example, but I want all the covariates interacted with. Is there a way to have an interaction term for every covariate in the macro?

EDIT: I've decided to go an alternate route, since a one-liner may not be possible. Namely, I'm trying to loop over the macro, where for each word in the macro, I interact it with the interaction variable and append it to a new, blank macro. So right now, this looks like

```<code>local ints ""
local len_e : word count $example
forval i=1/len_e{
    local e `:word `i' of `example''
    local ints $ints `e'#`int'
}
</code>```

but I'm getting an invalid syntax error.

答:
The thing to do is to add parentheses around the macro, i.e.

```<code>reg outcome_var `example' (`example')#interaction_var
</code>```

Then interaction_var interacts with everything inside example.

Body:
I'm trying to run a regression with a bunch of interactions. Specifically, I have a macro and one interaction variable, but want the interaction variable to interact with everything in the macro.

So far, what I have looks like

local example "covariate1 covariate2"

reg outcome_var `example' `example'#interaction_var

The problem is that

`example'#interaction_var

only has interaction_var interacting with one of the covariates in example, but I want all the covariates interacted with. Is there a way to have an interaction term for every covariate in the macro?

EDIT: I've decided to go an alternate route, since a one-liner may not be possible. Namely, I'm trying to loop over the macro, where for each word in the macro, I interact it with the interaction variable and append it to a new, blank macro. So right now, this looks like

local ints ""
local len_e : word count $example
forval i=1/len_e{
    local e `:word `i' of `example''
    local ints $ints `e'#`int'
}

but I'm getting an invalid syntax error.

Body:
The thing to do is to add parentheses around the macro, i.e.

reg outcome_var `example' (`example')#interaction_var

Then interaction_var interacts with everything inside example.


问:
Is the Spark-Cassandra-connector node aware?
Is Datastax Cassandra community edition integration with Spark community edition using spark-cassandra-connector community edition node aware or is this feature reserved for Enterprise editions only?

By node awareness I mean if Spark will send job execution to the nodes owning the data

答:
Yes, the Spark connector is node-aware and will function in that manner with both DSE and (open source) Apache Cassandra.

In fact on a SELECT it knows how to hash the partition keys to a token, and send queries on specific token ranges only to the nodes responsible for that data.  It can do this, because (like the Cassandra Java driver) it has a window into node-to-node gossip and can see things like node status (up/down) and token range assignment.


问:
How to display date in React.js using state?
I'm trying to display date using React.js but for some reason it's not displaying anything.

I'm a beginner so I'm sorry if I'm asking a stupid question, but I can't figure out why it's not working. Can someone please help me? Thanks so much!

```<code>class App extends React.Component {
  state = {
    date: ""
  };

  getDate() {
    var date = { currentTime: new Date().toLocaleString() };

    this.setState({
      date: date
    });
  }

  render() {
    return (
      <div class="date">
        <p> ddd {this.state.date}</p>
      </div>
    );
  }
}

export default App;
</code>```

答:
```<code>import React from "react";
import ReactDOM from "react-dom";

const tick = () => {
  const elem = (
    <div>
      <h2>It is {new Date().toLocaleString() } </h2>
    </div>
  );
  ReactDOM.render(elem, document.getElementById("root"));
};

setInterval(() => {
  tick();
}, 1000);
</code>```

Body:
I'm trying to display date using React.js but for some reason it's not displaying anything.

I'm a beginner so I'm sorry if I'm asking a stupid question, but I can't figure out why it's not working. Can someone please help me? Thanks so much!

class App extends React.Component {
  state = {
    date: ""
  };

  getDate() {
    var date = { currentTime: new Date().toLocaleString() };

    this.setState({
      date: date
    });
  }

  render() {
    return (

 ddd {this.state.date}

    );
  }
}

export default App;


问:
Making a bash process is slow
Below function takes a bash command, executes it, and returns the reply.

```<code>    public static String cmd(String s) {
        String out = "";
        try {
            Process pr = PB.command("bash","-c",s).start(); // PB is Process Builder
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line = "";
            out = buf.readLine();
        }catch(Exception e) {
            e.printStackTrace();
            // Shhh. be silent
        }
        return out;
    }
</code>```

Command : bash -c "java app <<< 5" where app.java is an app that reads from stdin to do specific function.

This function takes approx. 617ms to execute, why is that? is there any performance optimization?
Edit : Problem was in app.java. However, It still takes ~12ms.

答:
Making a new process is slow on OS level. I am surprised it only took 600ms.
Multithreading came to existence exactly because creating new process is slow on OS level.

If you need something faster from java, stay in java and make an alternative implementation.

Title: Making a bash process is slow

Body:
Below function takes a bash command, executes it, and returns the reply.

    public static String cmd(String s) {
        String out = "";
        try {
            Process pr = PB.command("bash","-c",s).start(); // PB is Process Builder
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line = "";
            out = buf.readLine();
        }catch(Exception e) {
            e.printStackTrace();
            // Shhh. be silent
        }
        return out;
    }

Command : bash -c "java app <<< 5" where app.java is an app that reads from stdin to do specific function.

This function takes approx. 617ms to execute, why is that? is there any performance optimization?
Edit : Problem was in app.java. However, It still takes ~12ms.


问:
I'm trying to get first 3 results from MySQL database in Node.js and I'm getting this error
Here's the code I'm using

```<code>con.query('SELECT * FROM tables', function(err, results) {
                if (err) throw err
                console.log(results[0].rawname)
                for(var i= 0; i <= 3; i++) {
                    eval("var " + 'name_' + i + ' = ' + "'" + results[i].rawname + "'" + ";")
                    eval("var " + 'url_' + i + ' = ' + "'" + results[i].url + "'" + ";")
                    eval("var " + 'creator_' + i + ' = ' + "'" + results[i].creator + "'" + ';' )
                }
</code>```

I'm getting this error:

TypeError: Cannot read property 'rawname' of undefined

Now I know it's a problem with the i variable since I tried logging it outside the loop with a 0 in the place of the i and it seems to work fine, how can I do it with the i variable?

答: so the problem was not in the js but in the table, so the thing is there was no results[1] since i only had 1 result, well, sorry for wasting your time.</p>

Body:
Here's the code I'm using

con.query('SELECT * FROM tables', function(err, results) {
                if (err) throw err
                console.log(results[0].rawname)
                for(var i= 0; i <= 3; i++) {
                    eval("var " + 'name_' + i + ' = ' + "'" + results[i].rawname + "'" + ";")
                    eval("var " + 'url_' + i + ' = ' + "'" + results[i].url + "'" + ";")
                    eval("var " + 'creator_' + i + ' = ' + "'" + results[i].creator + "'" + ';' )
                }

I'm getting this error:

TypeError: Cannot read property 'rawname' of undefined

Now I know it's a problem with the i variable since I tried logging it outside the loop with a 0 in the place of the i and it seems to work fine, how can I do it with the i variable?