问:
Azure Batch and Creating Containers Folder in Azure Storage
I have a c# console application that runs on a node in pool in Azure Batch. The console app writes to stdout.txt on the node and also creates a copy of this file in the Azure storage account linked to the batch account of the pool this all works fine.

In order to achieve this I followed the web-page:
https://learn.microsoft.com/en-us/azure/batch/batch-task-output-file-conventions.

If I create and run a pool job called 'jobid001' with a linked task called 'Task001' (the task runs the console app) then a container called 'job-jobid001' is created and what looks like a sub-folder called 'Task001' - this is all correctly created under the storage-account linked to the pool batch-account as shown below...

The c# code below creates the job container in the Az storage account and sets up for the contents of the stdout.txt on the batch-node to be written (asynch) to the file on the matching file on Az storage account - this all works fine.

```<code>   // Parse the connection string and return a reference to the storage account.

                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(account_url);

                    // Create a folder in Azure for the standard ouput log files to be copied to
                    string containerName = "job-" + _jobId;
                    containerName = containerName.ToLower();

                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
                    container.CreateIfNotExists();

                    TaskOutputStorage taskOutputStorage = new TaskOutputStorage(storageAccount, _jobId, _taskId);

                    TimeSpan stdoutFlushDelay = TimeSpan.FromSeconds(3);

                    // The primary task logic is wrapped in a using statement that sends updates to
                    // the stdout.txt blob in Storage every 15 seconds while the task code runs.
                    using (ITrackedSaveOperation stdout =
                            await taskOutputStorage.SaveTrackedAsync(
                            TaskOutputKind.TaskLog,
                            logFilePath,
                            "stdout.txt",
                            TimeSpan.FromSeconds(15)))
                    {

                        // MAIN C# CONSOLE CODE THAT DOES WORK HAS BEEN REMOVED

                        // We are tracking the disk file to save our standard output, but the
                        // node agent may take up to 3 seconds to flush the stdout stream to
                        // disk. So give the file a moment to catch up.
                        await Task.Delay(stdoutFlushDelay);
                    }
</code>```

What I want to achieve is to simulate a folder structure in the Az storage account under a root container 'MyAppLogFiles'. The root container will have a simulated sub-folder structure of: year, month, day and then jobid - how do I achieve this by enhancing the c# code above   ?  (with the year, month, day etc is the run date-time of the job)

Az-Container

```<code>-> MyAppLogFiles
           ->2020
             ->05
              ->31
                ->job-jobid001
                  ->Task001
                    stdout.txt
</code>```

答:
I just went through the source code of Microsoft.Azure.Batch.Conventions.Files(but did not give it a try), you may try the steps below:

1.In your code, set the container name to MyAppLogFiles.

2.In this line of code: TaskOutputStorage taskOutputStorage = new TaskOutputStorage(storageAccount, _jobId, _taskId);, you can pass this variable "2020/05/31/job-jobid001/Task001" for _taskId. The referenced source code is here.

Body:
I have a c# console application that runs on a node in pool in Azure Batch. The console app writes to stdout.txt on the node and also creates a copy of this file in the Azure storage account linked to the batch account of the pool this all works fine.

In order to achieve this I followed the web-page:
https://learn.microsoft.com/en-us/azure/batch/batch-task-output-file-conventions.

If I create and run a pool job called 'jobid001' with a linked task called 'Task001' (the task runs the console app) then a container called 'job-jobid001' is created and what looks like a sub-folder called 'Task001' - this is all correctly created under the storage-account linked to the pool batch-account as shown below...

The c# code below creates the job container in the Az storage account and sets up for the contents of the stdout.txt on the batch-node to be written (asynch) to the file on the matching file on Az storage account - this all works fine.

   // Parse the connection string and return a reference to the storage account.

                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(account_url);

                    // Create a folder in Azure for the standard ouput log files to be copied to
                    string containerName = "job-" + _jobId;
                    containerName = containerName.ToLower();

                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
                    container.CreateIfNotExists();

                    TaskOutputStorage taskOutputStorage = new TaskOutputStorage(storageAccount, _jobId, _taskId);

                    TimeSpan stdoutFlushDelay = TimeSpan.FromSeconds(3);

                    // The primary task logic is wrapped in a using statement that sends updates to
                    // the stdout.txt blob in Storage every 15 seconds while the task code runs.
                    using (ITrackedSaveOperation stdout =
                            await taskOutputStorage.SaveTrackedAsync(
                            TaskOutputKind.TaskLog,
                            logFilePath,
                            "stdout.txt",
                            TimeSpan.FromSeconds(15)))
                    {

                        // MAIN C# CONSOLE CODE THAT DOES WORK HAS BEEN REMOVED

                        // We are tracking the disk file to save our standard output, but the
                        // node agent may take up to 3 seconds to flush the stdout stream to
                        // disk. So give the file a moment to catch up.
                        await Task.Delay(stdoutFlushDelay);
                    }

What I want to achieve is to simulate a folder structure in the Az storage account under a root container 'MyAppLogFiles'. The root container will have a simulated sub-folder structure of: year, month, day and then jobid - how do I achieve this by enhancing the c# code above   ?  (with the year, month, day etc is the run date-time of the job)

Az-Container

-> MyAppLogFiles
           ->2020
             ->05
              ->31
                ->job-jobid001
                  ->Task001
                    stdout.txt


来源: stackexchange

问:
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

```<code>async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

```<code> console.log(positiondata, timerdata);
</code>```

What if I don't put any await(s) in the async like below?

```<code>async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

答:
An async function can contain an await expression, that pauses the

 execution of the async function and waits for the passed Promise's
 resolution, and then resumes the async function's execution and
 returns the resolved value.

As you assumed, if no await is present the execution is not paused and your code will then be executed in a non-blocking manner.

```<code>const getPromise = async (s) => {
   return new Promise((resolve, reject) => {
      setTimeout(() => resolve(s), 500);
   });
}

(async() => {
  try {
    const result = getPromise("a"); //no await, result has not been unwrapped
    console.log('async/await -> ', result);
  } catch (err) {
    console.log(err);
  }
})();
</code>```

Async function without await in Javascript

ContentLicense: CC BY-SA 4.0

Body:
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

 console.log(positiondata, timerdata);

What if I don't put any await(s) in the async like below?

async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

Body:
An async function can contain an await expression, that pauses the

 execution of the async function and waits for the passed Promise's
 resolution, and then resumes the async function's execution and
 returns the resolved value.

As you assumed, if no await is present the execution is not paused and your code will then be executed in a non-blocking manner.

const getPromise = async (s) => {
   return new Promise((resolve, reject) => {
      setTimeout(() => resolve(s), 500);
   });
}

(async() => {
  try {
    const result = getPromise("a"); //no await, result has not been unwrapped
    console.log('async/await -> ', result);
  } catch (err) {
    console.log(err);
  }
})();

Async function without await in Javascript


问:
.bashrc not sourced on Intellij IDEA's terminal
I have some aliased defined on my .bashrc that I'd like to use on my Intellij IDEA's terminal. Why is .bashrc not sourced?

答: I just restarted my MAC and it picked up the new stuff. </p>

ContentLicense: CC BY-SA 3.0


问:
Python string sequcence like excel
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

```<code>>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)
</code>```

答:
Simplely you may create a list to contain the sequance.
It's simple but not good enough.
e.g.

seq = ['A', 'B', ... 'ZZ']
s = 'A'  # s.toupper() if required.
idx = seq.index(s)
if idx < 0:
  print('not in sequence')
  return   # or exit
next = idx + 1
if next >= len(seq):
  next = 0
print(seq[next])

```

Title: Python string sequcence like excel

Body:
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)


问:
AWS Cognito's SMS Multi Factor Authentication returns invalid code or auth state
I am trying to implement authentication built on Cognito using their Go SDK. I have been able to get basic username/password authentication to work, but when I add in 2-factor authentication using SMS I am getting stuck.

Steps to reproduce :

I create the user with a username/password and email verification

I validate the email address

I set the phone number and request a verification code

I verify the phone number

I enable 2-factor authentication (via SMS)

I try to sign in and receive the SMS_MFA challenge

I receive the code on my phone and call AdminRespondToAuthChallenge

Problem, I receive an error :

```<code>CodeMismatchException: Invalid code or auth state for the user.
status code: 400, request id: 1513894e-8efa-11e8-a8f8-97e5e083c03b
</code>```

The SMS verification code is certainly correct, so it seems that it must be something to do with the auth state.

The calls to Cognito look like this:

```<code>c.cip.SignUp(&cognitoidentityprovider.SignUpInput{
        ClientId: aws.String(c.clientID),
        Username: aws.String(username),
        Password: aws.String(password),
        UserAttributes: []*cognitoidentityprovider.AttributeType{
            {
                Name:  aws.String("email"),
                Value: aws.String(email),
            },
            {
                Name:  aws.String("name"),
                Value: aws.String(fullName),
            },
        },
    })

c.cip.ConfirmSignUp(&cognitoidentityprovider.ConfirmSignUpInput{
    ClientId:         aws.String(c.clientID),
    Username:         aws.String(username),
    ConfirmationCode: aws.String(code),
})

//Add the phone number
c.cip.AdminUpdateUserAttributes(&cognitoidentityprovider.AdminUpdateUserAttributesInput{
            UserPoolId: aws.String(c.userPoolID),
            Username:   aws.String(username),
            UserAttributes: []*cognitoidentityprovider.AttributeType{
                {
                    Name:  aws.String("phone_number"),
                    Value: aws.String(phoneNumber),
                },
            },
        })

