问:
Resources > Repository triggers not firing and default triggers not disabled in Azure DevOps yaml pipeline
I have a triggers set up in our azure-pipelines.yml like so below:

the scriptsconn represents a connection to the default/self repo that contains the deployment pipeline yaml.

the serviceconn represents a microservice repo we are building and deploying using the template and publish tasks.

We have multiple microservices with similar build pipelines, so this approach is an attempt to lessen the amount of work needed to update these steps.

Right now the issue we're running into is two fold:

no matter what branch we specify in the scriptsconn resources -> repositories section the build triggers for every commit to every branch in the repo.

no matter how we configure the trigger for serviceconn we cannot get the build to trigger for any commit, PR created, or PR merged.

According to the link below this configuration should be pretty straighforward. Can someone point out what mistake we're making?

https://github.com/microsoft/azure-pipelines-yaml/blob/master/design/pipeline-triggers.md#repositories

```<code>resources:
  repositories:
    - repository: scriptsconn
      type: bitbucket
      endpoint: BitbucketAzurePipelines
      name: $(scripts.name)
      ref: $(scripts.branch)
      trigger:
        - develop
    - repository: serviceconn
      type: bitbucket
      endpoint: BitbucketAzurePipelines
      name: (service.name)
      ref: $(service.branch)
      trigger:
        - develop
      pr:
        branches:
        - develop

variables:
  - name: service.path
    value: $(Agent.BuildDirectory)/s/$(service.name)
  - name: scripts.path
    value: $(Agent.BuildDirectory)/s/$(scripts.name)
  - name: scripts.output
    value: $(scripts.path)/$(release.folder)/$(release.filename)
  - group: DeploymentScriptVariables.Dev

stages:
- stage: Build
  displayName: Build and push an image
  jobs:
  - job: Build
    displayName: Build
    pool:
      name: 'Self Hosted 1804'
    steps:
    - checkout: scriptsconn
    - checkout: serviceconn
</code>```

答:
The document you linked to is actually a design document. So it's possible\likely that not everything on that page is implemented. In the design document I also see this line:

However, triggers are not enabled on repository resource today. So, we will keep the current behavior and in the next version of YAML we will enable the triggers by default.

The current docs on the YAML schema seem to indicate that triggers are not supported on Repository Resources yet.

Just as an FYI you can see the current supported YAML schema at this url.

https://dev.azure.com/{organization}/_apis/distributedtask/yamlschema?api-version=5.1

I am not 100% sure on what you are after template wise. General suggestion, if you are going with the reusable content template workflow, you could trigger from an azure-pipelines.yml file in each of your microservice repos, consuming the reusable steps from your template. Hope that helps!

Body:
I have a triggers set up in our azure-pipelines.yml like so below:

the scriptsconn represents a connection to the default/self repo that contains the deployment pipeline yaml.

the serviceconn represents a microservice repo we are building and deploying using the template and publish tasks.

We have multiple microservices with similar build pipelines, so this approach is an attempt to lessen the amount of work needed to update these steps.

Right now the issue we're running into is two fold:

no matter what branch we specify in the scriptsconn resources -> repositories section the build triggers for every commit to every branch in the repo.

no matter how we configure the trigger for serviceconn we cannot get the build to trigger for any commit, PR created, or PR merged.

According to the link below this configuration should be pretty straighforward. Can someone point out what mistake we're making?

https://github.com/microsoft/azure-pipelines-yaml/blob/master/design/pipeline-triggers.md#repositories

resources:
  repositories:
    - repository: scriptsconn
      type: bitbucket
      endpoint: BitbucketAzurePipelines
      name: $(scripts.name)
      ref: $(scripts.branch)
      trigger:
        - develop
    - repository: serviceconn
      type: bitbucket
      endpoint: BitbucketAzurePipelines
      name: (service.name)
      ref: $(service.branch)
      trigger:
        - develop
      pr:
        branches:
        - develop

variables:
  - name: service.path
    value: $(Agent.BuildDirectory)/s/$(service.name)
  - name: scripts.path
    value: $(Agent.BuildDirectory)/s/$(scripts.name)
  - name: scripts.output
    value: $(scripts.path)/$(release.folder)/$(release.filename)
  - group: DeploymentScriptVariables.Dev

stages:
- stage: Build
  displayName: Build and push an image
  jobs:
  - job: Build
    displayName: Build
    pool:
      name: 'Self Hosted 1804'
    steps:
    - checkout: scriptsconn
    - checkout: serviceconn


来源: stackexchange

问:
ListView inside Dynamic ListView ( Pagewise )
I'm still very new to flutter and I'm trying  to create a comment list section where the child comment can be nested in the parent comment.

What I did was create a ListView inside a dynamic ListView in this case I used a 3rd party library PagewiseListView for lazy loading. But there was some error in building the List.

```<code> @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageWiseBuilder(context, _story.kids ?? [], PAGE_SIZE),
    );
  }

  Widget pageWiseBuilder(BuildContext context, List<int> list, int pageSize) {
    if (list != null && list.length > 0) {
      return PagewiseListView(
        padding: EdgeInsets.all(15.0),
        pageSize: pageSize,
        itemBuilder: this.itemBuilder,
        pageFuture: (pageIndex) =>
            _repository.fetchComments(list, pageIndex * pageSize, pageSize),
      );
    } else {
      return Container();
    }
  }

  Widget itemBuilder(BuildContext context, Comment entry, int index) {
    return Column(
      children: <Widget>[
        ListTile(
          title: Text(entry.by ??= ""),
          subtitle: Html(
            data: unescape.convert(entry.text ??= ""),
            useRichText: true,
            onLinkTap: (url) {
              _launchURL(url);
            },
            showImages: true,
            renderNewlines: true,
          ),
        ),
        Divider(),
        Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: SizedBox(height: 200.0,
                child: ListView.builder(
                  physics: ClampingScrollPhysics(),
                  shrinkWrap: true,
                  itemCount: 5,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 8.0),
                      child: Text('Nested list item $index'),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }
</code>```

I/flutter (  885): Another exception was thrown: RenderFlex children
  have non-zero flex but incoming height constraints are unbounded.

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#a1031 relayoutBoundary=up6 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#11980 relayoutBoundary=up5 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderFlex children
  have non-zero flex but incoming height constraints are unbounded.

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#a33b5 relayoutBoundary=up6 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#48c2a relayoutBoundary=up5 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderRepaintBoundary#d6726 relayoutBoundary=up4 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown:
  'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed
  assertion: line 549 pos 12: 'child.hasSize': is not true.

I/flutter (  885): Another exception was thrown: NoSuchMethodError:
  The method '>' was called on null.

I/flutter (  885): Another exception was thrown:
  'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed
  assertion: line 549 pos 12: 'child.hasSize': is not true.

答: I think you need to remove any Flexible in your code, It works for me.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm still very new to flutter and I'm trying  to create a comment list section where the child comment can be nested in the parent comment.