//Request a verification code
c.cip.GetUserAttributeVerificationCode(&cognitoidentityprovider.GetUserAttributeVerificationCodeInput{
    AccessToken:   aws.String(accessToken),
    AttributeName: aws.String("phone_number"),
})

//Verify the phone number
c.cip.VerifyUserAttribute(&cognitoidentityprovider.VerifyUserAttributeInput{
    AccessToken:   aws.String(accessToken),
    AttributeName: aws.String("phone_number"),
    Code:          aws.String(code),
})

//Enable SMS 2-factor auth c.cip.AdminSetUserSettings(&cognitoidentityprovider.AdminSetUserSettingsInput{
    UserPoolId: aws.String(c.userPoolID),
    Username:   aws.String(username),
    MFAOptions: []*cognitoidentityprovider.MFAOptionType{
        &cognitoidentityprovider.MFAOptionType{
            AttributeName:  aws.String("phone_number"),
            DeliveryMedium: aws.String("SMS"),
        },
    },
})

c.cip.AdminInitiateAuth(&cognitoidentityprovider.AdminInitiateAuthInput{
    ClientId:   aws.String(c.clientID),
    UserPoolId: aws.String(c.userPoolID),
    AuthFlow:   aws.String("ADMIN_NO_SRP_AUTH"),
    AuthParameters: map[string]*string{
        "USERNAME": aws.String(username),
        "PASSWORD": aws.String(password),
    },
})

c.cip.AdminRespondToAuthChallenge(&cognitoidentityprovider.AdminRespondToAuthChallengeInput{
        ClientId:      aws.String(c.clientID),
        UserPoolId:    aws.String(c.userPoolID),
        ChallengeName: aws.String("SMS_MFA"),
        Session:       aws.String(session),
        ChallengeResponses: map[string]*string{
            "USERNAME":     aws.String(username),
            "SMS_MFA_CODE": aws.String(code),
        },
    })
</code>```

Doing a GetUser call shows the current state of the user:

```<code>User = {
              Enabled: true,
              MFAOptions: [{
                  AttributeName: "phone_number",
                  DeliveryMedium: "SMS"
                }],
              PreferredMfaSetting: "SMS_MFA",
              UserAttributes: [
                {
                  Name: "sub",
                  Value: "bd2bb8bc-dfe6-4216-829c-5ae975ce24e5"
                },
                {
                  Name: "email_verified",
                  Value: "true"
                },
                {
                  Name: "name",
                  Value: "Ben Vogan"
                },
                {
                  Name: "phone_number_verified",
                  Value: "true"
                },
                {
                  Name: "phone_number",
                  Value: "<redacted>"
                },
                {
                  Name: "email",
                  Value: "<redacted>"
                }
              ],
              UserCreateDate: 2018-07-24 03:29:49 +0000 UTC,
              UserLastModifiedDate: 2018-07-24 04:19:51 +0000 UTC,
              UserMFASettingList: ["SMS_MFA"],
              UserStatus: "CONFIRMED",
              Username: "bd2bb8bc-dfe6-4216-829c-5ae975ce24e5"
            }
</code>```

I do not know if there is a way to query the user's auth state so that I can verify that.

The AWS documentation and unhelpful errors are driving me insane so any help would be greatly appreciated!

Thanks.

答:
Your questions seems ambiguous.

step 2 you are

I set the phone number and request a verification code

I verify the phone number

this is nothing but MFA in Cognito. if you have configured the pool correctly.

You cannot have both phone for login and MFA. that doesn't make sense.

but if you have phone for login, then Cognito will send SMS every time with code. password is only for email logins.

Body:
I am trying to implement authentication built on Cognito using their Go SDK. I have been able to get basic username/password authentication to work, but when I add in 2-factor authentication using SMS I am getting stuck.

Steps to reproduce :

I create the user with a username/password and email verification

I validate the email address

I set the phone number and request a verification code

I verify the phone number

I enable 2-factor authentication (via SMS)

I try to sign in and receive the SMS_MFA challenge

I receive the code on my phone and call AdminRespondToAuthChallenge

Problem, I receive an error :

CodeMismatchException: Invalid code or auth state for the user.
status code: 400, request id: 1513894e-8efa-11e8-a8f8-97e5e083c03b

The SMS verification code is certainly correct, so it seems that it must be something to do with the auth state.

The calls to Cognito look like this:

c.cip.SignUp(&cognitoidentityprovider.SignUpInput{
        ClientId: aws.String(c.clientID),
        Username: aws.String(username),
        Password: aws.String(password),
        UserAttributes: []*cognitoidentityprovider.AttributeType{
            {
                Name:  aws.String("email"),
                Value: aws.String(email),
            },
            {
                Name:  aws.String("name"),
                Value: aws.String(fullName),
            },
        },
    })

c.cip.ConfirmSignUp(&cognitoidentityprovider.ConfirmSignUpInput{
    ClientId:         aws.String(c.clientID),
    Username:         aws.String(username),
    ConfirmationCode: aws.String(code),
})

//Add the phone number
c.cip.AdminUpdateUserAttributes(&cognitoidentityprovider.AdminUpdateUserAttributesInput{
            UserPoolId: aws.String(c.userPoolID),
            Username:   aws.String(username),
            UserAttributes: []*cognitoidentityprovider.AttributeType{
                {
                    Name:  aws.String("phone_number"),
                    Value: aws.String(phoneNumber),
                },
            },
        })

//Request a verification code
c.cip.GetUserAttributeVerificationCode(&cognitoidentityprovider.GetUserAttributeVerificationCodeInput{
    AccessToken:   aws.String(accessToken),
    AttributeName: aws.String("phone_number"),
})

//Verify the phone number
c.cip.VerifyUserAttribute(&cognitoidentityprovider.VerifyUserAttributeInput{
    AccessToken:   aws.String(accessToken),
    AttributeName: aws.String("phone_number"),
    Code:          aws.String(code),
})

//Enable SMS 2-factor auth c.cip.AdminSetUserSettings(&cognitoidentityprovider.AdminSetUserSettingsInput{
    UserPoolId: aws.String(c.userPoolID),
    Username:   aws.String(username),
    MFAOptions: []*cognitoidentityprovider.MFAOptionType{
        &cognitoidentityprovider.MFAOptionType{
            AttributeName:  aws.String("phone_number"),
            DeliveryMedium: aws.String("SMS"),
        },
    },
})

c.cip.AdminInitiateAuth(&cognitoidentityprovider.AdminInitiateAuthInput{
    ClientId:   aws.String(c.clientID),
    UserPoolId: aws.String(c.userPoolID),
    AuthFlow:   aws.String("ADMIN_NO_SRP_AUTH"),
    AuthParameters: map[string]*string{
        "USERNAME": aws.String(username),
        "PASSWORD": aws.String(password),
    },
})

c.cip.AdminRespondToAuthChallenge(&cognitoidentityprovider.AdminRespondToAuthChallengeInput{
        ClientId:      aws.String(c.clientID),
        UserPoolId:    aws.String(c.userPoolID),
        ChallengeName: aws.String("SMS_MFA"),
        Session:       aws.String(session),
        ChallengeResponses: map[string]*string{
            "USERNAME":     aws.String(username),
            "SMS_MFA_CODE": aws.String(code),
        },
    })

Doing a GetUser call shows the current state of the user:

User = {
              Enabled: true,
              MFAOptions: [{
                  AttributeName: "phone_number",
                  DeliveryMedium: "SMS"
                }],
              PreferredMfaSetting: "SMS_MFA",
              UserAttributes: [
                {
                  Name: "sub",
                  Value: "bd2bb8bc-dfe6-4216-829c-5ae975ce24e5"
                },
                {
                  Name: "email_verified",
                  Value: "true"
                },
                {
                  Name: "name",
                  Value: "Ben Vogan"
                },
                {
                  Name: "phone_number_verified",
                  Value: "true"
                },
                {
                  Name: "phone_number",
                  Value: "<redacted>"
                },
                {
                  Name: "email",
                  Value: "<redacted>"
                }
              ],
              UserCreateDate: 2018-07-24 03:29:49 +0000 UTC,
              UserLastModifiedDate: 2018-07-24 04:19:51 +0000 UTC,
              UserMFASettingList: ["SMS_MFA"],
              UserStatus: "CONFIRMED",
              Username: "bd2bb8bc-dfe6-4216-829c-5ae975ce24e5"
            }

I do not know if there is a way to query the user's auth state so that I can verify that.

The AWS documentation and unhelpful errors are driving me insane so any help would be greatly appreciated!

Thanks.


问:
What should be the relationship between the classes of a supermarket management system?
I'm making a supermarket management system based on c++ and incorporating GUI.

so, when the user enters details and all, there are four categories displayed, namely dairy products, fruits, vegetables, and cooking ingredients. When clicking on any of those, further items from the category show up. For eg, when clicked on dairy products, user can see milk, eggs, and cheese. There's "add to cart" button with all three of them.

Now I'm basically confused about the classes and filing. Firstly, I had thought that dairy products should be a parent + abstract class and have three further child classes namely milk, eggs, cheese. But that would be too many classes and not very efficient I feel. Later, I thought there should be four classes for 4 categories and an instance of class should be created everytime "add to cart" button is clicked. But im still confused on what should be the member variables of the class.. ID (because milk, cheese, eggs must have a different ID), three variables of stock (because stock count for each will be different), and name?

If anyone can help me with the basic classes, their relationships, and the member variables in it.

Thank you!

Here's the code. I'm particularly confused on how to update the stock for a particular item in a file.

```<code>    #include <string>
    #include <iostream>
    using namespace std;
    class Product
    {
       protected:
       string name;
       string ID;
       int count;
       Product(string n, string id, int c)
       {
          name=n;
          ID= id;
          count=c;
       }
       Product()
       {

       }
     };
     class FV : public Product
     {
       public:
       FV()
       {

       }
       FV (int a)
       {
         name="Apples";
         ID: "APP01";
       }
       void UpdateStock()
       {
         count=count-1;
       }

  };