What I did was create a ListView inside a dynamic ListView in this case I used a 3rd party library PagewiseListView for lazy loading. But there was some error in building the List.

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageWiseBuilder(context, _story.kids ?? [], PAGE_SIZE),
    );
  }

  Widget pageWiseBuilder(BuildContext context, List<int> list, int pageSize) {
    if (list != null && list.length > 0) {
      return PagewiseListView(
        padding: EdgeInsets.all(15.0),
        pageSize: pageSize,
        itemBuilder: this.itemBuilder,
        pageFuture: (pageIndex) =>
            _repository.fetchComments(list, pageIndex * pageSize, pageSize),
      );
    } else {
      return Container();
    }
  }

  Widget itemBuilder(BuildContext context, Comment entry, int index) {
    return Column(
      children: <Widget>[
        ListTile(
          title: Text(entry.by ??= ""),
          subtitle: Html(
            data: unescape.convert(entry.text ??= ""),
            useRichText: true,
            onLinkTap: (url) {
              _launchURL(url);
            },
            showImages: true,
            renderNewlines: true,
          ),
        ),
        Divider(),
        Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: SizedBox(height: 200.0,
                child: ListView.builder(
                  physics: ClampingScrollPhysics(),
                  shrinkWrap: true,
                  itemCount: 5,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 8.0),
                      child: Text('Nested list item $index'),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

I/flutter (  885): Another exception was thrown: RenderFlex children
  have non-zero flex but incoming height constraints are unbounded.

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#a1031 relayoutBoundary=up6 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#11980 relayoutBoundary=up5 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderFlex children
  have non-zero flex but incoming height constraints are unbounded.

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#a33b5 relayoutBoundary=up6 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderFlex#48c2a relayoutBoundary=up5 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown: RenderBox was not
  laid out: RenderRepaintBoundary#d6726 relayoutBoundary=up4 NEEDS-PAINT
  NEEDS-COMPOSITING-BITS-UPDATE

I/flutter (  885): Another exception was thrown:
  'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed
  assertion: line 549 pos 12: 'child.hasSize': is not true.

I/flutter (  885): Another exception was thrown: NoSuchMethodError:
  The method '>' was called on null.

I/flutter (  885): Another exception was thrown:
  'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed
  assertion: line 549 pos 12: 'child.hasSize': is not true.


问:
react node csv postgres
I am trying to process a csv file from react to postgres using node and express.  What is the recommended way of doing this?  Should I first upload the file onto the node server then do bulk insert (copy) into postgres or parse the csv in react and do the insert into postgres in the post request?  Thanks!</p>

答: Thanks for the replies.  I ended up uploading the file and used an extension call pg-format to do the bulk insert.</p>

Title: react node csv postgres


问:
ssh_exchange_identification: Connection closed by remote host under Git bash
I work at win7 and set up git server with sshd.
I git --bare init myapp.git, and clone ssh://git@localhost/home/git/myapp.git in Cywgin correctly. But I need config git of Cygwin again, I want to git clone in Git Bash. I run git clone ssh://git@localhost/home/git/myapp.git and get following message

```<code>ssh_exchange_identification: Connection closed by remote host
</code>```

then I run ssh -vvv git@localhost in Git Bash and get message

```<code>debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host
</code>```

it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without BEGIN and END.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.

Any advises are welcome.
btw, I have read first 3 pages on google about this problem.

答:
In windows machine, remove the content of config file present in C:\Users{yourusername}.ssh

This worked well for me.

ContentLicense: CC BY-SA 3.0

Body:
I work at win7 and set up git server with sshd.
I git --bare init myapp.git, and clone ssh://git@localhost/home/git/myapp.git in Cywgin correctly. But I need config git of Cygwin again, I want to git clone in Git Bash. I run git clone ssh://git@localhost/home/git/myapp.git and get following message

ssh_exchange_identification: Connection closed by remote host

then I run ssh -vvv git@localhost in Git Bash and get message

debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host

it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without BEGIN and END.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.

Any advises are welcome.
btw, I have read first 3 pages on google about this problem.


问:
Making a series of plots that proceed by a click
In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)

```<code>for (i in 1:5){
    plot(1:i)
    Sys.sleep(1)
    #add something here that requests mouse click to proceed
}
</code>```

Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.

It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?

Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.

Thanks

Tom

答:
For scrolling back and forth between plots using the arrow keys: it depends on the platform/R interface.

Windows: there is a recording function (see Q5 of the R for Windows FAQ) which uses Page Up/Page Down

MacOS: under the standard GUI, the Quartz window has Apple-left and Apple-right arrow

under the standard Unix (no-GUI) interface, things are more limited.  You can use RStudio (which has a lot of buzz right now) ... I would have thought that JGR would have plot history as well, but it doesn't seem to ...

Body:
In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)

for (i in 1:5){
    plot(1:i)
    Sys.sleep(1)
    #add something here that requests mouse click to proceed
}

Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.

It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?

Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.

Thanks

Tom


问:
Spring Boot OAuth2 Security properties names in .properties files?
I'm currently learning and experimenting with the different Spring Boot Security OAuth2 packages and I'm really confused with the actual configuration properties names. I found on the internet and on multiple Spring Documentation pages different naming schemes for these properties. For example I found

```<code>security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri
spring.security.oauth2.resource.token-info-uri=xxx
spring.security.oauth2.resourceserver ...
...
</code>```

I'm trying to make sense of all this and would like to know what are the differences with all of them. Are they version related, package related, are they typos, are some names deprecated, ... ?

Regards

P.S. I'm currently using Spring Boot 2.2.4

答:
There are two OAuth implementations for Spring Security: the deprecated Spring Security OAuth project and the new Spring Security 5 OAuth classes.

These properties are for the deprecated project:

```<code>security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri
</code>```

And these are for Spring Security 5:

```<code>spring.security.oauth2.resource.token-info-uri=...
spring.security.oauth2.resourceserver=...
</code>```

You can find more info in this SO question.

PS. Using the spring-boot-starter-security starter will import Spring Security 5.

Body:
I'm currently learning and experimenting with the different Spring Boot Security OAuth2 packages and I'm really confused with the actual configuration properties names. I found on the internet and on multiple Spring Documentation pages different naming schemes for these properties. For example I found

security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri
spring.security.oauth2.resource.token-info-uri=xxx
spring.security.oauth2.resourceserver ...
...

I'm trying to make sense of all this and would like to know what are the differences with all of them. Are they version related, package related, are they typos, are some names deprecated, ... ?

Regards

P.S. I'm currently using Spring Boot 2.2.4

Body:
There are two OAuth implementations for Spring Security: the deprecated Spring Security OAuth project and the new Spring Security 5 OAuth classes.

These properties are for the deprecated project:

security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri

And these are for Spring Security 5:

spring.security.oauth2.resource.token-info-uri=...
spring.security.oauth2.resourceserver=...

You can find more info in this SO question.

PS. Using the spring-boot-starter-security starter will import Spring Security 5.


问:
How to plot a graph of expected vs actual values in python?
Current Dataframe

```<code>          Original      Predicted
0           1059         810.37
1           1441         527.76
2           977          366.07
...
744         2000         1878.18
</code>```

Expected Graph

<img src="https://i.stack.imgur.com/X9eL3.png" alt="Henter code here">

Code that I have tried:

```<code>plt.plot(arr, sub_df['original'], 'b-', label = 'actual')
plt.plot(arr, sub_df['predicted'], 'ro', label = 'prediction')
plt.xticks(rotation = '60');
plt.legend()
</code>```

Current Output:

答:
assuming df is your DataFrame:    </p>

```<code>import matplotlib.pyplot as plt
plt.plot(df.Original)
plt.plot(df.Predicted, 'o')

plt.show()
</code>```

Body:
Current Dataframe

          Original      Predicted
0           1059         810.37
1           1441         527.76
2           977          366.07
...
744         2000         1878.18

Expected Graph

<img src="https://i.stack.imgur.com/X9eL3.png" alt="Henter code here">

Code that I have tried:

plt.plot(arr, sub_df['original'], 'b-', label = 'actual')
plt.plot(arr, sub_df['predicted'], 'ro', label = 'prediction')
plt.xticks(rotation = '60');
plt.legend()

Current Output:

Body:
assuming df is your DataFrame:

import matplotlib.pyplot as plt
plt.plot(df.Original)
plt.plot(df.Predicted, 'o')

plt.show()


问:
change (lack of) user input to default string value
This is probably a straight forward question but I don't have the Python fundamentals down yet (running before walking)

I want user inputs for the following (coordinate) variables:

source_x = input('enter blast x: ')
source_y = input('enter blast y: ')
source_z = input('enter blast z: ')
receiver_x = input('enter receiver x: ')
receiver_y = input('enter receiver y: ')
receiver_z = input('enter receiver z: ')
```

<p>When the user input is <kbd>Enter</kbd> for the <code>z</code> coordinate (or any other), the following error arises:</p>

<pre class="lang-py prettyprint-override"><code>    source_z = float(source_z)
ValueError: could not convert string to float: ''
</code>```

I understand the error, the Enter input was seen as a string, but is there a quick way to identify and convert the Enter input to (e.g.) a 0?

Just in case I want to undertake bulk imports and not stop my calculations further down the code.

kind regards

答:
Input always returns a string. You could do variable = int(number inputted).

Also, just use a try/except statement and assign a default value in the except clause
>
    Try:
        Num1 = int(input("Enter a number"))
        #mathematical function or whatever
    Except Exception as e:
        Num1=int(10) #or whatever default number
        print(e) #for troubleshooting

Body:
This is probably a straight forward question but I don't have the Python fundamentals down yet (running before walking)

I want user inputs for the following (coordinate) variables:

source_x = input('enter blast x: ')
source_y = input('enter blast y: ')
source_z = input('enter blast z: ')
receiver_x = input('enter receiver x: ')
receiver_y = input('enter receiver y: ')
receiver_z = input('enter receiver z: ')

When the user input is Enter for the z coordinate (or any other), the following error arises:

    source_z = float(source_z)
ValueError: could not convert string to float: ''

I understand the error, the Enter input was seen as a string, but is there a quick way to identify and convert the Enter input to (e.g.) a 0?

Just in case I want to undertake bulk imports and not stop my calculations further down the code.

kind regards


问:
using bash command in perl
i have short bash code

```<code>cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'
</code>```

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

```<code>@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');
</code>```

Thanks for helping...

答:
Couldn't help making a pure perl version... should work the same, if I remember my very scant awk correctly.</p>

```<code>use strict;
use warnings;

open A, '<', '/path/example.txt' or die $!;
my @array = map { (split(/=/,(split(/,/,$_))[0]))[1] . "\n" } (grep /mail/, <A>);
</code>```

Title: using bash command in perl

Body:
i have short bash code

cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');

Thanks for helping...

Body:
Couldn't help making a pure perl version... should work the same, if I remember my very scant awk correctly.

use strict;
use warnings;

open A, '<', '/path/example.txt' or die $!;
my @array = map { (split(/=/,(split(/,/,$_))[0]))[1] . "\n" } (grep /mail/, <A>);


问:
Vue.js warns You may have an infinite update loop in a component render function
I'm quite new to Vue.js & Buefy and I believe I understand why this happens but have no idea how to fix it.

I have a list of project partners sorted by country and I need to output a list with checkboxes (I'm using Buefy on the page anyway) and country names as title (only when there's a "new" country). This ends with browser doing infinite loop (verified with console.log) and Vue Devtools gives warning "You may have an infinite update loop in a component render function".

I believe this happens because changing prevTitle triggers re-rendering. I know it's not possible to pass parameters to computed properties and I haven't been able to use any of the tricks I've found to make partner.country available there.

```<code>var app = new Vue({
    el: "#app",
    data: {
      prevTitle: ""
    ...

    methods: {
      changeCountryTitle(country) {
        if (country != this.prevTitle) {
          this.prevTitle = country;
          return true;
        }
        return false;
    }
</code>```

```<code><template v-for="partner in results">
    <div v-if="changeCountryTitle(partner.country)">
        {{ partner.country }}
    </div>
    <b-checkbox ... >{{ partner.name }}, ...</b-checkbox>
    <br />
</template>
</code>```

Then I tried to make a computed property where I do all processing instead of for loop in template and return a string that contains everything, including Buefy tags, which would be called

```<code><span v-html="printPartnerList"></span>
</code>```

But those Buefy tags don't get rendered properly, only HTML tags work, browser ignores Buefy tags showing the normal text only.

Any ideas how get this working? For time being I print country names for each partner after name etc. but it's not how this is supposed to work.

答:
v-html doesn't evaluate Vue (or in this case Buefy) components, only regular HTML tags.

Your first approach wasn't that bad, but instead of calling a method inside the v-for you can add a computed property in the items that tells if the country should be rendered:

```<code><template v-for="partner in computedResults">
    <div v-if="partner.showCountry">
        {{ partner.country }}
    </div>
    <b-checkbox ... >{{ partner.name }}, ...</b-checkbox>
    <br />
</template>
</code>```

New app:

```<code>var app = new Vue({
    el: "#app",
    data: {
      // prevTitle: "" <- not needed
    ...

    computed: {
      computedResults() {
        let prevCountry = ''
        let newResults = []
        this.results.forEach(partner => {
          let showCountry = false
          if (prevCountry != partner.country) {
            showCountry = true
          }
          newResults.push({
            ...partner,
            showCountry
          })
          prevCountry = partner.country
        })
        return newResults
      }
</code>```

Body:
I'm quite new to Vue.js & Buefy and I believe I understand why this happens but have no idea how to fix it.

I have a list of project partners sorted by country and I need to output a list with checkboxes (I'm using Buefy on the page anyway) and country names as title (only when there's a "new" country). This ends with browser doing infinite loop (verified with console.log) and Vue Devtools gives warning "You may have an infinite update loop in a component render function".

I believe this happens because changing prevTitle triggers re-rendering. I know it's not possible to pass parameters to computed properties and I haven't been able to use any of the tricks I've found to make partner.country available there.

var app = new Vue({
    el: "#app",
    data: {
      prevTitle: ""
    ...

    methods: {
      changeCountryTitle(country) {
        if (country != this.prevTitle) {
          this.prevTitle = country;
          return true;
        }
        return false;
    }

<template v-for="partner in results">

        {{ partner.country }}

    {{ partner.name }}, ...

</template>

Then I tried to make a computed property where I do all processing instead of for loop in template and return a string that contains everything, including Buefy tags, which would be called

But those Buefy tags don't get rendered properly, only HTML tags work, browser ignores Buefy tags showing the normal text only.

Any ideas how get this working? For time being I print country names for each partner after name etc. but it's not how this is supposed to work.

Body:
v-html doesn't evaluate Vue (or in this case Buefy) components, only regular HTML tags.

Your first approach wasn't that bad, but instead of calling a method inside the v-for you can add a computed property in the items that tells if the country should be rendered:

<template v-for="partner in computedResults">
    <div v-if="partner.showCountry">
        {{ partner.country }}
    </div>
    <b-checkbox ... >{{ partner.name }}, ...</b-checkbox>
    <br />
</template>

New app:

var app = new Vue({
    el: "#app",
    data: {
      // prevTitle: "" <- not needed
    ...

    computed: {
      computedResults() {
        let prevCountry = ''
        let newResults = []
        this.results.forEach(partner => {
          let showCountry = false
          if (prevCountry != partner.country) {
            showCountry = true
          }
          newResults.push({
            ...partner,
            showCountry
          })
          prevCountry = partner.country
        })
        return newResults
      }


问:
Setting up your own localhost server?
I'm trying to understand something that's been bugging me. I recently completed a frontend assignment that came with backend server/api node.js code. The server ran on localhost:4000 and the frontend ran on localhost:3000.

My question is, if it's a localhost server, does this generally mean it's not connected to any external database? I have the server/api code, I ran npm start on it and the response was "working!" Then I made api calls.

For context, the frontend made calls to a bakery api that pulled data for cupcakes: bases, frostings, etc. Below is an example of the db.json file.

```<code>{
  "bases": [
    {
      "key": "peanutButterBase",
      "name": "Peanut Butter Base",
      "price": 85,
      "ingredients": [
        "peanut butter cup cake"
      ]
    },
    ...
  ],
  "frostings": [
    {
      "key": "vanillaFrosting",
      "name": "Vanilla Frosting",
      "price": 15,
      "ingredients": [
        "vanilla frosting"
      ]
    },
    ...
 ],
</code>```

This may be a ridiculous question, but is it possible to make a small app building your own mock server and api that merely runs locally? I want to use this for my portfolio but I want to build my own server/api that a hypothetical user could run and I want to make sure this is something that's actually possible and I'm looking at this correctly (i.e. this is not connected to say AWS or some other external server somewhere).

Btw, I understand this would mean it couldn't be an actual live site.

答: You can use a tool such as json-server to quickly implement a mock API server, that simply returns the JSON you've specified. It's a quick way to get a server running with some mock responses, and from your question sounds like it would be a good solution.</p>

Title: Setting up your own localhost server?

Body:
I'm trying to understand something that's been bugging me. I recently completed a frontend assignment that came with backend server/api node.js code. The server ran on localhost:4000 and the frontend ran on localhost:3000.

My question is, if it's a localhost server, does this generally mean it's not connected to any external database? I have the server/api code, I ran npm start on it and the response was "working!" Then I made api calls.

For context, the frontend made calls to a bakery api that pulled data for cupcakes: bases, frostings, etc. Below is an example of the db.json file.

{
  "bases": [
    {
      "key": "peanutButterBase",
      "name": "Peanut Butter Base",
      "price": 85,
      "ingredients": [
        "peanut butter cup cake"
      ]
    },
    ...
  ],
  "frostings": [
    {
      "key": "vanillaFrosting",
      "name": "Vanilla Frosting",
      "price": 15,
      "ingredients": [
        "vanilla frosting"
      ]
    },
    ...
 ],

This may be a ridiculous question, but is it possible to make a small app building your own mock server and api that merely runs locally? I want to use this for my portfolio but I want to build my own server/api that a hypothetical user could run and I want to make sure this is something that's actually possible and I'm looking at this correctly (i.e. this is not connected to say AWS or some other external server somewhere).

Btw, I understand this would mean it couldn't be an actual live site.


问:
remainders for fractions in python
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

```<code>print(1%2)
=1

print(2%4)
=2
</code>```

答: What you are asking is a mod % symbol it isn't the same as division /.  Mod operator returns the remainder after integer division of its first argument by its second so if you divide 5 by 2 there is a 1 as remainder. If you try to divide a smaller number by a larger number you get the smaller number 1/2 is not divisible so 1 is the remainder.</p>

Title: remainders for fractions in python

Body:
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

print(1%2)
=1

print(2%4)
=2


问:
How to assign variables in a mailgun email template (Node js)?
I've made a google cloud function in which I send an email with some variables I receive from another place.
I'm using mailgun.js and I'm trying to send the email with a template I've already created in mailgun.
The issue is that I can't find a way to replace the placeholder variables in my template.

This is the code:

```<code>mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))
</code>```

The mailgun docs says this:

```<code>var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};
</code>```

As far as I know one cannot write "h:X-Mailgun-Variables" as a key in any object.

Does anybody know where or how do I need to put it?

I thought that it should be sent as a header but neither mailgun/mailgun-js nor highlycaffeinated/mailgun-js specifies how to pass headers.

答:
i have done same thing in NodeJs but using Nodemailer
So first i have render the file using EJS and by sending the variables to the file and then send the same file to user </p>

<p>So it helped me to assigned different attribute in my file as i like here is the code </p>

```<code>function generateToken_And_SendMail(user)
{
   token = jwt.sign(user,process.env.privateKey)
  ejs.renderFile(__dirname + '/verification_email.ejs',{verify_token : `${process.env.localhost_address}/verifyToken?Authorization=Bearer%20${token}`
                                                        ,username : user.Fullname},(error,file)=>
  {
    if(error)
    console.log(error)
    else
    sendmail_Config(file,user.userEmail,'Email Verification')
  })
   return token
}
</code>```

Body:
I've made a google cloud function in which I send an email with some variables I receive from another place.
I'm using mailgun.js and I'm trying to send the email with a template I've already created in mailgun.
The issue is that I can't find a way to replace the placeholder variables in my template.

This is the code:

mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))

The mailgun docs says this:

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};

As far as I know one cannot write "h:X-Mailgun-Variables" as a key in any object.

Does anybody know where or how do I need to put it?

I thought that it should be sent as a header but neither mailgun/mailgun-js nor highlycaffeinated/mailgun-js specifies how to pass headers.

Body:
i have done same thing in NodeJs but using Nodemailer
So first i have render the file using EJS and by sending the variables to the file and then send the same file to user

So it helped me to assigned different attribute in my file as i like here is the code

function generateToken_And_SendMail(user)
{
   token = jwt.sign(user,process.env.privateKey)
  ejs.renderFile(__dirname + '/verification_email.ejs',{verify_token : `${process.env.localhost_address}/verifyToken?Authorization=Bearer%20${token}`
                                                        ,username : user.Fullname},(error,file)=>
  {
    if(error)
    console.log(error)
    else
    sendmail_Config(file,user.userEmail,'Email Verification')
  })
   return token
}


问:
SWIFT_VERSION '5.0' is unsupported, supported versions are: 3.0, 4.0, 4.2. (in target 'SwiftyJSON')
I am getting this error while trying to install react-native-charts-wrapper. I have followed the steps exactly as they say but still not able to build the project successfully.

I also set the SWIFT_VERSION to 4.2 in build settings of my project, still getting the same error.

My XCODE version: Version 10.1 (10B61)

Any ideas?

答:
"Normally this error comes from the pods(dependencies like Alamofire, SwiftyJSON ets) you have installed."

To solve the problem, follow these steps:

(See the image below for illustration)

Select 'Pods' on the project tree

Select a dependency from TARGETS: select one dependecy at a time then do step 3 and step 4 for each targets

Make sure 'Build Settings' tab selected

Scroll up and down and find out 'Swift Language Version'. Select a version, for example 'Swift 4.2'

If you have multiple dependency installed, you have to set 'Swift Language Version' for each of them. (look at the image, this project have 2 dependencies: Alamofire and SwiftyJSON, so I have done 2 times step 2 to step 4)

Restart Xcode then build

hope the error gone.


问:
How to I get to my desktop when using "python3 -m http.server 8080"?
I am running a Windows Subsystem for Linux on my Win10 machine. I have another VM machine that is a windows7. When I access the localhost:8080 I want it to open to my desktop or just load my documents, music, downloads, desktop, pictures folders. Pretty much I am stuck because I do not know how to navigate to my desktop because all I see is

directory listing

I want to be able to see documents, music, downloads, desktop, pictures folders, etc. I know there is a way to dd it but I forgot how.

答:
I don't do windows, but you need to find the c:\ or where ever the directories you're hoping to see in your shell, and start the python3 -m http.server 8080 from there.

Edit:
Did some poking, you can cd /mnt/c/Users/<USERNAME> and start python from there ...


问:
What is the problem with using an instance of the following class to share between threads?
I'm being asked what is the problem of using an instance of the following class to share between threads.
What are the risks? And what are possible solutions?</p>

```<code>public class States {

    private String[] states = new String[] {
        "UNK", "NEW", "RUNNING", "DONE"
    };

    public String[] getStates() {
        return states;
    }
}
</code>```

答: The problem with this code is that although arrays are immutable in java but because you expose a reference to the array, nothing prevents anyone to reassign the whole array with a new one. It is better to use enum classes for this use case.</p>

Body:
I'm being asked what is the problem of using an instance of the following class to share between threads.
What are the risks? And what are possible solutions?

public class States {

    private String[] states = new String[] {
        "UNK", "NEW", "RUNNING", "DONE"
    };

    public String[] getStates() {
        return states;
    }
}


问:
Need to implement onPress logic on react native app to perfume two tasks
Hey stackoverflow I am new in react native world learning it through documentation and tutorials. My problem is I want to perform two tasks on single button-through onPress. Here is what I want I have two pages. On first page user enter his phone number and I save it in DB. When user press verify button it inserts the value in DB now I want the behaviour when user press button the data is inserted and my user move to second screen basically two onPress on one single button how I achieve this kind of functionality my code :

//mobilecheck.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button} from 'react-native';

export default class MobileCheck extends React.Component
{

    constructor(){
         super()
         this.state = {
            TextInput_mobile_number: '',
            mobile_number: '', loading: false, disabled: false

         }

    }

    sendDatafun=()=>{
        this.props.navigation.navigate('VerifyCode',{
            mobile_number:this.state.mobile_number
        });

    }

    saveData = () =>
    {
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/mobile_checkapi.php',
            {
                method: 'POST',
                headers:
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    mobile_number: this.state.mobile_number,

                })

            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });

    }

    render()
    {
        const { navigate } = this.props.navigation;
        return(
            <View style = { styles.container }>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Mobile Number" style = { styles.textInput } onChangeText = {(text) => this.setState({ mobile_number: text })}
               // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
                keyboardType={'numeric'}

                />

                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData } onPress={this.sendDatafun}  >
                    <Text style = { styles.btnText }>Get Code</Text>

                </TouchableOpacity>
                <Button title = 'Next'
                    onPress={this.sendDatafun}
                />

                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }

            </View>
        );
    }
}
//verifycode.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button } from 'react-native';

export default class VerifyCode extends React.Component
{
    constructor(props)
    {
        super(props);

        this.state = {
            code: '',
            TextInput_mobile_number: '',
            mobile_number: '',

            // new code
            UserName: '',
            UserEmail: '',
            UserPassword: '',
            UserCity: '',

            loading: false,
            disabled: false,

        }
    }
//     nextbutton = () =>
//   {
//      this.props.navigation.navigate('SignUp');

//   }

    saveData = () =>
    {

        // new code
        const { UserName }  = this.state ;
        const { UserEmail }  = this.state ;
        const { UserPassword }  = this.state ;
        const { UserCity }  = this.state ;
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/verify_codeapi.php',
            {
                method: 'POST',
                headers:
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    code: this.state.code,
                    mobile_number: this.props.navigation.state.params.mobile_number,

                    //new code
                    user_name: UserName,

                    user_email: UserEmail,

                    user_password: UserPassword,

                    user_city: UserCity,

                })

            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });
    }

    render()
    {
        return(
            <View style = { styles.container }>

                <Text style={styles.textStyle}>
                We send verification code to : {this.props.navigation.state.params.mobile_number}
                </Text>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Verification Code" style = { styles.textInput } onChangeText = {(text) => this.setState({code: text })}
                    keyboardType={'numeric'}
                />
                <TextInput
                placeholder="Enter Your Full Name"
                onChangeText={UserName => this.setState({ UserName })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Email"
                onChangeText={UserEmail => this.setState({ UserEmail })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Password"
                onChangeText={UserPassword => this.setState({ UserPassword })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your City name"
                onChangeText={UserCity => this.setState({ UserCity })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData }>
                   <Text style = { styles.btnText }>Verify</Text>
                </TouchableOpacity>
                <Button title = 'Next'
                    onPress={this.nextbutton}
                />

                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }

            </View>
        );
    }
}```

答:
In your scenario inside mobilecheck.js file you can add navigation inside saveData()  function according to the response from API. Same logic apply for verifycode.js file

Try this

```<code>//mobilecheck.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class MobileCheck extends React.Component {
  constructor() {
    super();
    this.state = {
      TextInput_mobile_number: "",
      mobile_number: "",
      loading: false,
      disabled: false
    };
  }

  //   sendDatafun = () => {
  //     this.props.navigation.navigate("VerifyCode", {
  //       mobile_number: this.state.mobile_number
  //     });
  //   };

  saveData = () => {
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/mobile_checkapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          mobile_number: this.state.mobile_number
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          //Accroding to your response you can handle events
          this.props.navigation.navigate("VerifyCode", {
            mobile_number: this.state.mobile_number
          });
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Mobile Number"
          style={styles.textInput}
          onChangeText={text => this.setState({ mobile_number: text })}
          // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
          keyboardType={"numeric"}
        />

        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Get Code</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.sendDatafun} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}
//verifycode.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class VerifyCode extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      code: "",
      TextInput_mobile_number: "",
      mobile_number: "",

      // new code
      UserName: "",
      UserEmail: "",
      UserPassword: "",
      UserCity: "",

      loading: false,
      disabled: false
    };
  }
  //     nextbutton = () =>
  //   {
  //      this.props.navigation.navigate('SignUp');

  //   }

  saveData = () => {
    // new code
    const { UserName } = this.state;
    const { UserEmail } = this.state;
    const { UserPassword } = this.state;
    const { UserCity } = this.state;
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/verify_codeapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          code: this.state.code,
          mobile_number: this.props.navigation.state.params.mobile_number,

          //new code
          user_name: UserName,

          user_email: UserEmail,

          user_password: UserPassword,

          user_city: UserCity
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          this.props.navigation.navigate("SignUp");
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.textStyle}>
          We send verification code to :{" "}
          {this.props.navigation.state.params.mobile_number}
        </Text>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Verification Code"
          style={styles.textInput}
          onChangeText={text => this.setState({ code: text })}
          keyboardType={"numeric"}
        />
        <TextInput
          placeholder="Enter Your Full Name"
          onChangeText={UserName => this.setState({ UserName })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Email"
          onChangeText={UserEmail => this.setState({ UserEmail })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Password"
          onChangeText={UserPassword => this.setState({ UserPassword })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your City name"
          onChangeText={UserCity => this.setState({ UserCity })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Verify</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.nextbutton} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}
</code>```

Or if you want to add two functions inside one single button press you can do like this,

```<code>functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableOpacity onPress={() => { this.functionOne(); this.functionTwo(); }/>
</code>```

Body:
In your scenario inside mobilecheck.js file you can add navigation inside saveData()  function according to the response from API. Same logic apply for verifycode.js file

Try this

//mobilecheck.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class MobileCheck extends React.Component {
  constructor() {
    super();
    this.state = {
      TextInput_mobile_number: "",
      mobile_number: "",
      loading: false,
      disabled: false
    };
  }

  //   sendDatafun = () => {
  //     this.props.navigation.navigate("VerifyCode", {
  //       mobile_number: this.state.mobile_number
  //     });
  //   };

  saveData = () => {
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/mobile_checkapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          mobile_number: this.state.mobile_number
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          //Accroding to your response you can handle events
          this.props.navigation.navigate("VerifyCode", {
            mobile_number: this.state.mobile_number
          });
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Mobile Number"
          style={styles.textInput}
          onChangeText={text => this.setState({ mobile_number: text })}
          // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
          keyboardType={"numeric"}
        />

        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Get Code</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.sendDatafun} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}
//verifycode.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class VerifyCode extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      code: "",
      TextInput_mobile_number: "",
      mobile_number: "",

      // new code
      UserName: "",
      UserEmail: "",
      UserPassword: "",
      UserCity: "",

      loading: false,
      disabled: false
    };
  }
  //     nextbutton = () =>
  //   {
  //      this.props.navigation.navigate('SignUp');

  //   }

  saveData = () => {
    // new code
    const { UserName } = this.state;
    const { UserEmail } = this.state;
    const { UserPassword } = this.state;
    const { UserCity } = this.state;
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/verify_codeapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          code: this.state.code,
          mobile_number: this.props.navigation.state.params.mobile_number,

          //new code
          user_name: UserName,

          user_email: UserEmail,

          user_password: UserPassword,

          user_city: UserCity
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          this.props.navigation.navigate("SignUp");
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.textStyle}>
          We send verification code to :{" "}
          {this.props.navigation.state.params.mobile_number}
        </Text>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Verification Code"
          style={styles.textInput}
          onChangeText={text => this.setState({ code: text })}
          keyboardType={"numeric"}
        />
        <TextInput
          placeholder="Enter Your Full Name"
          onChangeText={UserName => this.setState({ UserName })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Email"
          onChangeText={UserEmail => this.setState({ UserEmail })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Password"
          onChangeText={UserPassword => this.setState({ UserPassword })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your City name"
          onChangeText={UserCity => this.setState({ UserCity })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Verify</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.nextbutton} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}

Or if you want to add two functions inside one single button press you can do like this,

functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableOpacity onPress={() => { this.functionOne(); this.functionTwo(); }/>


问:
"Display Language" change in Pepper Robot

The pepper was factory-reseted multiple times, and the language was selected as English, but the default screen shows Japanese. When I click 'sort' button (In japanese), it shows below warning.

Does pepper Display have it's own language setting?

答:
The issue seems to be that English isn't enabled as a language for the app launcher. To change this, you need to copy the app launcher files off the robot, edit them in Choregraphe, then re-upload the app launcher.

Copying the files off the robot

Open Powershell / terminal and copy the robot's app launcher to your PC using SCP

```<code>scp -r nao@<nao-ip>:/home/nao/.local/PackageManager/apps/zzzzzzzzz_a2d762fb-cce8-464d-b604-da55ea7245ad_ral <path-to-copy-to>
</code>```

Make a new blank Choregraphe app and save it

Copy the contents of the app folder you got from the robot into the blank Choregraphe app

Open the Choregraphe app, click Properties under Project Files, then enable English under Supported Languages.

In Robot applications, click the first button: "Package and install current project to the robot"

Unfortunately the app launcher will still show some text in Japanese, but the sort function will now work.

Body:
The issue seems to be that English isn't enabled as a language for the app launcher. To change this, you need to copy the app launcher files off the robot, edit them in Choregraphe, then re-upload the app launcher.

Copying the files off the robot

Open Powershell / terminal and copy the robot's app launcher to your PC using SCP

scp -r nao@<nao-ip>:/home/nao/.local/PackageManager/apps/zzzzzzzzz_a2d762fb-cce8-464d-b604-da55ea7245ad_ral <path-to-copy-to>

Make a new blank Choregraphe app and save it

Copy the contents of the app folder you got from the robot into the blank Choregraphe app

Open the Choregraphe app, click Properties under Project Files, then enable English under Supported Languages.

In Robot applications, click the first button: "Package and install current project to the robot"

Unfortunately the app launcher will still show some text in Japanese, but the sort function will now work.


问:
Storing a pyspark dataframe to local file system using pandas
I have a pyspark dataframe that I'm converting to pandas to store it as csv on my local file system, but pandas is not recognizing my local file path

```<code>pandas_df = df.toPandas()
pandas_df.to_csv('/home/dir/my.csv', index=False, encoding='utf-8', sep='|')
</code>```

I'm getting this error FileNotFoundError: [Errno 2] No such file or directory

Here is how I'm submitting

```<code>/usr/bin/spark2-submit --master yarn --deploy-mode cluster <pyspark-file>.py
</code>```

答:
If you run the job as --deploy-mode cluster, the driver will be running in any of the machine which is managed by YARN, so if to_csv has local file path, then it will store the output in any of the machine where driver is running.

Check the if the file path exists on all the machines in the cluster

Check if appropriate permissions are given to the File Path

else try

Running the job as --deploy-mode client so the driver runs in the client machine, however step 1 & 2 still applies to the client machine

Body:
I have a pyspark dataframe that I'm converting to pandas to store it as csv on my local file system, but pandas is not recognizing my local file path

pandas_df = df.toPandas()
pandas_df.to_csv('/home/dir/my.csv', index=False, encoding='utf-8', sep='|')

I'm getting this error FileNotFoundError: [Errno 2] No such file or directory

Here is how I'm submitting

/usr/bin/spark2-submit --master yarn --deploy-mode cluster <pyspark-file>.py


问:
Resetting array index when reaching the last index
I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month.

```<code>e.g.
input: January
output: February, March,...November
</code>```

I'm having trouble reverting the index back to the start once the index exceeds 12, for example, if I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you

```<code>   String months[];
   String choice;
   months = new String[13];
   months[0] = null ;
   months[1] = "January";
   months[2] = "February";
   months[3] = "March";
   months[4] = "April";
   months[5] = "May";
   months[6] = "June";
   months[7] = "July";
   months[8] = "August";
   months[9] = "September";
   months[10] = "October";
   months[11] = "November";
   months[12] = "December";
   System.out.print("Enter Month : ");
   choice = a.nextLine();

   if (choice.equals("August")) {
       for(int i=8; i<i+10; i++) {
           String result= months[i];
           System.out.println(result);
       }
   }
</code>```

答:
Use modulus to reset the array index. The solution given above is correct. But if you want to continue with your own defined months array, where months[0] = null ;, just start the for loop from the next index of the input month.

```<code>if ("August".equals(choice)) {
    int start = 9;
    for(int i=start; i < start+11; i++) {
        if(i!=13){
            String result= months[i % 13];
            System.out.println(result);
        }
    }
}
</code>```

Body:
I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month.

e.g.
input: January
output: February, March,...November

I'm having trouble reverting the index back to the start once the index exceeds 12, for example, if I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you

   String months[];
   String choice;
   months = new String[13];
   months[0] = null ;
   months[1] = "January";
   months[2] = "February";
   months[3] = "March";
   months[4] = "April";
   months[5] = "May";
   months[6] = "June";
   months[7] = "July";
   months[8] = "August";
   months[9] = "September";
   months[10] = "October";
   months[11] = "November";
   months[12] = "December";
   System.out.print("Enter Month : ");
   choice = a.nextLine();

   if (choice.equals("August")) {
       for(int i=8; i<i+10; i++) {
           String result= months[i];
           System.out.println(result);
       }
   }

Body:
Use modulus to reset the array index. The solution given above is correct. But if you want to continue with your own defined months array, where months[0] = null ;, just start the for loop from the next index of the input month.

if ("August".equals(choice)) {
    int start = 9;
    for(int i=start; i < start+11; i++) {
        if(i!=13){
            String result= months[i % 13];
            System.out.println(result);
        }
    }
}


问:
Azure VM running Windows Server not receiving license activation response
I have a Azure VM running Windows Server. It is not receiving a license activation response. I have been using the following Microsoft public documentations as reference:

Troubleshoot Azure Windows virtual machine activation problems

Guidelines for troubleshooting the Key Management Service (KMS)

I have confirmed that the Azure VM can access the Azure KMS server endpoint kms.core.windows.net on port 1688 (verified through Telnet). So networking issues do not seem to be the problem.

I have also verified through the Event Logs that the VM is sending out several activation requests to the correct Azure KMS server endpoint (event ID 12288). However, that same VM is not receiving any activation responses (event ID 12289). Screenshot below:

What could be going on? This is a newly deployed Azure VM and its image is directly from the Azure marketplace. Is there maybe a time delay between a new Azure VM and the Azure KMS server actually responding to the activation request? And if so, how long is that delay?

答:
In the screenshots below, the VM was stopped sometime after 2/17/2020 7:14 PM UTC. It was then restarted sometime shortly before 2/19/2020 2:06 PM UTC. Upon the VM being restarted, that VM's activation request was quickly paired with a successful activation response.

Detail of Activation Request (event ID 12288):

Detail of Activation Response (event ID 12289):

As long as Windows Server VMs do not delay in being activated being their 30-day grace period, a small delay in activation is not a problem.

For further Windows Server activation issues in Azure, the troubleshooting steps to be followed are documented here:
https://learn.microsoft.com/en-us/archive/blogs/supportingwindows/troubleshooting-windows-activation-failures-on-azure-vms


问:
from Eclipse to Android phone
I have made a program on eclipse. But how can I get the program from eclipse to my phone? I have a cable because it probably wont make a QR code like appinventor does huh. How do i install my app on there? </p>

答: In Windows you will need drivers to install for the particular device that you have. And if you are on Linux, there is a rules.txt file in which you have to make entries with the device UID. Check this link.</p>

Title: from Eclipse to Android phone


问:
Why vue-router does not work? My project is in GitHub
I have tried to access to others pages via url, but those pages never loads

http://localhost:8080/users

http://localhost:8080/#/users

http://localhost:8080/home

http://localhost:8080/#/home

etc

This is my main.js file:

```<code>import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router"

Vue.config.productionTip = false
Vue.use(VueRouter);

import Users from './components/Users.vue'
const Home = { template: "<p>home page</p>" };
const Index = { template: "<p>index page</p>" };
const About = { template: "<p>about page</p>" };

const routes = [
  { path: "/users", name: "users", component: Users },
  { path: "/home", name: "home", component: Home },
  { path: "/index", name: "index", component: Index },
  { path: "/about", name: "about", component: About },
];

var router = new VueRouter({
  routes: routes,
  mode: "history",
});

new Vue({
  router: router,
  render: h => h(App),
}).$mount('#app')
</code>```

Does anyone know why vue-router not work?

I created this project with Vue CLI, and then I intalled npm install vue-router, basically i just added a new component in ./components/users and also modified the main.js file, and that's all.

I uploaded my project to GitHub: https://github.com/alex-developer-18x/vueapp

答:
I ran your code and the problem is because you are not using "router-view". Go to your App.vue and add "router-view" component.

Example (Edited from your code):

```<code><template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- You should add this instead of <HelloWorld/> -->
    <router-view></router-view>
  </div>
</template>

<script>
// Remove the Hello World import here
export default {
  name: 'App',
  components: {
    // And remove the Hello World component here
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

</code>```

Body:
I have tried to access to others pages via url, but those pages never loads

http://localhost:8080/users

http://localhost:8080/#/users

http://localhost:8080/home

http://localhost:8080/#/home

etc

This is my main.js file:

import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router"

Vue.config.productionTip = false
Vue.use(VueRouter);

import Users from './components/Users.vue'
const Home = { template: "
home page
" };
const Index = { template: "
index page
" };
const About = { template: "
about page
" };

const routes = [
  { path: "/users", name: "users", component: Users },
  { path: "/home", name: "home", component: Home },
  { path: "/index", name: "index", component: Index },
  { path: "/about", name: "about", component: About },
];

var router = new VueRouter({
  routes: routes,
  mode: "history",
});

new Vue({
  router: router,
  render: h => h(App),
}).$mount('#app')

Does anyone know why vue-router not work?

I created this project with Vue CLI, and then I intalled npm install vue-router, basically i just added a new component in ./components/users and also modified the main.js file, and that's all.

I uploaded my project to GitHub: https://github.com/alex-developer-18x/vueapp

Body:
I ran your code and the problem is because you are not using "router-view". Go to your App.vue and add "router-view" component.

Example (Edited from your code):

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- You should add this instead of <HelloWorld/> -->
    <router-view></router-view>
  </div>
</template>

<script>
// Remove the Hello World import here
export default {
  name: 'App',
  components: {
    // And remove the Hello World component here
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


问:
DDD: Lazy loading in aggregates
I've been learning DDD for the past few days and struggling to understand some core concepts of aggregate roots. Maybe somebody could give me push in the right direction and elaborate what's best practice in this scenario:

To make this example less complex, let's say we have a domain of two entities: restaurant and opening time. Restaurant is defined as aggregate root.

From what I understood in all the online examples (correct me if I'm mistaken), the aggregate root is eager loading all sub-entities every time I need an instance of it. So whenever I want to call call a method on the restaurant, all opening times are loaded (no matter if they are used or not).

In this example I want to verify that there is no intersection of opening times when a new time get's added to that restaurant. In this case the eager loading of every other opening time makes sense because I need to compare them with the existing ones.

BUT: this is kind of restricting because I know every time I want to add another collection of something (let's say restaurant images), the SQL load get's heavier and heavier even though most of the methods only require one of the collections.

I could think of two possible solutions:

Lazy loading

Lazy loading opening times / sub entities through entity framework property proxies. So the aggregate root can exist without eager loading them but whenever they are needed they can be accessed.
However everywhere I was searching for an answer I've red that lazy loading in aggregate roots is considered bad practice. Maybe somebody could explain why.

Smaller aggregate roots

Of course I could define the opening time itself as an aggregate root but then I need to take the business logic (in this case the verification of intersections) outside of the model.

In all the examples above I'm only talking about the command side (not querying or serializing).

Maybe I'm missing some fundamental ideas. How should the aggregate roots be organized in this example and why is lazy loading considered bad practice?

EDIT
Not sure why this question was closed because of "opinion based". I'm asking for best practice and why lazy loading is not in this case.

答:
However everywhere I was searching for an answer I've red that lazy loading in aggregate roots is considered bad practice.

That is not exactly the case. The actual restriction is for lazy loading other aggregates, due to direct references, at aggregate roots; referring other aggregates with their identifiers is recommended instead. This restriction has very good reasons behind it.

References to aggregates unnecessarily increases application's memory footprint (retrieving an entity that is not going to be used in a transaction); in highly concurrent use cases, where locks are in effect, degrades application performance (unnecessarily locking an entity); hampers data partitioning (both aggregates need to be processed in the same data node).

Each aggregate root defines its own consistency boundary; each transaction is meant to ensure one aggregate's consistency. Update operations (or transactions) across aggregates, communicated through domain events, are supposed to be eventually consistent.

If you are holding direct reference to another aggregate, thereby necessitating lazy loading, and performing updates on them, you should rethink your design.

The choice in your scenario, as usual, depends on the business context or the domain it deals with. If you think OpeninigTime is a separate aggregate, with its own consistency boundary, you should hold only its id and publish domain events, containing the id, that the OpeningTime aggregate will handle by retrieving the appropriate aggregate. If, however, it is not the case (that seems to be more likely), you may very much hold reference, lazy load, and perform updates on it.

Title: DDD: Lazy loading in aggregates


问:
Get variables datatypes in kernel mode drivers windows
I want to know if there is any method in kernel mode drivers which gives the datatype of a variable. Like if I declare:

```<code>INT i = 0;
</code>```

And ask about datatype of "i", it will return INT. I also want the same thing for structures.

答:
You could declare your function like this:

```<code>void myapi(void *param, enum type param_type);
</code>```

And the associated enum:

```<code>enum type {
    TYPE_INT,
    TYPE_CHAR,
    // more types
 };
</code>```

With a body like this:

```<code>void myapi(void *param, enum type param_type)
{
    if (param_type == TYPE_INT) {
        int *intptr = param;
        // do something with intptr
    } else if (param_type == TYPE_CHAR) {
        char *charptr = param;
        // do something with charptr
    // cases for other types
    }
}
</code>```

And you would call it like this:

```<code>int myint = 0;
myapi(&myint, TYPE_INT);
char mychar = 'x';
myapi(&mychar, TYPE_CHAR);
</code>```

Body:
I want to know if there is any method in kernel mode drivers which gives the datatype of a variable. Like if I declare:

INT i = 0;

And ask about datatype of "i", it will return INT. I also want the same thing for structures.

Body:
You could declare your function like this:

void myapi(void *param, enum type param_type);

And the associated enum:

enum type {
    TYPE_INT,
    TYPE_CHAR,
    // more types
 };

With a body like this:

void myapi(void *param, enum type param_type)
{
    if (param_type == TYPE_INT) {
        int *intptr = param;
        // do something with intptr
    } else if (param_type == TYPE_CHAR) {
        char *charptr = param;
        // do something with charptr
    // cases for other types
    }
}

And you would call it like this:

int myint = 0;
myapi(&myint, TYPE_INT);
char mychar = 'x';
myapi(&mychar, TYPE_CHAR);


问:
Is there a simple way to show .gitignore rules that are not matched by any file in the directory tree?
I need to clean up my .gitignore file. I run some commands and then go through the .gitignore file and delete any line that isn't needed anymore.

The command finds all files in a tree, runs git's check-ignore, greps out only matches that are in my .gitignore file, cleans up the line, and then uniquely sorts the results. Any rule that doesn't appear in this output is a candidate for removal.

```<code>find . -type f -not -path .git -exec git check-ignore -v '{}' \; | grep '^.gitignore:' | sed 's/.*:\(.*\)\t.*$/\1/' | sort -u >> .gitignore
</code>```

This command can take quite some time, especially in repositories with a lot of files and mounted on an NFS.

Is there a simpler method that will show me rules that are not matched by any file in the tree?

答:
You can use git status --ignored=matching to get a list of the ignored file that matches a pattern in <code>.gitignore</code>. </p>

```<code>git status -s --ignored=matching | grep "^\!\!" | awk '{print $2}' | xargs git check-ignore -v | grep '^.gitignore:' | sed 's/.*:\(.*\)\t.*$/\1/' | sort -u >> .gitignore
</code>```

Body:
I need to clean up my .gitignore file. I run some commands and then go through the .gitignore file and delete any line that isn't needed anymore.

The command finds all files in a tree, runs git's check-ignore, greps out only matches that are in my .gitignore file, cleans up the line, and then uniquely sorts the results. Any rule that doesn't appear in this output is a candidate for removal.

find . -type f -not -path .git -exec git check-ignore -v '{}' \; | grep '^.gitignore:' | sed 's/.*:\(.*\)\t.*$/\1/' | sort -u >> .gitignore

This command can take quite some time, especially in repositories with a lot of files and mounted on an NFS.

Is there a simpler method that will show me rules that are not matched by any file in the tree?

Body:
You can use git status --ignored=matching to get a list of the ignored file that matches a pattern in .gitignore.

git status -s --ignored=matching | grep "^\!\!" | awk '{print $2}' | xargs git check-ignore -v | grep '^.gitignore:' | sed 's/.*:\(.*\)\t.*$/\1/' | sort -u >> .gitignore


问:
Disable Button until all edittext fields are not empty and the logic fulfilled
I have a problem where I need to disable the button until all the edittext fields have valid data in them and not empty. I would also want to have the submit button not enabled if there is any null or empty field.

Part of my logic includes for example that the user's first and second name should at least have 3 characters as shown.

I am able to validate all the edittext fields using TextWatcher afterTextChanged method but I unable to disable the button until all the data is valid.

My question is how do I make sure I disable my button until all the logic is validated?

Below is my code.

```<code> @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {

email.addTextChangedListener(new EditTextWatcher(email));
            password.addTextChangedListener(new EditTextWatcher(password));
            name.addTextChangedListener(new EditTextWatcher(name));

 button.setOnClickListener((View v) -> {
                updateDatabase();
            }

            }

private class EditTextWatcher implements TextWatcher {

        private View view;

        private EditTextWatcher(View view) {
            this.view = view;
        }
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            switch (view.getId()) {
                case R.id.email:
                    validateEmail();
                    break;
                case R.id.password:
                    validatePassword();
                    break;

            }

        }
        }

        private boolean validateEmail() {
            String email = email.getText().toString().trim();

            if (email.isEmpty() || !isValidEmail(email)) {
                layoutEmail.setError(getString(R.string.err_msg_email));
                requestFocus(email);
                return false;
            } else {
                layoutEmail.setErrorEnabled(false);
            }
            return true;
        }

        private static boolean isValidEmail(String email) {
            return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
        }

     private boolean validatePassword() {
            String password = password.getText().toString().trim();
            if (StringUtils.isEmpty(password) || !isValidPassword(password)) {
                layoutPassword.setError(getString(R.string.err_msg_password));
                requestFocus(password);
                return false;
            } else {
                password.setErrorEnabled(false);
            }
            return true;
        }

            private void requestFocus(View view) {
            if (view.requestFocus()) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }

            private boolean validatePassword() {
            String password = password .getText().toString().trim();
            if (StringUtils.isEmpty(password) || !isValidPassword(password)) {
                layoutPassword.setError(getString(R.string.err_msg_password));
                requestFocus(password);
                return false;
            } else {
                layoutPassword.setErrorEnabled(false);
            }
            return true;
        }

            private static boolean isValidPassword(String password){
            return !TextUtils.isEmpty(password) && PASSWORD_PATTERN.matcher(password).matches();
        }
</code>```

答:
Disable your button in xml and enable after completion of your logic

call this below method in afterTextChanged irrespctive of viewId

```<code>void validatationForButton(){
   if(validateEmail()&&validatePassWord()){
      //enable Button here
      btn.setEnabled(true);
}}````
```

Body:
I have a problem where I need to disable the button until all the edittext fields have valid data in them and not empty. I would also want to have the submit button not enabled if there is any null or empty field.

Part of my logic includes for example that the user's first and second name should at least have 3 characters as shown.

I am able to validate all the edittext fields using TextWatcher afterTextChanged method but I unable to disable the button until all the data is valid.

My question is how do I make sure I disable my button until all the logic is validated?

Below is my code.

 @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {

email.addTextChangedListener(new EditTextWatcher(email));
            password.addTextChangedListener(new EditTextWatcher(password));
            name.addTextChangedListener(new EditTextWatcher(name));

 button.setOnClickListener((View v) -> {
                updateDatabase();
            }

            }

private class EditTextWatcher implements TextWatcher {

        private View view;

        private EditTextWatcher(View view) {
            this.view = view;
        }
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            switch (view.getId()) {
                case R.id.email:
                    validateEmail();
                    break;
                case R.id.password:
                    validatePassword();
                    break;

            }

        }
        }

        private boolean validateEmail() {
            String email = email.getText().toString().trim();

            if (email.isEmpty() || !isValidEmail(email)) {
                layoutEmail.setError(getString(R.string.err_msg_email));
                requestFocus(email);
                return false;
            } else {
                layoutEmail.setErrorEnabled(false);
            }
            return true;
        }

        private static boolean isValidEmail(String email) {
            return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
        }

     private boolean validatePassword() {
            String password = password.getText().toString().trim();
            if (StringUtils.isEmpty(password) || !isValidPassword(password)) {
                layoutPassword.setError(getString(R.string.err_msg_password));
                requestFocus(password);
                return false;
            } else {
                password.setErrorEnabled(false);
            }
            return true;
        }

            private void requestFocus(View view) {
            if (view.requestFocus()) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }

            private boolean validatePassword() {
            String password = password .getText().toString().trim();
            if (StringUtils.isEmpty(password) || !isValidPassword(password)) {
                layoutPassword.setError(getString(R.string.err_msg_password));
                requestFocus(password);
                return false;
            } else {
                layoutPassword.setErrorEnabled(false);
            }
            return true;
        }

            private static boolean isValidPassword(String password){
            return !TextUtils.isEmpty(password) && PASSWORD_PATTERN.matcher(password).matches();
        }

Body:
Disable your button in xml and enable after completion of your logic

call this below method in afterTextChanged irrespctive of viewId

void validatationForButton(){
   if(validateEmail()&&validatePassWord()){
      //enable Button here
      btn.setEnabled(true);
}}````