</code>```

答: You might want to define a Product class with id, name and count variables and inherit the four categories as child classes. Depending on your database design, your query to show items of same category can be different, but the idea is to find objects of the same type and use them as a data source for your ui.

Body:
I'm making a supermarket management system based on c++ and incorporating GUI.

so, when the user enters details and all, there are four categories displayed, namely dairy products, fruits, vegetables, and cooking ingredients. When clicking on any of those, further items from the category show up. For eg, when clicked on dairy products, user can see milk, eggs, and cheese. There's "add to cart" button with all three of them.

Now I'm basically confused about the classes and filing. Firstly, I had thought that dairy products should be a parent + abstract class and have three further child classes namely milk, eggs, cheese. But that would be too many classes and not very efficient I feel. Later, I thought there should be four classes for 4 categories and an instance of class should be created everytime "add to cart" button is clicked. But im still confused on what should be the member variables of the class.. ID (because milk, cheese, eggs must have a different ID), three variables of stock (because stock count for each will be different), and name?

If anyone can help me with the basic classes, their relationships, and the member variables in it.

Thank you!

Here's the code. I'm particularly confused on how to update the stock for a particular item in a file.

    #include <string>
    #include <iostream>
    using namespace std;
    class Product
    {
       protected:
       string name;
       string ID;
       int count;
       Product(string n, string id, int c)
       {
          name=n;
          ID= id;
          count=c;
       }
       Product()
       {

       }
     };
     class FV : public Product
     {
       public:
       FV()
       {

       }
       FV (int a)
       {
         name="Apples";
         ID: "APP01";
       }
       void UpdateStock()
       {
         count=count-1;
       }

  };


问:
How can I make the content of a grid element not affect its size?
Basically i just want the four boxes in the snippet below to be the same size while still having the text centered inside the first box. Right now the text 'qwe' affects the size of the first box. Also it has to be using display: grid, like it is now.

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asd">
  <div class="box1">qwe</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div></code>```

答:
Add height and width to 50px of each div as the asd is 100px

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  width:50px;
  height:50px;

}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asd">
  <div class="box1">aqs</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div></code>```

Body:
Basically i just want the four boxes in the snippet below to be the same size while still having the text centered inside the first box. Right now the text 'qwe' affects the size of the first box. Also it has to be using display: grid, like it is now.

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}

qwe

Body:
Add height and width to 50px of each div as the asd is 100px

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  width:50px;
  height:50px;

}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}

<div class="asd">
  <div class="box1">aqs</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div>


问:
Azure pipeline stageList parameter to extend template
I'm trying to pass stage list from azure pipeline shown below

```<code># File: azure-pipelines.yml
trigger:
- master

extends:
  template: start_stage.yml
  parameters:
    cdstages:
    - stage: secure_buildstage
      pool: Hosted VS2017
      jobs:
      - job: secure_buildjob
        steps:
        - bash: echo This happens before code
          displayName: 'Base: Pre-build'
        - bash: echo Building
          displayName: 'Base: Build'

        - bash: echo This happens after code
          displayName: 'Base: Signing'

    - stage: secure_deploystage
      pool: Hosted VS2017
      jobs:
      - job: secure_deployjob
        steps:
        - bash: echo This happens before code
          displayName: 'Base: Pre-build'
        - bash: echo Building
          displayName: 'Base: Build'

        - script: echo This happens after code
          displayName: 'Base: Signing'
</code>```

to extend template shown below

```<code>parameters:
- name: cdstages # the name of the parameter is buildSteps
  type: stageList # data type is StepList
  default: [] # default value of buildSteps
stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each job in stage.jobs }}:
    - ${{ each step in job.steps }}:
      - ${{ each pair in step }}:
          ${{ if ne(pair.value, 'CmdLine@2') }}:
            ${{ pair.key }}: ${{ pair.value }}
          ${{ if eq(pair.value, 'CmdLine@2') }}:
            '${{ pair.value }}': error
</code>```

The goal is to take stage list and validate if users are only running steps approved by firm's compliance team.

I'm getting error
[][1

not sure why getting "task" error, there are no task keywords used anywhere.
Any help?

答:
Based on my test , it seems that the stagelist in start_stage.yml doesn't support to add eachdirective to get  deeper content (e.g. job and steps).

When you use the stagelist, it could get the stage and use it for comparison.

For example:

```<code>parameters:
- name: cdstages # the name of the parameter is buildSteps
  type: stageList # data type is StepList
  default: [] # default value of buildSteps

stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each pair in stage }}:
      ${{ if ne(pair.value, 'abc') }}:
        ${{ pair.key }}: ${{ pair.value }}
      ${{ if eq(pair.value, 'abc') }}:
        '${{ pair.value }}': error
</code>```

This Yaml template could work.

But when I add the each directive behind the stage to get the jobs. The jobs are is not available.

```<code>parameters:
- name: cdstages
  type: stageList
  default: []

stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each job in stage.jobs }}:
    - ${{ each pair in job }}:
        ${{ if ne(pair.value, 'abc') }}:
          ${{ pair.key }}: ${{ pair.value }}
        ${{ if eq(pair.value, 'abc') }}:
          '${{ pair.value }}': error
</code>```

According to your requirements, you need to get the build step and use it for comparison.

You could try to directly use the steplist type.

Here is an example about steplist, you could refer to it.

Hope this helps.

Body:
I'm trying to pass stage list from azure pipeline shown below

# File: azure-pipelines.yml
trigger:
- master

extends:
  template: start_stage.yml
  parameters:
    cdstages:
    - stage: secure_buildstage
      pool: Hosted VS2017
      jobs:
      - job: secure_buildjob
        steps:
        - bash: echo This happens before code
          displayName: 'Base: Pre-build'
        - bash: echo Building
          displayName: 'Base: Build'

        - bash: echo This happens after code
          displayName: 'Base: Signing'

    - stage: secure_deploystage
      pool: Hosted VS2017
      jobs:
      - job: secure_deployjob
        steps:
        - bash: echo This happens before code
          displayName: 'Base: Pre-build'
        - bash: echo Building
          displayName: 'Base: Build'

        - script: echo This happens after code
          displayName: 'Base: Signing'

to extend template shown below

parameters:
- name: cdstages # the name of the parameter is buildSteps
  type: stageList # data type is StepList
  default: [] # default value of buildSteps
stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each job in stage.jobs }}:
    - ${{ each step in job.steps }}:
      - ${{ each pair in step }}:
          ${{ if ne(pair.value, 'CmdLine@2') }}:
            ${{ pair.key }}: ${{ pair.value }}
          ${{ if eq(pair.value, 'CmdLine@2') }}:
            '${{ pair.value }}': error

The goal is to take stage list and validate if users are only running steps approved by firm's compliance team.

I'm getting error
[][1

not sure why getting "task" error, there are no task keywords used anywhere.
Any help?

Body:
Based on my test , it seems that the stagelist in start_stage.yml doesn't support to add eachdirective to get  deeper content (e.g. job and steps).

When you use the stagelist, it could get the stage and use it for comparison.

For example:

parameters:
- name: cdstages # the name of the parameter is buildSteps
  type: stageList # data type is StepList
  default: [] # default value of buildSteps

stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each pair in stage }}:
      ${{ if ne(pair.value, 'abc') }}:
        ${{ pair.key }}: ${{ pair.value }}
      ${{ if eq(pair.value, 'abc') }}:
        '${{ pair.value }}': error

This Yaml template could work.

But when I add the each directive behind the stage to get the jobs. The jobs are is not available.

parameters:
- name: cdstages
  type: stageList
  default: []

stages:
- ${{ each stage in parameters.cdstages }}:
  - ${{ each job in stage.jobs }}:
    - ${{ each pair in job }}:
        ${{ if ne(pair.value, 'abc') }}:
          ${{ pair.key }}: ${{ pair.value }}
        ${{ if eq(pair.value, 'abc') }}:
          '${{ pair.value }}': error

According to your requirements, you need to get the build step and use it for comparison.

You could try to directly use the steplist type.

Here is an example about steplist, you could refer to it.

Hope this helps.


问:
How to convert string number into numeric number with given string, Java
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

```<code>public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}
</code>```

答:
I don’t think I’d use a regular expression for this. I am offering three avenues:

The easy way: for each digit from 0 through 9, replace every occurrence.

Build the result in a StringBuilder. For each char in the original string append the appropriate word if it’s a digit, otherwise just the char.

A fix to your regex approach.

Replace all digits

I have put your declaration outside the method (you don’t have to do that):

```<code>private static final String SINGLE_DIGITS[] = { "ZERO", "ONE", "TWO", "THREE",
        "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
</code>```

Now we do:

```<code>    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";

    for (int d = 0; d < 10; d++) {
        testString = testString.replace(String.valueOf(d), SINGLE_DIGITS[d]);
    }
    System.out.println(testString);
</code>```

Output:

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.

When some digit is not found (for example, 0), replace() just returns the same string (or an equal one, I don’t care). If on the other hand a digit occurs more than once (both 2 and 5 do), every occurrence is replaced. This is not the most efficient way, but for strings the size of yours you should be fine.

Build result linearly

I am using these further declarations:

```<code>private static final BitSet DIGITS = new BitSet();
static {
    DIGITS.set('0', '9' + 1);
}
</code>```

Now we can do:

```<code>    StringBuilder buf = new StringBuilder();
    for (int ix = 0; ix < testString.length(); ix++) {
        char ch = testString.charAt(ix);
        if (DIGITS.get(ch)) {
            buf.append(SINGLE_DIGITS[Character.getNumericValue(ch)]);
        } else {
            buf.append(ch);
        }
    }
    String result = buf.toString();

    System.out.println(result);
</code>```

Output is the same as before. This is the recommended way if efficiency is a priority.

Your approach with regex

First, since you want 12 replaced by ONETWO(not TWELVE), don’t include a + in your regular expression:

```<code>public static Pattern pattern = Pattern.compile("\\d");
</code>```

Now for each digit found, make a lookup in SINGLE_DIGITS to find the replacement:

```<code>    Matcher matcher = pattern.matcher(testString);

    while (matcher.find()) {
        testString = testString.replace(matcher.group(),
                SINGLE_DIGITS[Integer.parseInt(matcher.group())]);
    }

    System.out.println(testString);
</code>```

The output is the same as before.

Body:
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}

Body:
I don’t think I’d use a regular expression for this. I am offering three avenues:

The easy way: for each digit from 0 through 9, replace every occurrence.

Build the result in a StringBuilder. For each char in the original string append the appropriate word if it’s a digit, otherwise just the char.

A fix to your regex approach.

Replace all digits

I have put your declaration outside the method (you don’t have to do that):

private static final String SINGLE_DIGITS[] = { "ZERO", "ONE", "TWO", "THREE",
        "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };

Now we do:

    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";

    for (int d = 0; d < 10; d++) {
        testString = testString.replace(String.valueOf(d), SINGLE_DIGITS[d]);
    }
    System.out.println(testString);

Output:

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.

When some digit is not found (for example, 0), replace() just returns the same string (or an equal one, I don’t care). If on the other hand a digit occurs more than once (both 2 and 5 do), every occurrence is replaced. This is not the most efficient way, but for strings the size of yours you should be fine.

Build result linearly

I am using these further declarations:

private static final BitSet DIGITS = new BitSet();
static {
    DIGITS.set('0', '9' + 1);
}

Now we can do:

    StringBuilder buf = new StringBuilder();
    for (int ix = 0; ix < testString.length(); ix++) {
        char ch = testString.charAt(ix);
        if (DIGITS.get(ch)) {
            buf.append(SINGLE_DIGITS[Character.getNumericValue(ch)]);
        } else {
            buf.append(ch);
        }
    }
    String result = buf.toString();

    System.out.println(result);

Output is the same as before. This is the recommended way if efficiency is a priority.

Your approach with regex

First, since you want 12 replaced by ONETWO(not TWELVE), don’t include a + in your regular expression:

public static Pattern pattern = Pattern.compile("\\d");

Now for each digit found, make a lookup in SINGLE_DIGITS to find the replacement:

    Matcher matcher = pattern.matcher(testString);

    while (matcher.find()) {
        testString = testString.replace(matcher.group(),
                SINGLE_DIGITS[Integer.parseInt(matcher.group())]);
    }

    System.out.println(testString);

The output is the same as before.


问:
Add text to specific line without removing the exist line in php
I'm trying to add only last name if first name is same

data.txt

```<code>Alice Sandy
Alice Nanami
James Watt
Alice Monica
Johann Gauss
</code>```

to result.txt

```<code>Alice Sandy Nanami Monica
James Watt
Johann Gauss
</code>```

I try with this code

$resultFile = "result.txt";
$search     = "Alice";
$lineNumber = false;
if ($handle = fopen($result, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE and !$lineNumber) {
        $count++;
        $lineNumber = (strpos($line, $search) !== FALSE) ? $count : $lineNumber;
        $isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
    }
fclose($handle);
}
if($isExist=="yup"){
    $lines = file($resultFile);
    $lines[$lineNumber] = $lines[$lineNumber].' '.$lastName;
    file_put_contents($result, implode('', $lines));
}else{
    $fullName = $firstName.' '.$lastName;
    $fileOpen = fopen($result, "a");
    fwrite($fileOpen,$fullName);
    fclose($fileOpen);
    $addBreaker = "\n";
    $splResult = new SplFileObject($resultFile, 'a');
    $splResult->fwrite($addBreaker);
}
```

<p>But it give error offset (I'm using PHP 7) and the result is untidy</p>

```Alice Sandy Nanami
 Monica
James Watt

Johan Gauss
```

Thanks for help

答:
Another apporach instead of replacing lines would be save every line to an array and then iterate over array and save to the new file. You can also use the same file as an $outputFile.

```<code>$inputFile = 'names.txt';
$outputFile = 'result.txt';

$names = [];

if ($handle = fopen($inputFile, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE) {
        $count++;
        $lineNames = explode(' ', $line);
        $names[$lineNames[0]][] = trim($lineNames[1]);
    }
    fclose($handle);
}

$handle = fopen($outputFile, 'w');
foreach ($names as $firstName => $lastNames) {
    fwrite($handle, $firstName . ' ' . implode(' ', $lastNames) . PHP_EOL);
}
</code>```

Two additional notes:

Don't use string as boolean value.

$isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";

Use just following condition. It's enough

```<code>$isExist = (strpos($line, $search) !== FALSE)
</code>```

If you read lines from file you copy also new lines char, although you can't see them quite well in the output. You should trim all whitespace characters before inserting/replacing etc. to avoid old structure of file.

Body:
I'm trying to add only last name if first name is same

data.txt

Alice Sandy
Alice Nanami
James Watt
Alice Monica
Johann Gauss

to result.txt

Alice Sandy Nanami Monica
James Watt
Johann Gauss

I try with this code

$resultFile = "result.txt";
$search     = "Alice";
$lineNumber = false;
if ($handle = fopen($result, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE and !$lineNumber) {
        $count++;
        $lineNumber = (strpos($line, $search) !== FALSE) ? $count : $lineNumber;
        $isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
    }
fclose($handle);
}
if($isExist=="yup"){
    $lines = file($resultFile);
    $lines[$lineNumber] = $lines[$lineNumber].' '.$lastName;
    file_put_contents($result, implode('', $lines));
}else{
    $fullName = $firstName.' '.$lastName;
    $fileOpen = fopen($result, "a");
    fwrite($fileOpen,$fullName);
    fclose($fileOpen);
    $addBreaker = "\n";
    $splResult = new SplFileObject($resultFile, 'a');
    $splResult->fwrite($addBreaker);
}

But it give error offset (I'm using PHP 7) and the result is untidy

Alice Sandy Nanami
 Monica
James Watt

Johan Gauss

Thanks for help

Body:
Another apporach instead of replacing lines would be save every line to an array and then iterate over array and save to the new file. You can also use the same file as an $outputFile.

$inputFile = 'names.txt';
$outputFile = 'result.txt';

$names = [];

if ($handle = fopen($inputFile, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE) {
        $count++;
        $lineNames = explode(' ', $line);
        $names[$lineNames[0]][] = trim($lineNames[1]);
    }
    fclose($handle);
}

$handle = fopen($outputFile, 'w');
foreach ($names as $firstName => $lastNames) {
    fwrite($handle, $firstName . ' ' . implode(' ', $lastNames) . PHP_EOL);
}

Two additional notes:

Don't use string as boolean value.

$isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";

Use just following condition. It's enough

$isExist = (strpos($line, $search) !== FALSE)

If you read lines from file you copy also new lines char, although you can't see them quite well in the output. You should trim all whitespace characters before inserting/replacing etc. to avoid old structure of file.


问:
Why is my Javascript fizzbuzz code not working?
I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance

This is my code:

```<code>var output = [];
var count = 1;

function fizzBuzz() {
  if (count % 3 === 0) {
    output.push("Fizz");
  }
  if (count % 5 === 0) {
    output.push("Buzz");
  }
  if (count % 15 === 0) {
    output.push("FizzBuzz");
  } else {
    output.push(count);
  }

  count++;

  console.log(output);
};
</code>```

答:
Try This

```<code>var output = [];

function fizzBuzz(i) {
    if (i % 3 == 0 && i % 5 == 0) {
        output.push("FizzBuzz");
      } else if (i % 3 == 0) {
        output.push("Fizz");
      } else if (i % 5 == 0) {
        output.push("Buzz");
      } else {
        output.push(i)
      }
      console.log(output)
};

fizzBuzz(15)
</code>```

Body:
I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance

This is my code:

var output = [];
var count = 1;

function fizzBuzz() {
  if (count % 3 === 0) {
    output.push("Fizz");
  }
  if (count % 5 === 0) {
    output.push("Buzz");
  }
  if (count % 15 === 0) {
    output.push("FizzBuzz");
  } else {
    output.push(count);
  }

  count++;

  console.log(output);
};

Body:
Try This

var output = [];

function fizzBuzz(i) {
    if (i % 3 == 0 && i % 5 == 0) {
        output.push("FizzBuzz");
      } else if (i % 3 == 0) {
        output.push("Fizz");
      } else if (i % 5 == 0) {
        output.push("Buzz");
      } else {
        output.push(i)
      }
      console.log(output)
};

fizzBuzz(15)


问:
What is the best way to deploy authenticated autoupdates in a .NET application?
Currently applications are deployed only to my office of 40 employees or so.  ClickOnce works great for this as everyone has network access or VPN access which makes updating pretty straightforward.  Now, it has been tasked to me to figure out the best way to deploy these applications to res of the company.  ClickOnce would work but the files would be made publicly available to any.

What would be the easiest way to implement this feature with some form of authentication?

答:
The actual deploy page can be set up on a site that requires Windows Authentication. As long as the domain controller you are using trusts the other domain controllers, you are golden. You might be able to do this at the folder level, as well. If you go this route, you can still use the click once model.

There are a few more ideas here:
http://tinyurl.com/bn5e76

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gregory A Beamer


问:
Iterating Hashsets
Good morning guys

I have a hashset which has different objects

Object has attributes

GroupName
MachineName
EmailAddress

Now from the HashSet I have to find the Object which has same MachineName and EmailAddress but different Group and add into an arraylist.

thanks

答:
A big assumption is that you are using Java:

```<code>Set<YourObject> yourHashSet = //
List<YourObject> result = new ArrayList<YourObject>();
for( YourObject o: yourHashSet ){
    if( o.getMachineName().equals("machine1") && o.getEmailAddress().equals("one@example.com")){
        result.add(o);
    }
}

// result will contain a list of matching objects.
</code>```

It's pretty much the same code in any language, but if you are in C# you can use LINQ-Objects to do the something in a nice single statement.

Title: Iterating Hashsets

Body:
A big assumption is that you are using Java:

Set<YourObject> yourHashSet = //
List<YourObject> result = new ArrayList<YourObject>();
for( YourObject o: yourHashSet ){
    if( o.getMachineName().equals("machine1") && o.getEmailAddress().equals("one@example.com")){
        result.add(o);
    }
}

// result will contain a list of matching objects.

It's pretty much the same code in any language, but if you are in C# you can use LINQ-Objects to do the something in a nice single statement.


问:
Programatically setting default values in react-jsonschema-forms
I am trying to add default values to select fields in my form using react-jsonschema-form. The way I am achieving this is by having custom components. When the custom component is loaded it will call the onChange function with the default data. An example of when I use this is when I have a date field that I want today to be the default value.

If I only have one custom component that sets a default value, it works. However, if I have multiple fields that require default values, it does not work. I have made a small JSFiddle showing this in action. If you don't change anything and press the submit button you can see that only date4 is set.

We kind of got it working by using an effect and adding a timeout before calling onChange. This JSFiddle shows what we did, but I cannot get it to work on JSFiddle.

My question is, what's the best way to set a default value programmatically using react-jsonschema-form? I'd really prefer not modifying the schema itself programmatically.

答:
Add the default value in the schema.

```<code>properties: {
        date: { type: "string", format: "date", default:'2020-06-09' },
        date2: { type: "string", format: "date" },
        date3: { type: "string", format: "date" },
        date4: { type: "string", format: "date" },
        description: { type: "string" }
    }
</code>```

You will get the default value in custom widget props

```<code>const DatePickerDefaultToToday = (props) => {
    const onChange = (e) => {
            props.onChange(convertDateToString(e.value));
        }
  onChange({value: new Date(), syntheticEvent: null, show: true, target: null});
  return (<input type="date" onChange={onChange} defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}/>)
}
</code>```

The default value will get in the props. If the default value is not present,ive added to take it today's date

```<code>defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}
</code>```

Another way to set the value is you can pass the formData attribute to the Form.

```<code><Form schema={schema} uiSchema={uiSchema} formData={formData} widgets={customWidget} onSubmit={onSubmit}/>
</code>```

You can pass the data as key-value p2020-06-09air as name defined in the schema

```<code>const formData={{date:'2020-06-09'}}
</code>```

Body:
Add the default value in the schema.

properties: {
        date: { type: "string", format: "date", default:'2020-06-09' },
        date2: { type: "string", format: "date" },
        date3: { type: "string", format: "date" },
        date4: { type: "string", format: "date" },
        description: { type: "string" }
    }

You will get the default value in custom widget props

const DatePickerDefaultToToday = (props) => {
    const onChange = (e) => {
            props.onChange(convertDateToString(e.value));
        }
  onChange({value: new Date(), syntheticEvent: null, show: true, target: null});
  return (<input type="date" onChange={onChange} defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}/>)
}

The default value will get in the props. If the default value is not present,ive added to take it today's date

defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}

Another way to set the value is you can pass the formData attribute to the Form.

<Form schema={schema} uiSchema={uiSchema} formData={formData} widgets={customWidget} onSubmit={onSubmit}/>

You can pass the data as key-value p2020-06-09air as name defined in the schema

const formData={{date:'2020-06-09'}}


问:
Layering a contourf plot and surface_plot in matplotlib
I am struggling with layering and zorder in python. I am making a 3D plot using matplotlib with three relevant elements: A surface_plot of a planet, a surface_plot of rings around that planet, and a contourf image that shows the planet's shadow cast onto the rings.

I want the graphics to display exactly how this scenario would look in real life, with the rings going around the planet and the shadow residing across the rings in the appropriate spot. If the shadow is behind the planet for a given POV, I want the shadow to be blocked by the planet, and vice versa if the shadow is in front of the planet for a given POV.

To be clear, this is ONLY a layering issue. I have the planet, rings, and shadow all plotting correctly. However, the shadow will not ever display in front of the planet. It acts as though the planet is "blocking" the shadow, even though the planet is supposed to be underneath the shadow in terms of layering.

I have tried every single thing I can think of in terms of zorder and rearranging which order the various plot elements are called to be drawn. The rings DO correctly display in front of the planet, but the shadow will not.

My actual code is very long. here are the relevant parts:

Plot setup:

def orthographic_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    return np.array([[1,0,0,0],
                        [0,1,0,0],
                        [0,0,a,b],
                        [0,0,0,zback]])

def setup_saturn_plot(ax3, elev, azim, drawz, drawxy,view):
    #ax3.set_aspect('equal','box')
    ax3.view_init(elev=elev, azim=azim)
    if(view=="top" or view == "Top" or view == "TOP"):
        ax3.dist = 5.5
    if(view=="star" or view == "Star" or view == "STAR"):
        ax3.dist = 5.0 #4.5 is best value
    proj3d.persp_transformation = orthographic_proj

    # hide grid and background
    ax3.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.grid(False)

    # hide z axis in orthographic top view, xy axes in star view
    if (drawz == False):
        ax3.w_zaxis.line.set_lw(0.)
        ax3.set_zticks([])

    if (drawz == True):
        ax3.set_zlabel('Z (1000 km)',fontsize=12)

    if (drawxy == False):
        ax3.w_xaxis.line.set_lw(0.)
        ax3.set_xticks([])
        ax3.w_yaxis.line.set_lw(0.)
        ax3.set_yticks([])

    if (drawxy == True):
        ax3.set_xlabel('X (1000 km)',fontsize=12)
        ax3.set_ylabel('Y (1000 km)',fontsize=12)

```

<h2>Planet:</h2>

<pre class="lang-py prettyprint-override"><code>def draw_saturn(ax3, elev, azim):
    # Saturn dimensions
    radius = 60268. / 1000.
    radius_pole = 54364. / 1000.

    # draw Saturn
    phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0*np.pi:100j]
    x = radius*np.sin(phi)*np.cos(theta)
    y = radius*np.sin(phi)*np.sin(theta)
    z = radius_pole*np.cos(phi)

    line3 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=5, shade=False, lw=0.25)
    #line3 = ax3.plot_wireframe(x, y, z, color="w", edgecolor='b', rstride = 5, cstride=5, lw=0.25)

    ax3.tick_params(labelsize=10)

</code>```

rings:

def draw_rings(ax3, elev, azim, draw_mode):
    # Saturn dimensions
    radius = 60268. / 1000.

    # Saturn rings
    dringmin = 1.110 * radius
    dringmax = 1.236 * radius
    cringmin = 1.239 * radius
    titanringlet = 1.292 * radius
    maxwellgap = 1.452 * radius
    cringmax = 1.526 * radius
    bringmin = 1.526 * radius
    bringmax = 1.950 * radius
    aringmin = 2.030 * radius
    enckegap = 2.214 * radius
    keelergap = 2.265 * radius
    aringmax = 2.270 * radius
    fringmin = 2.320 * radius
    gringmin = 2.754 * radius
    gringmax = 2.874 * radius
    eringmin = 2.987 * radius
    eringmax = 7.964 * radius

    if (draw_mode == 'back'):
        offset = -azim*np.pi/180. - 0.5*np.pi
    if (draw_mode == 'front'):
        offset = -azim*np.pi/180. + 0.5*np.pi

    rad, theta = np.mgrid[dringmin:dringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line1 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[cringmin:cringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line2 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[bringmin:bringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line3 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[aringmin:aringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line4 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[fringmin:1.005*fringmin:2j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line7 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.1,alpha=0.)

```

<h2>Shadow:</h2>

<pre class="lang-py prettyprint-override"><code>def draw_shadowboundary(ax3, sundir):
    sqrt = np.sqrt

    #azimuthal angle between x direction and direction of sun
    alpha = np.arctan2(sundir[1],sundir[0])
    #adjustments to keep -pi/2 < alpha < pi/2
    alphaadj = 0.*np.pi/180.
    if (alpha<0.):
        alpha += 2.*np.pi
    if ((alpha >= np.pi/2.) & (alpha <= np.pi)):
        alpha += np.pi
        alphaadj = np.pi
    if ((alpha > np.pi) & (alpha <= 3.*np.pi/2.)):
        alpha -= np.pi
        alphaadj = np.pi
    if (alpha>3.*np.pi/2.):
        alpha-=2*np.pi

    #azimuthal angle between x direction and northern summer -- found using VIMS_2005_14_OMICET and VIMS_2017_053_ALPORI to define eq. of plane of Sun's annual path in chosen coordinate system: -0.193318*x + 0.1963755*y + 0.5471502*z = 0
    beta = 44.5505*np.pi/180.
    #Saturn's obliquity -- from NASA fact sheet
    psi = 26.73*np.pi/180.
    #Saturn's oblateness -- from NASA fact sheet
    obl = 0.09796
    #helpful definitions for optimization
    cpsic = np.cos(psi*np.cos(alpha+beta))
    spsic = np.sin(psi*np.cos(alpha+beta))
    calpha = np.cos(alpha)
    salpha = np.sin(alpha)
    #Saturn's projected shorter planetary axis as seen by the sun & ring inner edge
    req = 60268. / 1000.
    b = req*sqrt((1.-obl)*(1.-obl)*cpsic*cpsic + spsic*spsic)
    ringstart = 1.239 * req
    ringend = 2.270 * req
    #shadow boundary of Saturn's rings -- can approximate using a=inf and cancelling terms
    a = 9.582*1.496*10.**5
    shadowline = lambda x,y : (1/a)*sqrt((req*salpha*(-a+x*calpha*cpsic+y*salpha)*(y*calpha-x*cpsic*salpha)/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2) + calpha*(a*cpsic*(x*calpha*cpsic+y*salpha) + b*x*(a-x*calpha*cpsic-y*salpha)*spsic*spsic/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2)))**2 + (req*calpha*(a-x*calpha*cpsic-y*salpha)*(y*calpha-x*cpsic*salpha)/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2) + salpha*(a*cpsic*(x*calpha*cpsic+y*salpha)+b*x*(a-x*calpha*cpsic-y*salpha)*spsic*spsic/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2)))**2)
    #azimuthal radius & antisolar angle for inequalities
    radius = lambda x,y : np.sqrt(x**2+y**2)
    anti = lambda x,y : abs(np.arctan2(y,x)-(alpha-alphaadj))

    #properties of shadow
    samples=1200
    d = np.linspace(-3*req,3*req,samples)
    x,y = np.meshgrid(d,d)
    #z = ((radius(x,y)<=shadowline(x,y)) & (ringstart<=radius(x,y)) & (np.pi/2<=anti(x,y)) & (anti(x,y)<=3.*np.pi/2)).astype(int)
    z = ((radius(x,y)<=shadowline(x,y)) & (ringstart<=radius(x,y)) & (radius(x,y)<=ringend) & (np.pi/2<=anti(x,y)) & (anti(x,y)<=3.*np.pi/2)).astype(int)
    cmap = matplotlib.colors.ListedColormap(["k","k"])
    #add shadow to plot
    ax3.contourf(x,y,z, [0.5,1.50001], cmap=cmap,alpha=0.5)
</code>```

Combine graphics:

import matplotlib
import numpy

from math import *

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting

from mpl_toolkits.mplot3d import proj3d

def plot_results(phi, theta, sundir=[0.5, 0.5]):
    #plot_names.append("occultation_track_" + starname)
    fig2 = plt.figure(figsize=(9,9))
    ax3 = fig2.add_subplot(111, projection='3d')
    setup_saturn_plot(ax3, phi, theta, False, False, "star")
    draw_saturn(ax3, phi, theta)
    draw_rings(ax3, phi, theta, 'back')
    draw_rings(ax3, phi, theta, 'front')
    draw_shadowboundary(ax3,sundir)
    ax3.set_xlim([-200, 200])
    ax3.set_ylim([-200, 200])
    ax3.set_zlim([-200, 200])

plot_results(phi=40, theta=50, sundir = (30,60))

```

The code produces an image like this:

The grey shadow is supposed to be residing on the rings in front of the planet. However, it won't display in front of the planet, so only the little sliver of shadow to the right of the planet is actually appearing. The shadow displays correctly in all scenarios except when it needs to go in front the planet.

Any fixes for this?

答:
I'm working on getting my head around this code at the moment, but in the meantime, at least so far, this seams to be a known issue with matplotlib3d.

As @TheImportanceOfBeingErnest pointed out a long time ago, this issue appears in the mpl3d faq

My 3D plot doesn’t look right at certain viewing angles

This is probably the most commonly reported issue with mplot3d. The problem is that – from some viewing angles – a 3D object would appear in front of another object, even though it is physically behind it. This can result in plots that do not look “physically correct.”

Unfortunately, while some work is being done to reduce the occurrence of this artifact, it is currently an intractable problem, and can not be fully solved until matplotlib supports 3D graphics rendering at its core.

The problem occurs due to the reduction of 3D data down to 2D + z-order scalar. A single value represents the 3rd dimension for all parts of 3D objects in a collection. Therefore, when the bounding boxes of two collections intersect, it becomes possible for this artifact to occur. Furthermore, the intersection of two 3D objects (such as polygons or patches) can not be rendered properly in matplotlib’s 2D rendering engine.

This problem will likely not be solved until OpenGL support is added to all of the backends (patches are greatly welcomed). Until then, if you need complex 3D scenes, we recommend using MayaVi.

Body:
I am struggling with layering and zorder in python. I am making a 3D plot using matplotlib with three relevant elements: A surface_plot of a planet, a surface_plot of rings around that planet, and a contourf image that shows the planet's shadow cast onto the rings.

I want the graphics to display exactly how this scenario would look in real life, with the rings going around the planet and the shadow residing across the rings in the appropriate spot. If the shadow is behind the planet for a given POV, I want the shadow to be blocked by the planet, and vice versa if the shadow is in front of the planet for a given POV.

To be clear, this is ONLY a layering issue. I have the planet, rings, and shadow all plotting correctly. However, the shadow will not ever display in front of the planet. It acts as though the planet is "blocking" the shadow, even though the planet is supposed to be underneath the shadow in terms of layering.

I have tried every single thing I can think of in terms of zorder and rearranging which order the various plot elements are called to be drawn. The rings DO correctly display in front of the planet, but the shadow will not.

My actual code is very long. here are the relevant parts:

Plot setup:

def orthographic_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    return np.array([[1,0,0,0],
                        [0,1,0,0],
                        [0,0,a,b],
                        [0,0,0,zback]])

def setup_saturn_plot(ax3, elev, azim, drawz, drawxy,view):
    #ax3.set_aspect('equal','box')
    ax3.view_init(elev=elev, azim=azim)
    if(view=="top" or view == "Top" or view == "TOP"):
        ax3.dist = 5.5
    if(view=="star" or view == "Star" or view == "STAR"):
        ax3.dist = 5.0 #4.5 is best value
    proj3d.persp_transformation = orthographic_proj

    # hide grid and background
    ax3.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax3.grid(False)

    # hide z axis in orthographic top view, xy axes in star view
    if (drawz == False):
        ax3.w_zaxis.line.set_lw(0.)
        ax3.set_zticks([])

    if (drawz == True):
        ax3.set_zlabel('Z (1000 km)',fontsize=12)

    if (drawxy == False):
        ax3.w_xaxis.line.set_lw(0.)
        ax3.set_xticks([])
        ax3.w_yaxis.line.set_lw(0.)
        ax3.set_yticks([])

    if (drawxy == True):
        ax3.set_xlabel('X (1000 km)',fontsize=12)
        ax3.set_ylabel('Y (1000 km)',fontsize=12)

Planet:

def draw_saturn(ax3, elev, azim):
    # Saturn dimensions
    radius = 60268. / 1000.
    radius_pole = 54364. / 1000.

    # draw Saturn
    phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0*np.pi:100j]
    x = radius*np.sin(phi)*np.cos(theta)
    y = radius*np.sin(phi)*np.sin(theta)
    z = radius_pole*np.cos(phi)

    line3 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=5, shade=False, lw=0.25)
    #line3 = ax3.plot_wireframe(x, y, z, color="w", edgecolor='b', rstride = 5, cstride=5, lw=0.25)

    ax3.tick_params(labelsize=10)

rings:

def draw_rings(ax3, elev, azim, draw_mode):
    # Saturn dimensions
    radius = 60268. / 1000.

    # Saturn rings
    dringmin = 1.110 * radius
    dringmax = 1.236 * radius
    cringmin = 1.239 * radius
    titanringlet = 1.292 * radius
    maxwellgap = 1.452 * radius
    cringmax = 1.526 * radius
    bringmin = 1.526 * radius
    bringmax = 1.950 * radius
    aringmin = 2.030 * radius
    enckegap = 2.214 * radius
    keelergap = 2.265 * radius
    aringmax = 2.270 * radius
    fringmin = 2.320 * radius
    gringmin = 2.754 * radius
    gringmax = 2.874 * radius
    eringmin = 2.987 * radius
    eringmax = 7.964 * radius

    if (draw_mode == 'back'):
        offset = -azim*np.pi/180. - 0.5*np.pi
    if (draw_mode == 'front'):
        offset = -azim*np.pi/180. + 0.5*np.pi

    rad, theta = np.mgrid[dringmin:dringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line1 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[cringmin:cringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line2 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[bringmin:bringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line3 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[aringmin:aringmax:4j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line4 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.25,alpha=0.)

    rad, theta = np.mgrid[fringmin:1.005*fringmin:2j, 0.0-offset:1.0*np.pi-offset:100j]
    x = rad * np.cos(theta)
    y = rad * np.sin(theta)
    z = 0. * rad
    line7 = ax3.plot_surface(x, y, z, color="w", edgecolor='b', rstride = 8, cstride=25, shade=False, lw=0.1,alpha=0.)

Shadow:

def draw_shadowboundary(ax3, sundir):
    sqrt = np.sqrt

    #azimuthal angle between x direction and direction of sun
    alpha = np.arctan2(sundir[1],sundir[0])
    #adjustments to keep -pi/2 < alpha < pi/2
    alphaadj = 0.*np.pi/180.
    if (alpha<0.):
        alpha += 2.*np.pi
    if ((alpha >= np.pi/2.) & (alpha <= np.pi)):
        alpha += np.pi
        alphaadj = np.pi
    if ((alpha > np.pi) & (alpha <= 3.*np.pi/2.)):
        alpha -= np.pi
        alphaadj = np.pi
    if (alpha>3.*np.pi/2.):
        alpha-=2*np.pi

    #azimuthal angle between x direction and northern summer -- found using VIMS_2005_14_OMICET and VIMS_2017_053_ALPORI to define eq. of plane of Sun's annual path in chosen coordinate system: -0.193318*x + 0.1963755*y + 0.5471502*z = 0
    beta = 44.5505*np.pi/180.
    #Saturn's obliquity -- from NASA fact sheet
    psi = 26.73*np.pi/180.
    #Saturn's oblateness -- from NASA fact sheet
    obl = 0.09796
    #helpful definitions for optimization
    cpsic = np.cos(psi*np.cos(alpha+beta))
    spsic = np.sin(psi*np.cos(alpha+beta))
    calpha = np.cos(alpha)
    salpha = np.sin(alpha)
    #Saturn's projected shorter planetary axis as seen by the sun & ring inner edge
    req = 60268. / 1000.
    b = req*sqrt((1.-obl)*(1.-obl)*cpsic*cpsic + spsic*spsic)
    ringstart = 1.239 * req
    ringend = 2.270 * req
    #shadow boundary of Saturn's rings -- can approximate using a=inf and cancelling terms
    a = 9.582*1.496*10.**5
    shadowline = lambda x,y : (1/a)*sqrt((req*salpha*(-a+x*calpha*cpsic+y*salpha)*(y*calpha-x*cpsic*salpha)/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2) + calpha*(a*cpsic*(x*calpha*cpsic+y*salpha) + b*x*(a-x*calpha*cpsic-y*salpha)*spsic*spsic/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2)))**2 + (req*calpha*(a-x*calpha*cpsic-y*salpha)*(y*calpha-x*cpsic*salpha)/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2) + salpha*(a*cpsic*(x*calpha*cpsic+y*salpha)+b*x*(a-x*calpha*cpsic-y*salpha)*spsic*spsic/sqrt((y*calpha-x*cpsic*salpha)**2 + (x*spsic)**2)))**2)
    #azimuthal radius & antisolar angle for inequalities
    radius = lambda x,y : np.sqrt(x**2+y**2)
    anti = lambda x,y : abs(np.arctan2(y,x)-(alpha-alphaadj))

    #properties of shadow
    samples=1200
    d = np.linspace(-3*req,3*req,samples)
    x,y = np.meshgrid(d,d)
    #z = ((radius(x,y)<=shadowline(x,y)) & (ringstart<=radius(x,y)) & (np.pi/2<=anti(x,y)) & (anti(x,y)<=3.*np.pi/2)).astype(int)
    z = ((radius(x,y)<=shadowline(x,y)) & (ringstart<=radius(x,y)) & (radius(x,y)<=ringend) & (np.pi/2<=anti(x,y)) & (anti(x,y)<=3.*np.pi/2)).astype(int)
    cmap = matplotlib.colors.ListedColormap(["k","k"])
    #add shadow to plot
    ax3.contourf(x,y,z, [0.5,1.50001], cmap=cmap,alpha=0.5)

Combine graphics:

import matplotlib
import numpy

from math import *

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting

from mpl_toolkits.mplot3d import proj3d

def plot_results(phi, theta, sundir=[0.5, 0.5]):
    #plot_names.append("occultation_track_" + starname)
    fig2 = plt.figure(figsize=(9,9))
    ax3 = fig2.add_subplot(111, projection='3d')
    setup_saturn_plot(ax3, phi, theta, False, False, "star")
    draw_saturn(ax3, phi, theta)
    draw_rings(ax3, phi, theta, 'back')
    draw_rings(ax3, phi, theta, 'front')
    draw_shadowboundary(ax3,sundir)
    ax3.set_xlim([-200, 200])
    ax3.set_ylim([-200, 200])
    ax3.set_zlim([-200, 200])

plot_results(phi=40, theta=50, sundir = (30,60))

The code produces an image like this:

The grey shadow is supposed to be residing on the rings in front of the planet. However, it won't display in front of the planet, so only the little sliver of shadow to the right of the planet is actually appearing. The shadow displays correctly in all scenarios except when it needs to go in front the planet.

Any fixes for this?


问:
Error while uploading image file using Flask
Error
while uploading files to my  selected folder it raises the following error.

As I am new to flask I am unable to catch the error.

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

app.py

```<code>import os
#import magic
import urllib.request
#from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
app = Flask(__name__)

#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
UPLOAD_FOLDER = '/static'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the files part
        if 'files[]' not in request.files:
            flash('No file part')
            return redirect(request.url)
        files = request.files.getlist('files[]')
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File(s) successfully uploaded')
        return redirect('/')

if __name__ == "__main__":
    app.run(debug = True)
</code>```

upload.html

```<code><!doctype html>
<title>Python Flask Multiple Files Upload Example</title>
<h2>Select file(s) to upload</h2>
<p>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
</p>
<form method="post" action="/" enctype="multipart/form-data">
    <dl>
        <p>
            <input type="file" name="files[]" multiple="true" autocomplete="off" required>
        </p>
    </dl>
    <p>
        <input type="submit" value="Submit">
    </p>
</form>

</code>```

答:
You should change your code</p>

```<code>    @app.route('/', methods=['POST', 'GET'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the files part
        if 'files[]' not in request.files:
            flash('No file part')
            return redirect(request.url)
        files = request.files.getlist('files[]')
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File(s) successfully uploaded')
        return redirect('/')
    elif request.method == 'GET':
        return render_template('upload.html')
</code>```

Body:
Error
while uploading files to my  selected folder it raises the following error.

As I am new to flask I am unable to catch the error.

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

app.py

import os
#import magic
import urllib.request
#from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
app = Flask(__name__)

#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
UPLOAD_FOLDER = '/static'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the files part
        if 'files[]' not in request.files:
            flash('No file part')
            return redirect(request.url)
        files = request.files.getlist('files[]')
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File(s) successfully uploaded')
        return redirect('/')

if __name__ == "__main__":
    app.run(debug = True)

upload.html

<!doctype html>
<title>Python Flask Multiple Files Upload Example</title>

Select file(s) to upload

    {% with messages = get_flashed_messages() %}
      {% if messages %}

        {% for message in messages %}

{{ message }}

        {% endfor %}

      {% endif %}
    {% endwith %}

<form method="post" action="/" enctype="multipart/form-data">

            <input type="file" name="files[]" multiple="true" autocomplete="off" required>

        <input type="submit" value="Submit">

</form>

Body:
You should change your code

    @app.route('/', methods=['POST', 'GET'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the files part
        if 'files[]' not in request.files:
            flash('No file part')
            return redirect(request.url)
        files = request.files.getlist('files[]')
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File(s) successfully uploaded')
        return redirect('/')
    elif request.method == 'GET':
        return render_template('upload.html')


答:
Suppose you want to go "n deep", meaning that you want your last header to have n letters:

```<code>import itertools
import string

def generateHeaders(n=None):
    if n is None: nums = itertools.count(1)
    else: nums = range(1, n+1)

    for n in nums:
        yield from map(''.join, itertools.product(*([string.ascii_uppercase]*n)))
</code>```

Output testing:

```<code>for _,header in zip(range(60), generateHeaders()): print(header)

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
AA
AB
AC
AD
AE
AF
AG
AH
AI
AJ
AK
AL
AM
AN
AO
AP
AQ
AR
AS
AT
AU
AV
AW
AX
AY
AZ
BA
BB
BC
BD
BE
BF
BG
BH
</code>```

Title: Python string sequcence like excel

Body:
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)

Body:
Suppose you want to go "n deep", meaning that you want your last header to have n letters:

import itertools
import string

def generateHeaders(n=None):
    if n is None: nums = itertools.count(1)
    else: nums = range(1, n+1)

    for n in nums:
        yield from map(''.join, itertools.product(*([string.ascii_uppercase]*n)))

Output testing:

for _,header in zip(range(60), generateHeaders()): print(header)

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
AA
AB
AC
AD
AE
AF
AG
AH
AI
AJ
AK
AL
AM
AN
AO
AP
AQ
AR
AS
AT
AU
AV
AW
AX
AY
AZ
BA
BB
BC
BD
BE
BF
BG
BH


问:
Plugin incompatible with the new build found: Firebase Services

I am not able to update to Android Studio 4.0

When I check for updates, it is showing me the below message.

"Plugin incompatible with the new build found: Firebase Services."

答:
Go to File -> Settings -> Plugins -> Update Firebase services plugin if update available or Disable the plugin for time being.

The warning will be gone and you can update the Android Studio!

After disabling the plugin, the warning is gone as shown in Image


问:
What does "Uncaught TypeError: seats[Symbol.iterator] is not a function" mean?
I am making a movie seat booking app.But when I run the code, I get an error. The Google console says the error is on line 224, and that the error is "Uncaught TypeError: seats[Symbol.iterator] is not a function.

What does that mean? And why is that?

Here is my codepen link to the source code

And here is the actual code:

  <title>Tommy's movie seat booking app</title>

    Pick a movie
    <select id="movieName">
      <option value="10">Gone with the Wind ($10)</option>
      <option value="12">The Sound of Music ($12)</option>
      <option value="14">E.T. the Extra-Terrestrial ($14)</option>
      <option value="17">Titanic ($17)</option>
      <option value="20">The Ten Commandments ($20)</option>
      <option value="21">Jaws ($21)</option>
      <option value="24">Doctor Zhivago ($24)</option>
      <option value="28">The Exorcist ($28)</option>
      <option value="29">Snow White and the Seven Dwarfs ($29)</option>
      <option value="32">Avengers: Endgame ($32)</option>
      <option value="44">Star Wars ($44)</option>
    </select>

        Available

        Selected

        Occupied

You have selected 0 seats for the price of $0.

```

答:
Oh, I just figured it out! I used this piece of code:

```<code>const seatsIndex = [...selectedSeats].map(function(seats) {
  return [...seats].indexOf(seat);
})
</code>```

But instead, I should have given each seat a name, and then use this piece of code:

```<code>let seatsIndex = [...selectedSeats].map(function (seat) {
  return seat.getAttribute("name");
});
seatsIndex.shift();
</code>```

Body:
Oh, I just figured it out! I used this piece of code:

const seatsIndex = [...selectedSeats].map(function(seats) {
  return [...seats].indexOf(seat);
})

But instead, I should have given each seat a name, and then use this piece of code:

let seatsIndex = [...selectedSeats].map(function (seat) {
  return seat.getAttribute("name");
});
seatsIndex.shift();


问:
How to initialise the h_n and h_c in LSTM?
I try to use LSTM do to some classifications, and I see some examples where h_n and h_c are set to 0, can I initialise these two parameters with other values? </p>

答:
Yes, you can initialize them with any values you want.

A sample random initialization of h_n and h_c would be:

```<code>h_n = torch.randn(num_layers * num_directions, batch_size, input_size).cuda().requires_grad_(True)
h_c = torch.randn(num_layers * num_directions, batch_size, input_size).cuda().requires_grad_(True)
</code>```

num_layers is the number of layers that you have specified in your LSTM model and num_directions = 2 for bidirectional and 1 otherwise.

Note: Do .cuda() only if you want to train your model on a GPU.

Body:
Yes, you can initialize them with any values you want.

A sample random initialization of h_n and h_c would be:

h_n = torch.randn(num_layers * num_directions, batch_size, input_size).cuda().requires_grad_(True)
h_c = torch.randn(num_layers * num_directions, batch_size, input_size).cuda().requires_grad_(True)

num_layers is the number of layers that you have specified in your LSTM model and num_directions = 2 for bidirectional and 1 otherwise.

Note: Do .cuda() only if you want to train your model on a GPU.


问:
Java 7 underscore in numeric literals
When we must use a _ to separate digits in a number I don't understand the following case in which I can't use it:

In positions where a string of digits is expected

(as documented in the JDK7 guide here)

Some examples?

答:
You don't have to use "_", you can. And examples given in the proposal are credit card numbers, phone numbers, or simply numbers for which it makes sense to have a separator in the code.

For the "In positions where a string of digits is expected" it's simply in places where it's supposed to start (or end) with a digit. Here are some examples.

Note that according to this proposal, underscores can only be placed between digits. They cannot be placed by themselves in positions where a string of digits would normally be expected:

int x1 = _52;  // This is an identifier, not a numeric literal.

int x2 = 5_2;  // OK. (Decimal literal)

int x2 = 52_;  // Illegal. (Underscores must always be between digits)

int x3 = 5_______2; // OK. (Decimal literal.)

int x4 = 0_x52;  // Illegal. Can't put underscores in the "0x" radix prefix.

int x5 = 0x_52;  // Illegal. (Underscores must always be between digits)

int x6 = 0x5_2;  // OK. (Hexadecimal literal)

int x6 = 0x52_;  // Illegal. (Underscores must always be between digits)

int x6 = 0x_;    // Illegal. (Not valid with the underscore removed)

int x7 = 0_52;   // OK. (Octal literal)

int x7 = 05_2;   // OK. (Octal literal)

int x8 = 052_;   // Illegal. (Underscores must always be between digits)

Resources:

OpenJDK - Project Coin - PROPOSAL: Underscores in Numbers (Version 2)

Joe Darcy's blog - Project Coin: Project Coin: Literal Grammar Hackery

Title: Java 7 underscore in numeric literals


问:
How to split dataset into train and test when the number of samples do not match?
I'm working with PlantVillage dataset for an image classification model built with Keras, based on this example. I'm trying to divide the dataset into train and test. However, I have 1676 images and only 15 labels, each corresponding to the names of the folders containing the images. Here is the piece of code I'm working with:

```<code>x_train, x_test, y_train, y_test = train_test_split(np_image_list, image_labels, test_size=0.2, random_state=42)
</code>```

And the error I am getting:

```<code> ValueError: Found input variables with inconsistent numbers of samples: [1676, 15]
</code>```

答:
when the samples do not match then you need to concat them first. for example if you have train.csv with 100 columns including target label and test.csv with 99 columns then you need to remove the target label from train.csv and concat both train.csv and test.csv. Once you have merged both then you can split them with .iloc into your choice of samples for train and test datasets.</p>

```<code>df = 200 columns
train = df.iloc[:100,:]
test = df.iloc[100:,:]
</code>```

Body:
I'm working with PlantVillage dataset for an image classification model built with Keras, based on this example. I'm trying to divide the dataset into train and test. However, I have 1676 images and only 15 labels, each corresponding to the names of the folders containing the images. Here is the piece of code I'm working with:

x_train, x_test, y_train, y_test = train_test_split(np_image_list, image_labels, test_size=0.2, random_state=42)

And the error I am getting:

 ValueError: Found input variables with inconsistent numbers of samples: [1676, 15]

Body:
when the samples do not match then you need to concat them first. for example if you have train.csv with 100 columns including target label and test.csv with 99 columns then you need to remove the target label from train.csv and concat both train.csv and test.csv. Once you have merged both then you can split them with .iloc into your choice of samples for train and test datasets.

df = 200 columns
train = df.iloc[:100,:]
test = df.iloc[100:,:]


问:
UseExceptionHandler is not working with ExceptionHandlingPath
In an Asp.Net Core Mvc app using .Net Core 3.0, I am trying to set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

If I use:

```<code>public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler("/Error/Show");
    ...
}
</code>```

The Error controller show Action never gets hit, neither does the Error controller constructor.

If I change the code to:

```<code>public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler(new ExceptionHandlerOptions
    {
        ExceptionHandler = async context =>
        {
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                title = "An Error Occurred",
                message = "The error was caught by UseExceptionHandler"
            }));
        }
    });
    ...
}
</code>```

The expected response is returned, but I'd really like to use the ExceptionHandlingPath so that I can return json if the request was made using ajax and a razor view if the request was a standard Get.

I also tried using:

```<code>app.UseExceptionHandler(new ExceptionHandlerOptions
{
    ExceptionHandlingPath = "/Error/Show"
});
</code>```

but this behaves the same as app.UseExceptionHandler("/Error/Show")

Any ideas why ExceptionHandlingPath wouldn't work, but ExceptionHandler would work as expected?

答:
set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

I did a test with using same code to configure a custom error handling page, like below, which works as expected.

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Error/Show");

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

    });
}
</code>```

Error controller and Show action

```<code>public class ErrorController : Controller
{
    public IActionResult Show()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
</code>```

Test Result

To troubleshot the issue, please try:

1) make sure you create corresponding "/Error/Show" controller action and view

2) check if you enabled the Developer Exception Page app.UseDeveloperExceptionPage();

3) check if you add other middlewares/filters, which cause the issue.

Body:
In an Asp.Net Core Mvc app using .Net Core 3.0, I am trying to set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

If I use:

public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler("/Error/Show");
    ...
}

The Error controller show Action never gets hit, neither does the Error controller constructor.

If I change the code to:

public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler(new ExceptionHandlerOptions
    {
        ExceptionHandler = async context =>
        {
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                title = "An Error Occurred",
                message = "The error was caught by UseExceptionHandler"
            }));
        }
    });
    ...
}

The expected response is returned, but I'd really like to use the ExceptionHandlingPath so that I can return json if the request was made using ajax and a razor view if the request was a standard Get.

I also tried using:

app.UseExceptionHandler(new ExceptionHandlerOptions
{
    ExceptionHandlingPath = "/Error/Show"
});

but this behaves the same as app.UseExceptionHandler("/Error/Show")

Any ideas why ExceptionHandlingPath wouldn't work, but ExceptionHandler would work as expected?

Body:
set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

I did a test with using same code to configure a custom error handling page, like below, which works as expected.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Error/Show");

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

    });
}

Error controller and Show action

public class ErrorController : Controller
{
    public IActionResult Show()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Test Result

To troubleshot the issue, please try:

1) make sure you create corresponding "/Error/Show" controller action and view

2) check if you enabled the Developer Exception Page app.UseDeveloperExceptionPage();

3) check if you add other middlewares/filters, which cause the issue.


问:
How can I switch between tabs in a TabLayout programatically from within a fragment
How can I switch between tabs in a TabLayout programatically from within a fragment which is currently displayed in the selected tab?
I have a button in my fragment which I want to switch to the other tab\fragment, and I can not use - tabs.getTabAt(2).select(); because it does not work from inside the fragment.

答:
create method in your Activity

```<code>public void changeTab(int position){
    tabs.getTabAt(position).select();
}
</code>```

and use in your Fragment

```<code>((YourActivity) getActivity()).changeTab(2);
</code>```

Body:
create method in your Activity

public void changeTab(int position){
    tabs.getTabAt(position).select();
}

and use in your Fragment

((YourActivity) getActivity()).changeTab(2);