问:
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>```

答:
I think you should implement enable/disable button within onTextChange().

```<code>      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!s.toString().isEmpty() && s.toString().length() > 0) {
          // enable the button here
        } else {
          // disable the button here
        }
      }
</code>```

Because every time you type in TextFiled or every text change occur, the button will be enabled or disabled.

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:
I think you should implement enable/disable button within onTextChange().

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!s.toString().isEmpty() && s.toString().length() > 0) {
          // enable the button here
        } else {
          // disable the button here
        }
      }

Because every time you type in TextFiled or every text change occur, the button will be enabled or disabled.


来源: stackexchange

问:
Vaadin 14.1.17 - Get element selected in chart - Java
Hello i'm wondering how to retrieve the clicked element from a pie chart in Vaadin 14.1.17.

I'm using a classic pie with DataSeries and some values inside and i want to get the current selected item from a click listener

DataSeries initialization

```<code>DataSeries ds = new DataSeries();

for (AssetClassModel a : p.getAssetClasses()) {
    ds.add(new DataSeriesItem(a.getDesc(), a.getPerc()));
}
conf.setSeries(ds);
</code>```

I've tried reading the selected field inside DataSeriesItem but it's always false

Click Listener

```<code>chart.addSeriesClickListener(
        e -> {
            List<DataSeriesItem> items = ((DataSeries) e.getSeries()).getData();

            for (DataSeriesItem item : items) {
                System.out.println(item.getName() + " selected: " + item.isSelected());
            }

        }
);
</code>```

Output

```<code>value1 selected: false
value2 selected: false
value4 selected: false
</code>```

Do you have any idea on how to manage this?

Thanks
Davide

答:
This is more of a workaround, but seems to work :)

The SeriesClickEvent has a getMouseDetails().getyValue() method. The returned value matches with the y value of an item. (It's the second constructor parameter of a DataSeriesItem)

chart.addSeriesClickListener(event->{
     series.getData().forEach( item->{
          if(event.getMouseDetails().getyValue()== ((DataSeriesItem)item).getY().doubleValue()){
              System.out.println("SELECTED : " +  ((DataSeriesItem)item).getName());
           }
     });
});
```

The isSelected() method seems to rely on the selected property set implicitly using item.setSelected(true);. This was confusing for me as well, so it's either a bug or a non documented behaviour.

ContentLicense: CC BY-SA 4.0

Body:
Hello i'm wondering how to retrieve the clicked element from a pie chart in Vaadin 14.1.17.

I'm using a classic pie with DataSeries and some values inside and i want to get the current selected item from a click listener

DataSeries initialization

DataSeries ds = new DataSeries();

for (AssetClassModel a : p.getAssetClasses()) {
    ds.add(new DataSeriesItem(a.getDesc(), a.getPerc()));
}
conf.setSeries(ds);

I've tried reading the selected field inside DataSeriesItem but it's always false

Click Listener

chart.addSeriesClickListener(
        e -> {
            List<DataSeriesItem> items = ((DataSeries) e.getSeries()).getData();

            for (DataSeriesItem item : items) {
                System.out.println(item.getName() + " selected: " + item.isSelected());
            }

        }
);

Output

value1 selected: false
value2 selected: false
value4 selected: false

Do you have any idea on how to manage this?

Thanks
Davide

Body:
This is more of a workaround, but seems to work :)

The SeriesClickEvent has a getMouseDetails().getyValue() method. The returned value matches with the y value of an item. (It's the second constructor parameter of a DataSeriesItem)

chart.addSeriesClickListener(event->{
     series.getData().forEach( item->{
          if(event.getMouseDetails().getyValue()== ((DataSeriesItem)item).getY().doubleValue()){
              System.out.println("SELECTED : " +  ((DataSeriesItem)item).getName());
           }
     });
});

The isSelected() method seems to rely on the selected property set implicitly using item.setSelected(true);. This was confusing for me as well, so it's either a bug or a non documented behaviour.


问:
How can I set my local date in javaScript
I'm using this code to get the difference between today date and my data date from database

I notice every day at 3 pm . next day start
( for example if today is 20 . at 3 pm the date will be 21 )

```<code>  const oneDay = 24 * 60 * 60 * 1000;
  var serverDate = new Date(value)
  let todayDate = new Date()
  const difference = Math.round(Math.abs((todayDate - serverDate) / oneDay));
  return difference
</code>```

How can I set my local date or there is better way to solve this problem

答:
If you need to find the difference between the current and your DB date run the below code.

var d = new Date();
var currentDate = moment(d.toLocaleString(),'M/D/YYYY');
var systemDate = moment('2/20/2019','M/D/YYYY');
var diffDays = currentDate.diff(systemDate, 'days');

 console.log("diffDays",diffDays);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I'm using this code to get the difference between today date and my data date from database

I notice every day at 3 pm . next day start
( for example if today is 20 . at 3 pm the date will be 21 )

  const oneDay = 24 * 60 * 60 * 1000;
  var serverDate = new Date(value)
  let todayDate = new Date()
  const difference = Math.round(Math.abs((todayDate - serverDate) / oneDay));
  return difference

How can I set my local date or there is better way to solve this problem

Body:
If you need to find the difference between the current and your DB date run the below code.

var d = new Date();
var currentDate = moment(d.toLocaleString(),'M/D/YYYY');
var systemDate = moment('2/20/2019','M/D/YYYY');
var diffDays = currentDate.diff(systemDate, 'days');

 console.log("diffDays",diffDays);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
What is the exact meaning of invasive? and what makes Spring non-invasive?
I'm new to the spring framework. In most of the Spring tutorials I saw, Spring is described as "non-invasive".

What is meant by invasive? What are the merits of using Spring in Java and what makes it non-invasive?

答:
Claiming that Spring is non-invasive is like claiming that the earth is flat. You completely deny reality based on nothing else than your personal bias.

Spring is not only invasive to your code base, it is also invasive to your brain. It will annoy the hell out of you when you have built a decent confidence in searching the web for information and solutions for your programming problems.
I have done serious programming work in some 10 languages and shells, and almost always managed to find useful information, answers and hints to solve my problems. Usually I manage to find convergence towards a decent solution pretty fast, and sometimes after a bit of digging.
Not so with Spring. A once popular scripting language touted the slogan "there's more than way to do it". For Spring, you will mostly find many ways how not to do it, or many ways that will not work in your particular setup.

I do not doubt that Spring has real value. I do see that. But it comes with way too much magic, that works well as long as it works, but once it fails, the tooling and documentation often fail as well.

ContentLicense: CC BY-SA 3.0


问:
URL Rewrite Issue with Mango Blog (404 error)
I am working on setting up an instance of Mango Blog on an Ubuntu Server running Apache 2 HTTPD and Tomcat 6 with Railo 3.1.2.  I was able to get everything setup until I started trying to implement URL rewriting for the blog URLs.

I used a combination of Adam Tuttle's and John Sieber's posts to get the rewrite rules.  I have the site setup as follows:

{webroot}/.htaccess

```<code>RewriteEngine on
RewriteBase /
# archives rule must be located before page rule for paging to work correctly
RewriteRule archives/(.*)$              archives.cfm/$1 [PT,L,NC]
RewriteRule page/(.*)$                  page.cfm/$1 [PT,L,NC]
RewriteRule post/(.*)$                  post.cfm/$1 [PT,L,NC]
RewriteRule author/(.*)$                author.cfm/$1 [PT,L,NC]
</code>```

{apache-home}/sites-enabled/sitename

```<code><VirtualHost *:80>
        ServerAdmin *******

        DocumentRoot /var/www/******/www
        ServerName mango.*****.com
        DirectoryIndex index.cfm

        <Directory /var/www/*******.com/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog /var/log/apache2/error-*******_com.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access-********_com.log combined

        ProxyPreserveHost Off
        ProxyPassMatch ^/(.+\.cf[cm])(/.*)?$ ajp://********.com:8009/

</VirtualHost>
</code>```

When I visit blog posts by going to /post/hello-world on the site I get a 404 error.  If I go to /post.cfm/hello-world the post comes up just fine.  I tried the rewrite rules against a rewrite tester, and that said that the rewrites should work fine.  I am very new to rewriting, so I apologize if this is something simple.

答:
Try moving your rewrite rules to the VirtualHost block. I've had weird problems with .htaccess not working correctly w/ rewrites.

I could be wrong here, but this is what I think happens.

Apache is going to look for /post/, which doesn't exist and return the 404. It'd run .htaccess if it existed in /post/, but it doesn't.

If the rewrite rules are in your Directory block inside the VirtualHost block in httpd.conf file, then Apache knows to redirect instead of looking for /post/.

```<code><VirtualHost *:80>
    ServerAdmin *******

    DocumentRoot /var/www/******/www
    ServerName mango.*****.com
    DirectoryIndex index.cfm

    <Directory /var/www/*******.com/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
            Order allow,deny
            allow from all

            RewriteEngine on
            RewriteBase /
            # archives rule must be located before page rule for paging to work correctly
            RewriteRule archives/(.*)$              archives.cfm/$1 [PT,L,NC]
            RewriteRule page/(.*)$                  page.cfm/$1 [PT,L,NC]
            RewriteRule post/(.*)$                  post.cfm/$1 [PT,L,NC]
            RewriteRule author/(.*)$                author.cfm/$1 [PT,L,NC]
    </Directory>

    ErrorLog /var/log/apache2/error-*******_com.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access-********_com.log combined

    ProxyPreserveHost Off
    ProxyPassMatch ^/(.+\.cf[cm])(/.*)?$ ajp://********.com:8009/
</code>```

Body:
I am working on setting up an instance of Mango Blog on an Ubuntu Server running Apache 2 HTTPD and Tomcat 6 with Railo 3.1.2.  I was able to get everything setup until I started trying to implement URL rewriting for the blog URLs.

I used a combination of Adam Tuttle's and John Sieber's posts to get the rewrite rules.  I have the site setup as follows:

{webroot}/.htaccess

RewriteEngine on
RewriteBase /
# archives rule must be located before page rule for paging to work correctly
RewriteRule archives/(.*)$              archives.cfm/$1 [PT,L,NC]
RewriteRule page/(.*)$                  page.cfm/$1 [PT,L,NC]
RewriteRule post/(.*)$                  post.cfm/$1 [PT,L,NC]
RewriteRule author/(.*)$                author.cfm/$1 [PT,L,NC]

{apache-home}/sites-enabled/sitename

<VirtualHost *:80>
        ServerAdmin *******

        DocumentRoot /var/www/******/www
        ServerName mango.*****.com
        DirectoryIndex index.cfm

        <Directory /var/www/*******.com/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog /var/log/apache2/error-*******_com.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access-********_com.log combined

        ProxyPreserveHost Off
        ProxyPassMatch ^/(.+\.cf[cm])(/.*)?$ ajp://********.com:8009/

</VirtualHost>

When I visit blog posts by going to /post/hello-world on the site I get a 404 error.  If I go to /post.cfm/hello-world the post comes up just fine.  I tried the rewrite rules against a rewrite tester, and that said that the rewrites should work fine.  I am very new to rewriting, so I apologize if this is something simple.

Body:
Try moving your rewrite rules to the VirtualHost block. I've had weird problems with .htaccess not working correctly w/ rewrites.

I could be wrong here, but this is what I think happens.

Apache is going to look for /post/, which doesn't exist and return the 404. It'd run .htaccess if it existed in /post/, but it doesn't.

If the rewrite rules are in your Directory block inside the VirtualHost block in httpd.conf file, then Apache knows to redirect instead of looking for /post/.

<VirtualHost *:80>
    ServerAdmin *******

    DocumentRoot /var/www/******/www
    ServerName mango.*****.com
    DirectoryIndex index.cfm

    <Directory /var/www/*******.com/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
            Order allow,deny
            allow from all

            RewriteEngine on
            RewriteBase /
            # archives rule must be located before page rule for paging to work correctly
            RewriteRule archives/(.*)$              archives.cfm/$1 [PT,L,NC]
            RewriteRule page/(.*)$                  page.cfm/$1 [PT,L,NC]
            RewriteRule post/(.*)$                  post.cfm/$1 [PT,L,NC]
            RewriteRule author/(.*)$                author.cfm/$1 [PT,L,NC]
    </Directory>

    ErrorLog /var/log/apache2/error-*******_com.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access-********_com.log combined

    ProxyPreserveHost Off
    ProxyPassMatch ^/(.+\.cf[cm])(/.*)?$ ajp://********.com:8009/


问:
Disable back button after logout?
I am using php. i want redirect users to logout page when he clicks back button after login. How to achieve this? where to write the code?

i logged into site admin..logged out and then hit back button and i am able to see the previous page. Why site admin does not handle this.

This is the code for logout in site admin:

```<code>if( !function_exists( 'adifier_logout_inactive' ) ){
function adifier_logout_inactive( $username, $user ){
    if( !is_wp_error( $user ) ){
        $logout = true;
        if( !empty( $user->allcaps['edit_posts'] ) && $user->allcaps['edit_posts'] === true ){
            $logout = false;
        }
        else if( get_user_meta( $user->ID, 'user_active_status', true ) == 'active' ){
            $logout = false;
        }
        if( $logout === true  ){
            wp_logout();
        }
    }
}
add_filter( 'wp_login', 'adifier_logout_inactive', 10, 2 );
}
</code>```

答:
First question: What is the back button?

Answer: It is a button outside the control of the web server. If presses, the browser loads again the page with the previous used URL. Some browsers (or all?) support a back N steps button.

What does the web server see?

The web server sees only the URL. He does't know if the URL is loaded again or if the user used one of the back buttons. So the (new) URL is the only data for the decision. The only chance to recognize the the usage of a back button is to use session data too.

Pitfalls: The user can open several windows. He can press the reload button. He can set and use bookmarks.

With this knowledge you should rethink how to detect thew back button and if you really want to mange (some aspects of) it. Or in other words: Is it rally worth to forbid loading the previous URL again.

A soluton may be: If the user enters the login page and is already logged-in, then redirect him to another page (welcome, status, overview). I do that at my websites.

Title: Disable back button after logout?

Body:
I am using php. i want redirect users to logout page when he clicks back button after login. How to achieve this? where to write the code?

i logged into site admin..logged out and then hit back button and i am able to see the previous page. Why site admin does not handle this.

This is the code for logout in site admin:

if( !function_exists( 'adifier_logout_inactive' ) ){
function adifier_logout_inactive( $username, $user ){
    if( !is_wp_error( $user ) ){
        $logout = true;
        if( !empty( $user->allcaps['edit_posts'] ) && $user->allcaps['edit_posts'] === true ){
            $logout = false;
        }
        else if( get_user_meta( $user->ID, 'user_active_status', true ) == 'active' ){
            $logout = false;
        }
        if( $logout === true  ){
            wp_logout();
        }
    }
}
add_filter( 'wp_login', 'adifier_logout_inactive', 10, 2 );
}


问:
utag for tealium is being coverted to file:// in ionic 3 after building into an Android app
I have a utag_src with "https://......" (I have also tried "//tags.tiqcdn...." without the protocol) but after being called the first time, it sends 2 more times with http://

http://tags.tiqcdn.com/utag/company/appname/environment/utag.3.js?event

This works fine on browser but after building it into an Android App, it's being converted to file:// and that's throwing me an error and I am no longer able to track things.

file://tags.tiqcdn.com/utag/company/appname/environment/utag.3.js?event

Anyone know a way to either keep it in https or prevent it from converting into file:// in android?

答:
I'm not an expert with Ionic, but can certainly help steer you in the right direction with Tealium.

For mobile implementations it would be the recommendation to invoke Tealium via our SDKs: https://github.com/Tealium

With Ionic I believe you can use the Cordova SDK, or use the Native Android SDK, and write your own communication layer.

It will depend a little on what you want to achieve with Tealium, and with which product, but the SDKs are designed for mobile, so as well as solving your direct issue it will ensure optimal performance of Tealium event captures and triggers.  If you are solely looking for CDH support Tealium does have an HTTP API to receive events as well, but the SDK approach for all mobile requirements.

support@tealium.com can also help you to find the best solution.


问:
Unable to prompt for search in an array
I am trying to create a search array where user enter the number of items, enter the value of all items and search for an array. However, I am unable to prompt for the search array to display after user enter the values of all the items. Here is an example of the desired output:

```<code>Enter the number of items: 5
Enter the value of all items (separated by space): 6 1 8 2 4
Enter the search key: 8
8 is found with index 2
</code>```

Here is my coding:

```<code>import java.util.Scanner;

public class SearchArray {

public static void main(String[] args) {

    int[] array;
    int items;

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the number of items: ");
    items = in.nextInt();

    array = new int[items];
    print(array);
    System.out.println();

}

public static void print(int[] array) {

    Scanner in = new Scanner(System.in);

    if (array.length > 0) {
        System.out.print("Enter the value of all items (separated by space): ");
        for (int i = 0; i < array.length; ++i) {
            array[i] = in.nextInt();
        }

    }

}

public static int search(int[] array, int key){

    Scanner in = new Scanner(System.in);

  if (array.length > 0) {
      System.out.print("Enter the search key: ");
    for(int i=0; i<array.length; ++i){
        if(array[i] == key){
            key = in.nextInt();
            System.out.println(key + "is present at location " + (i+1) + ".");
        }
    }

  }
  return -1;

 }

public static boolean isEmpty(int[] array) {

    if (array.length == 0)
        return true;
    else
        return false;

}
}
</code>```

It would be good if someone can help me on that. Thanks!

答:
After reading the code, I see that you are not calling search(int[] array) which is why you dont see the desired output of:

Enter the search key: ...

Furthermore, inside of your print(int[] array) function, you are setting array[i] = in.nextInt(); however you are not using that array within the scope of that function, I would recommend returning that array and setting the one in the main function to it, so it would look something like array = print(array). This allows you to change the value of the array in the main function, then you can call the search(int[] array) function using the array you just manipulated. The way we can allow the function to return an integer array would look like public static int[] print(int[] array).

I also see in the search(int[] array, int key) function, that the second parameter is unnecessary because you ask for the key within that function, you are not expecting to know the key until that function is already called. When you are expecting input for the key, you should receive the input outside of the for loop since you are only asking for one key. And the search function also does not need to return anything, thus you can make the return type void.

Title: Unable to prompt for search in an array

Body:
I am trying to create a search array where user enter the number of items, enter the value of all items and search for an array. However, I am unable to prompt for the search array to display after user enter the values of all the items. Here is an example of the desired output:

Enter the number of items: 5
Enter the value of all items (separated by space): 6 1 8 2 4
Enter the search key: 8
8 is found with index 2

Here is my coding:

import java.util.Scanner;

public class SearchArray {

public static void main(String[] args) {

    int[] array;
    int items;

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the number of items: ");
    items = in.nextInt();

    array = new int[items];
    print(array);
    System.out.println();

}

public static void print(int[] array) {

    Scanner in = new Scanner(System.in);

    if (array.length > 0) {
        System.out.print("Enter the value of all items (separated by space): ");
        for (int i = 0; i < array.length; ++i) {
            array[i] = in.nextInt();
        }

    }

}

public static int search(int[] array, int key){

    Scanner in = new Scanner(System.in);

  if (array.length > 0) {
      System.out.print("Enter the search key: ");
    for(int i=0; i<array.length; ++i){
        if(array[i] == key){
            key = in.nextInt();
            System.out.println(key + "is present at location " + (i+1) + ".");
        }
    }

  }
  return -1;

 }

public static boolean isEmpty(int[] array) {

    if (array.length == 0)
        return true;
    else
        return false;

}
}

It would be good if someone can help me on that. Thanks!


问:
Node.js - How do you call an async function with a callback?
The async function below is supposed to check if a url is a legit url

```<code>let CheckUrl = function (url, done) {
  dns.lookup(url, function(err, address) {
    if (err) return done(err);
    done(null, true); //return true because I don't care what the address is, only that it works
  });
}
</code>```

The express.js code below gets the url but I'm having trouble understanding how to write the if statement so that it returns true or false.

```<code>// Gets URL
app.post("/api/shorturl/new", function(req, res) {
  if (CheckUrl(req.body.url)) {
    // do something
  }
});
</code>```

I'm not sure what to pass as the second argument in CheckUrl() in this if statement. Or maybe I wrote the first async function incorrectly to begin with?

答:
Please use the async  await

I have written a test code for you as below:

```<code>const express = require('express');
const app = express();
const dns = require('dns');

let CheckUrl = function (url, done) {
    return new Promise((resolve, reject) => {
        dns.lookup(url, function(err, address) {
            console.log("err " , err)
            if (err) {
                resolve(false)
            } else {
                resolve(true)
            }

        });
    });
}

app.post("/api/shorturl/new", async function(req, res) {

  try {

    let result = await CheckUrl(req.body.url);
    console.log("result " , result)
    res.send(result)
  }
  catch (error) {
    console.log("in catch error " , error)
    res.send(error)
  }
});

app.listen(3000)
</code>```

you can get the knowledge to know about the Promise here. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Body:
The async function below is supposed to check if a url is a legit url

let CheckUrl = function (url, done) {
  dns.lookup(url, function(err, address) {
    if (err) return done(err);
    done(null, true); //return true because I don't care what the address is, only that it works
  });
}

The express.js code below gets the url but I'm having trouble understanding how to write the if statement so that it returns true or false.

// Gets URL
app.post("/api/shorturl/new", function(req, res) {
  if (CheckUrl(req.body.url)) {
    // do something
  }
});

I'm not sure what to pass as the second argument in CheckUrl() in this if statement. Or maybe I wrote the first async function incorrectly to begin with?

Body:
Please use the async  await

I have written a test code for you as below:

const express = require('express');
const app = express();
const dns = require('dns');

let CheckUrl = function (url, done) {
    return new Promise((resolve, reject) => {
        dns.lookup(url, function(err, address) {
            console.log("err " , err)
            if (err) {
                resolve(false)
            } else {
                resolve(true)
            }

        });
    });
}

app.post("/api/shorturl/new", async function(req, res) {

  try {

    let result = await CheckUrl(req.body.url);
    console.log("result " , result)
    res.send(result)
  }
  catch (error) {
    console.log("in catch error " , error)
    res.send(error)
  }
});

app.listen(3000)

you can get the knowledge to know about the Promise here. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.


问:
How to get current user in Laravel API using Passport?
I am using passport package for Laravel API Authentication. When I post data I get error:

401 Unauthorized","error":{"error":"Unauthenticated."}.

I use Auth::user()->id; to get current user id.

How to solve this error?

答:
You can get current user in laravel api using passport as below:

```<code>Route::get('/user', function (Request $request) {
 return $request->user();
});
</code>```

but you are getting 401 Error that means either you are not passing access_token in Authorization header or your access_token has expired so you have to refresh the token,

You have to pass access_token in Authorization header which you have got after successfully logged in.

Your user route is protected by passport so When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request.

For example, when using the Guzzle HTTP library you can pass it as below:

```<code>$response = $client->request('GET', '/api/logout', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);
</code>```

from the doc laravel passport passing access token

Body:
You can get current user in laravel api using passport as below:

Route::get('/user', function (Request $request) {
 return $request->user();
});

but you are getting 401 Error that means either you are not passing access_token in Authorization header or your access_token has expired so you have to refresh the token,

You have to pass access_token in Authorization header which you have got after successfully logged in.

Your user route is protected by passport so When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request.

For example, when using the Guzzle HTTP library you can pass it as below:

$response = $client->request('GET', '/api/logout', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

from the doc laravel passport passing access token


问:
Favicon not displaying on staging server
Please help this here i'm trying to display title with logo on tab But in local it's working fine but staging server not displaying the logo.</p>

```<code><title>Global</title>

<link type="image/png" href="src/assets/images/logo/bigImage.png" rel="shortcut icon" />
</code>```

答:
It's the same as adding any other external script or stylesheet. All you have to do is focus on giving the correct path and rel and type.

Note: When my favicon image was in the assets folder, it was not displaying the favicon. So I copied the image to the same folder as of my index.html and it worked perfectly as it should.

```<code><head>
    <link rel="shortcut icon" type="image/png/ico" href="/favicon.png" />
    <title>SITE NAME</title>
</head>
</code>```

It worked for me. I hope it works for you too.

You can also check some more answers here: Add Favicon with React and Webpack

Body:
Please help this here i'm trying to display title with logo on tab But in local it's working fine but staging server not displaying the logo.

<title>Global</title>

<link type="image/png" href="src/assets/images/logo/bigImage.png" rel="shortcut icon" />

Body:
It's the same as adding any other external script or stylesheet. All you have to do is focus on giving the correct path and rel and type.

Note: When my favicon image was in the assets folder, it was not displaying the favicon. So I copied the image to the same folder as of my index.html and it worked perfectly as it should.

<head>
    <link rel="shortcut icon" type="image/png/ico" href="/favicon.png" />
    <title>SITE NAME</title>
</head>

It worked for me. I hope it works for you too.

You can also check some more answers here: Add Favicon with React and Webpack


问:
search for innerHTML value in a table
how can I search in a table for a row with a specifik innerHTML value?

```<code><table>
<tr><td>test</td><td>100</td></tr>
<tr><td>test</td><td>200</td></tr>
<tr><td>test</td><td>300</td></tr>
</table>
</code>```

I need the index for the row (tr) where the second td is 200

here the index has to give 1

```<code>$('table tr'). something??
</code>```

EDIT:

and I also need a version that select the index before a give value is bigger (asc) than 200 (if it exists)

答:
```<code>$("TABLE TR").each(function() {
    if ($("TD", this).eq(1).html()== "200") {
        // Your logic here

        return false; // break out of .each() loop
    }
});
</code>```

Title: search for innerHTML value in a table

Body:
how can I search in a table for a row with a specifik innerHTML value?

test	100

test	200

test	300

I need the index for the row (tr) where the second td is 200

here the index has to give 1

$('table tr'). something??

EDIT:

and I also need a version that select the index before a give value is bigger (asc) than 200 (if it exists)


问:
Error:Execution failed for task ':app:clean'
i need your help, when i try to compile my new app without any addition of dependences and classpath i get this exception

android studio ver 21.1

ubuntu 15.4 32bit

Error Execution failed for task app clean.

Unable to delete directory: .../app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/23.4.0/jars

答:
Gradle process holds file locks, so either kill any java.exe processes manually or be more precise and kill all Gradle daemons by issuing this command in your project root directory:

```<code>gradlew daemon --stop
</code>```

This will stop all daemons of particular Gradle version.

Body:
Gradle process holds file locks, so either kill any java.exe processes manually or be more precise and kill all Gradle daemons by issuing this command in your project root directory:

gradlew daemon --stop

This will stop all daemons of particular Gradle version.


问:
EXISTS clause ISSUE with TOP clause in sub query
I have a query sub query below (Purpose search top 2 orders from order table whose freight_charges=2 and get the customers of those orders)

Working query with IN clause

```<code>    SELECT *
    FROM Customers C
    WHERE C.CUST_ID IN (
      SELECT TOP 2 CUST_ID
      FROM Orders O
      where FREIGHT_CHARGES = 2
    )
</code>```

However I want to convert the IN clause into a more efficient EXISTS clause

Code not working with exists clause

```<code>    SELECT *
    FROM Customers C
    WHERE EXISTS (
        SELECT TOP 2 CUST_ID
        FROM Orders O
        where FREIGHT_CHARGES = 2 AND C.CUST_ID = O.CUST_ID
    )
</code>```

In case of the second query I am not retrieving the top 2 cust_id BUT all the records.

Please let me know any implementation to get the desired result.

Edited: Using INNER JOIN as suggested in the answers . I am able to get the correct result. However since I don't want to retrieve any record from Orders table I thought exists would be a better approach performance wise.

```<code>    SELECT C.*
    FROM Customers C
    INNER JOIN (
      SELECT TOP 2 CUST_ID
      FROM Orders
      where FREIGHT_CHARGES = 2
    ) O ON C.CUST_ID=O.CUST_ID
</code>```

答:
I can suggest you should go for INNER JOIN. It is always a good practice to avoid subqueries if possible as it gets executed against each row from master table because it in WHERE condition. Rather, you can use simple INNER JOIN to get the desired output.

Like in your example, you just need TOP 2 customers having the FREIGHT_CHARGES value to 2. You can use below query using INNER JOIN.

```<code>SELECT
    TOP 2
    C.*
FROM Customers C
INNER JOIN Orders O ON C.CUST_ID = O.CUST_ID
WHERE O.FREIGHT_CHARGES = 2
ORDER BY C.CUST_ID -- Use 'ORDER BY' clause if 'C.CUST_ID' column does not have clustered index or you can use any other column
</code>```

Please let me know your feedback.

Body:
I have a query sub query below (Purpose search top 2 orders from order table whose freight_charges=2 and get the customers of those orders)

Working query with IN clause

    SELECT *
    FROM Customers C
    WHERE C.CUST_ID IN (
      SELECT TOP 2 CUST_ID
      FROM Orders O
      where FREIGHT_CHARGES = 2
    )

However I want to convert the IN clause into a more efficient EXISTS clause

Code not working with exists clause

    SELECT *
    FROM Customers C
    WHERE EXISTS (
        SELECT TOP 2 CUST_ID
        FROM Orders O
        where FREIGHT_CHARGES = 2 AND C.CUST_ID = O.CUST_ID
    )

In case of the second query I am not retrieving the top 2 cust_id BUT all the records.

Please let me know any implementation to get the desired result.

Edited: Using INNER JOIN as suggested in the answers . I am able to get the correct result. However since I don't want to retrieve any record from Orders table I thought exists would be a better approach performance wise.

    SELECT C.*
    FROM Customers C
    INNER JOIN (
      SELECT TOP 2 CUST_ID
      FROM Orders
      where FREIGHT_CHARGES = 2
    ) O ON C.CUST_ID=O.CUST_ID

Body:
I can suggest you should go for INNER JOIN. It is always a good practice to avoid subqueries if possible as it gets executed against each row from master table because it in WHERE condition. Rather, you can use simple INNER JOIN to get the desired output.

Like in your example, you just need TOP 2 customers having the FREIGHT_CHARGES value to 2. You can use below query using INNER JOIN.

SELECT
    TOP 2
    C.*
FROM Customers C
INNER JOIN Orders O ON C.CUST_ID = O.CUST_ID
WHERE O.FREIGHT_CHARGES = 2
ORDER BY C.CUST_ID -- Use 'ORDER BY' clause if 'C.CUST_ID' column does not have clustered index or you can use any other column

Please let me know your feedback.


问:
How to split images diagonally?
I have images like below. I would like to split them diagonally, probably using the centroid of the image or get the angle of the bounding rect/ellipse and cut along that.

The blue and green colors are to represent different contours, in practice, these will be binary thresholded, so all colors look the same.

I can cut the images horizontally or vertically using list slicing:

```<code>eg img_split=img[:50%,:]
</code>```

How do I do it diagonally in OpenCV Python/Numpy?

Images:

Split sample:

答:
I'm basically following your idea:

Inverse binary threshold the image (assumption: distinct object(s) on plain white background).

Find external contour (assumption: only one object/contour).

Find rotated rectangle of minimum area.

Calculate centroid.

With the centroid and the rotation angle, calculate the two edge points, where the "diagonal" divides the images in two parts.

Generate a mask for both image parts and split image using the mask and the "anti-mask".

Here's the full code:

import cv2
import numpy as np
from skimage import io              # Only needed for web reading images

def process(img_url):

    # Web read image
    img = cv2.cvtColor(io.imread(img_url), cv2.COLOR_RGB2BGR)
    img_c = img.copy()

    # Inverse binary threshold grayscale version of image
    # Assumption: plain white background
    img_thr = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 248, 255, cv2.THRESH_BINARY_INV)[1]

    # Find external contour
    # Assumption: only one object/contour
    cnts = cv2.findContours(img_thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    # Find rotated rectangle of the minimum area
    rect = cv2.minAreaRect(cnts[0])
    rect_pts = np.int0(cv2.boxPoints(rect))

    # Calculate centroid
    cent = np.int0((rect_pts[0] + rect_pts[2]) / 2)

    # Calculate tangent of rotation angle
    alpha = rect[2]
    if np.abs(alpha) > 45:
        alpha += 90
    tan_alpha = np.tan(np.deg2rad(alpha))

    # Calculate first edge point
    x0 = np.int32(cent[0] - cent[1] / tan_alpha)
    if x0 < 0:
        x0 = 0
        y0 = np.int32(-cent[0] * tan_alpha + cent[1])
    else:
        y0 = 0

    # Calculate second edge point
    x1 = np.int32(cent[0] + (img.shape[0] - cent[1]) / tan_alpha)
    if x1 > img.shape[1]:
        x1 = img.shape[1]
        y1 = np.int32((x1 - cent[0]) * tan_alpha + cent[1])
    else:
        y1 = img.shape[0]

    # Generate mask for cutting
    # Assumption: Image is sufficient large
    mask = np.zeros_like(img_thr)
    mask = cv2.line(mask, (x0, y0), (x1, y1), 255, 1)
    cv2.floodFill(mask, None, (cent[0] - 5, cent[1] - 5), 255)

    # Split image
    mask3 = np.repeat(np.expand_dims(mask, 2), 3, 2)
    img1 = ~mask3 + cv2.bitwise_and(img_c, img_c, mask=mask)
    img2 = mask3 + cv2.bitwise_and(img_c, img_c, mask=255-mask)

    # Debug output
    img = cv2.line(img, (x0, y0), (x1, y1), (0, 0, 255), 2)
    img = cv2.drawContours(img, [rect_pts], -1, (128, 128, 128), 2)
    img = cv2.circle(img, tuple(cent), 5, (255, 0, 0), 4)

    cv2.imshow('img', img)
    cv2.imshow('img1', img1)
    cv2.imshow('img2', img2)
    cv2.waitKey(0)

img_urls = [
    'https://i.stack.imgur.com/suzjF.png',
    'https://i.stack.imgur.com/Rl2WN.png'
]

for i in img_urls:
    process(i)

cv2.destroyAllWindows()
```

<p>And here are the results (with some debug output):</p>

<p><img src="https://i.stack.imgur.com/mQg4G.png" alt="First image: Debug"></p>

<p><img src="https://i.stack.imgur.com/Wg4vd.png" alt="First image: Upper half"></p>

<p><img src="https://i.stack.imgur.com/nK5tg.png" alt="First image: Lower half"></p>

<p><img src="https://i.stack.imgur.com/E2gAL.png" alt="Second image: Debug"></p>

<p><img src="https://i.stack.imgur.com/Buzeb.png" alt="Second image: Upper half"></p>

<p><img src="https://i.stack.imgur.com/QeTDr.png" alt="Second image: Lower half"></p>

<p>Hope that helps!</p>

<pre class="lang-none prettyprint-override"><code>----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
OpenCV:      4.2.0
----------------------------------------
</code>```

Title: How to split images diagonally?

Body:
I have images like below. I would like to split them diagonally, probably using the centroid of the image or get the angle of the bounding rect/ellipse and cut along that.

The blue and green colors are to represent different contours, in practice, these will be binary thresholded, so all colors look the same.

I can cut the images horizontally or vertically using list slicing:

eg img_split=img[:50%,:]

How do I do it diagonally in OpenCV Python/Numpy?

Images:

Split sample:

Body:
I'm basically following your idea:

Inverse binary threshold the image (assumption: distinct object(s) on plain white background).

Find external contour (assumption: only one object/contour).

Find rotated rectangle of minimum area.

Calculate centroid.

With the centroid and the rotation angle, calculate the two edge points, where the "diagonal" divides the images in two parts.

Generate a mask for both image parts and split image using the mask and the "anti-mask".

Here's the full code:

import cv2
import numpy as np
from skimage import io              # Only needed for web reading images

def process(img_url):

    # Web read image
    img = cv2.cvtColor(io.imread(img_url), cv2.COLOR_RGB2BGR)
    img_c = img.copy()

    # Inverse binary threshold grayscale version of image
    # Assumption: plain white background
    img_thr = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 248, 255, cv2.THRESH_BINARY_INV)[1]

    # Find external contour
    # Assumption: only one object/contour
    cnts = cv2.findContours(img_thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    # Find rotated rectangle of the minimum area
    rect = cv2.minAreaRect(cnts[0])
    rect_pts = np.int0(cv2.boxPoints(rect))

    # Calculate centroid
    cent = np.int0((rect_pts[0] + rect_pts[2]) / 2)

    # Calculate tangent of rotation angle
    alpha = rect[2]
    if np.abs(alpha) > 45:
        alpha += 90
    tan_alpha = np.tan(np.deg2rad(alpha))

    # Calculate first edge point
    x0 = np.int32(cent[0] - cent[1] / tan_alpha)
    if x0 < 0:
        x0 = 0
        y0 = np.int32(-cent[0] * tan_alpha + cent[1])
    else:
        y0 = 0

    # Calculate second edge point
    x1 = np.int32(cent[0] + (img.shape[0] - cent[1]) / tan_alpha)
    if x1 > img.shape[1]:
        x1 = img.shape[1]
        y1 = np.int32((x1 - cent[0]) * tan_alpha + cent[1])
    else:
        y1 = img.shape[0]

    # Generate mask for cutting
    # Assumption: Image is sufficient large
    mask = np.zeros_like(img_thr)
    mask = cv2.line(mask, (x0, y0), (x1, y1), 255, 1)
    cv2.floodFill(mask, None, (cent[0] - 5, cent[1] - 5), 255)

    # Split image
    mask3 = np.repeat(np.expand_dims(mask, 2), 3, 2)
    img1 = ~mask3 + cv2.bitwise_and(img_c, img_c, mask=mask)
    img2 = mask3 + cv2.bitwise_and(img_c, img_c, mask=255-mask)

    # Debug output
    img = cv2.line(img, (x0, y0), (x1, y1), (0, 0, 255), 2)
    img = cv2.drawContours(img, [rect_pts], -1, (128, 128, 128), 2)
    img = cv2.circle(img, tuple(cent), 5, (255, 0, 0), 4)

    cv2.imshow('img', img)
    cv2.imshow('img1', img1)
    cv2.imshow('img2', img2)
    cv2.waitKey(0)

img_urls = [
    'https://i.stack.imgur.com/suzjF.png',
    'https://i.stack.imgur.com/Rl2WN.png'
]

for i in img_urls:
    process(i)

cv2.destroyAllWindows()

And here are the results (with some debug output):

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
OpenCV:      4.2.0
----------------------------------------


问:
SwiftUI - How to close the sheet view, while dismissing that view
I want to achieve the function. Like, "Look up" view that is from Apple.

My aim is when the sheet view push another view by navigation, the user can tap the navigation item button to close the sheet view. Like, this below gif.

I try to achieve this function.

I found a problem that is when the user tap the "Done" button. The App doesn't close the sheet view. It only pop the view to parent view. Like, this below gif.

This is my code.

import SwiftUI

struct ContentView: View {
    @State var isShowSheet = false
    var body: some View {
        Button(action: {
            self.isShowSheet.toggle()
        }) {
            Text("Tap to show the sheet")
        }.sheet(isPresented: $isShowSheet) {
            NavView()
        }
    }
}

struct NavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView()) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Done")
            }
        )
    }
}

```

How did I achieve this function? :)
Please help me, thank you. :)

答:
UPDATE: Restored original version - provided below changes should be done, as intended, to the topic starter's code. Tested as worked with Xcode 13 / iOS 15

As navigation in sheet might be long enough and closing can be not in all navigation subviews, I prefer to use environment to have ability to specify closing feature only in needed places instead of passing binding via all navigation stack.

Here is possible approach (tested with Xcode 11.2 / iOS 13.2)

Define environment key to store sheet state

```<code>struct ShowingSheetKey: EnvironmentKey {
    static let defaultValue: Binding<Bool>? = nil
}

extension EnvironmentValues {
    var showingSheet: Binding<Bool>? {
        get { self[ShowingSheetKey.self] }
        set { self[ShowingSheetKey.self] = newValue }
    }
}
</code>```

Set this environment value to root of sheet content, so it will be available in any subview when declared

```<code>}.sheet(isPresented: $isShowSheet) {
    NavView()
       .environment(\.showingSheet, self.$isShowSheet)
}
</code>```

Declare & use environment value only in subview where it is going to be used

```<code>struct NavSubView: View {
    @Environment(\.showingSheet) var showingSheet

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button("Done") {
                self.showingSheet?.wrappedValue = false
            }
        )
    }
}
</code>```

Body:
I want to achieve the function. Like, "Look up" view that is from Apple.

My aim is when the sheet view push another view by navigation, the user can tap the navigation item button to close the sheet view. Like, this below gif.

I try to achieve this function.

I found a problem that is when the user tap the "Done" button. The App doesn't close the sheet view. It only pop the view to parent view. Like, this below gif.

This is my code.

import SwiftUI

struct ContentView: View {
    @State var isShowSheet = false
    var body: some View {
        Button(action: {
            self.isShowSheet.toggle()
        }) {
            Text("Tap to show the sheet")
        }.sheet(isPresented: $isShowSheet) {
            NavView()
        }
    }
}

struct NavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView()) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Done")
            }
        )
    }
}

How did I achieve this function? :)
Please help me, thank you. :)

Body:
UPDATE: Restored original version - provided below changes should be done, as intended, to the topic starter's code. Tested as worked with Xcode 13 / iOS 15

As navigation in sheet might be long enough and closing can be not in all navigation subviews, I prefer to use environment to have ability to specify closing feature only in needed places instead of passing binding via all navigation stack.

Here is possible approach (tested with Xcode 11.2 / iOS 13.2)

Define environment key to store sheet state

struct ShowingSheetKey: EnvironmentKey {
    static let defaultValue: Binding<Bool>? = nil
}

extension EnvironmentValues {
    var showingSheet: Binding<Bool>? {
        get { self[ShowingSheetKey.self] }
        set { self[ShowingSheetKey.self] = newValue }
    }
}

Set this environment value to root of sheet content, so it will be available in any subview when declared

}.sheet(isPresented: $isShowSheet) {
    NavView()
       .environment(\.showingSheet, self.$isShowSheet)
}

Declare & use environment value only in subview where it is going to be used

struct NavSubView: View {
    @Environment(\.showingSheet) var showingSheet

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button("Done") {
                self.showingSheet?.wrappedValue = false
            }
        )
    }
}


问:
VBA Extract data from specific column on another sheet
I have 2 sheets which I extract from the system. For sheet1(Data) contain multiple column and all the data inside. For sheet2(Get) I have 2 column, as per below. With reference column no 2 (ID) on sheet2(Get), I want to search this value in the sheet1(Data) then extract specific column value. I try to search online for example code and found this piece of code which extract all column value. But I only want to extract column with highlighted with yellow then extract this value into sheet2(Get). Can help me to modified this code?

Note: For sheet2(Get), all the data on both column A and B already prefilled so I would like to change Worksheet_SelectionChange into a normal sub then run this sub using macro. Possible?

```<code>Column C (Get sheet) should extract from Column B (Data sheet)
Column D (Get sheet) should extract from Column M (Data sheet)
Column E (Get sheet) should extract from Column J (Data sheet)
Column F (Get sheet) should extract from Column L (Data sheet)
Column G (Get sheet) should extract from Column C (Data sheet)
Column H (Get sheet) should extract from Column G (Data sheet)
</code>```

sheet2(Get)

sheet1(Data)

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim k As Integer, i As Long, Str As Range
    'row number
    For i = 3 To Sheets("GetData").Range("a65536").End(3).Row
        Set Str = Sheets("Data").Range("a:a").Find(Cells(i, 1).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then
            'column number
            For k = 1 To 14
                If k > 1 Then Sheets("GetData").Cells(i, k).Value = Sheets("Data").Cells(Str.Row, k).Value
            Next k
        Else
            For k = 2 To 14

                Sheets("GetData").Cells(i, k).Value = "Null"
            Next k

        End If
    Next i
End Sub
</code>```

答:
```<code>Public Sub fill_data()
    Dim k As Integer, i As Long, Str As Range, col As Long, e As Variant
    'row number
    For i = 2 To Sheets("GetData").Range("B65536").End(3).Row
        Set Str = Sheets("Data").Range("A:A").Find(Cells(i, 2).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then 'if not empty
        col = 3
            For Each e In Array(13, 2, 10, 3, 5, 12, 9) 'columns to fetch
            Sheets("GetData").Cells(i, col).Value = Str.EntireRow.Cells(e).Value
            col = col + 1
            Next
        Else 'if empty
        For col = 3 To 9
            'Sheets("GetData").Cells(i, col).Interior.ColorIndex = 16 'change cell color OR
            Sheets("GetData").Cells(i, col).Value = "NOTFOUND" 'change cell text
            Next col
        End If
    Next i
End Sub
</code>```

Thank you to Tim Williams for you help.

Body:
I have 2 sheets which I extract from the system. For sheet1(Data) contain multiple column and all the data inside. For sheet2(Get) I have 2 column, as per below. With reference column no 2 (ID) on sheet2(Get), I want to search this value in the sheet1(Data) then extract specific column value. I try to search online for example code and found this piece of code which extract all column value. But I only want to extract column with highlighted with yellow then extract this value into sheet2(Get). Can help me to modified this code?

Note: For sheet2(Get), all the data on both column A and B already prefilled so I would like to change Worksheet_SelectionChange into a normal sub then run this sub using macro. Possible?

Column C (Get sheet) should extract from Column B (Data sheet)
Column D (Get sheet) should extract from Column M (Data sheet)
Column E (Get sheet) should extract from Column J (Data sheet)
Column F (Get sheet) should extract from Column L (Data sheet)
Column G (Get sheet) should extract from Column C (Data sheet)
Column H (Get sheet) should extract from Column G (Data sheet)

sheet2(Get)

sheet1(Data)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim k As Integer, i As Long, Str As Range
    'row number
    For i = 3 To Sheets("GetData").Range("a65536").End(3).Row
        Set Str = Sheets("Data").Range("a:a").Find(Cells(i, 1).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then
            'column number
            For k = 1 To 14
                If k > 1 Then Sheets("GetData").Cells(i, k).Value = Sheets("Data").Cells(Str.Row, k).Value
            Next k
        Else
            For k = 2 To 14

                Sheets("GetData").Cells(i, k).Value = "Null"
            Next k

        End If
    Next i
End Sub

Body:
Public Sub fill_data()
    Dim k As Integer, i As Long, Str As Range, col As Long, e As Variant
    'row number
    For i = 2 To Sheets("GetData").Range("B65536").End(3).Row
        Set Str = Sheets("Data").Range("A:A").Find(Cells(i, 2).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then 'if not empty
        col = 3
            For Each e In Array(13, 2, 10, 3, 5, 12, 9) 'columns to fetch
            Sheets("GetData").Cells(i, col).Value = Str.EntireRow.Cells(e).Value
            col = col + 1
            Next
        Else 'if empty
        For col = 3 To 9
            'Sheets("GetData").Cells(i, col).Interior.ColorIndex = 16 'change cell color OR
            Sheets("GetData").Cells(i, col).Value = "NOTFOUND" 'change cell text
            Next col
        End If
    Next i
End Sub

Thank you to Tim Williams for you help.


问:
PayPal payment integration for REACT NATIVE with latest lib android + ios
Can any body provide a swipe solution with latest react-native PayPal library ?

I have spent a week but not getting a proper solution.

There are many old and incomplete solution on net but not a proper and
complete solution for new developers.

Resources :

https://www.npmjs.com/package/react-native-paypal

https://github.com/MattFoley/react-native-paypal

https://github.com/sharafat/sample-code-php

答:
Screenshot attached
link=
https://www.npmjs.com/package/react-native-paypal-lib
Use this Library for React Native Application It's very simple to implements.follow these steps for implementation.</p>


问:
existing nodeJS and swagger JS docs not working
I have a simple nodeJS project and want to add swagger into it.
I have required swaggerUI and swaggerJSDoc

Here is my app.js file.

```<code>// requires
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const postsRoutes = require("./routes/posts/posts");
const userRoutes = require("./routes/auth/user");
const swaggerUi = require("swagger-ui-express");
const swaggerJSDoc = require("swagger-jsdoc");

// https://swagger.io/specification/v2/
const swaggerOptions = {
  swaggerDefinition: {
    info: {
      title: "Post API",
      description: "This is a sample Post API",
      contact: {
        name: "Test ",
        url: "http://www.swagger.io/support",
        email: "test@gmail.com"
      },
      servers: ["http://localhost:3850/"]
    }
  },
  swagger: "2.0",
  apis: ["/backend/routes/posts/posts.js"]
};

const app = express();
let options = {
  explorer: true
};

// swagger
const swaggerDocs = swaggerJSDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs, options));

// MONGOOSE CONNECT
mongoose
  .connect(
    "mongodb+srv://"
  )
  .then(() => {
    console.log("####-connected to MongoDB");
  })
  .catch(error => {
    console.log("Connection ERROR!", error);
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join("backend/images")));

// CORS
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

// ROUTES
app.use("/api/posts", postsRoutes);
app.use("/api/user", userRoutes);

module.exports = app;
</code>```

I have a couple of routes, also a post.js route file. This file is included in the array, with the definition of swagger.

```<code>// express router
const router = express.Router();

// get posts endpoint
/**
 * @swagger
 * /api/posts:
 *  get:
 *   description use to request all posts
 *   responses:
 *   '200':
 *     description: a successful response
 */
router.get("", PostController.getPosts);
</code>```

Unfortunately I don't see any api definition in the browser.

Can somebody help me?

Grz,
Pete

答:
Its very simple to add swagger in your project. just follow the steps:-

Install the module "swagger-ui-express"

npm install swagger-ui-express

In your app.js file add:-

```<code>const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
</code>```

create swagger.json file (I have added simple login API and classes) looks like:-

```<code>{
    "swagger": "2.0",
    "info": {
      "version": "1.0.0",
      "title": "Parveen App API",
      "description": "Find out how your APIs work",
      "license": {
        "name": "MIT",
        "url": "https://opensource.org/licenses/MIT"
      }
    },
    "host": "localhost:5000",
    "basePath": "/api/v1",
    "tags": [
      {
        "name": "Users",
        "description": "API for users in the system"
      }

    ],
    "schemes": [
      "http",
      "https"
    ],
    "consumes": [
      "application/json"
    ],
    "produces": [
      "application/json"
    ],
    "securityDefinitions": {
        "ApiKeyAuth":{
          "type": "apiKey",
          "in": "headers",
          "name": "authorization"
        }
    },
    "paths": {
      "/users/login": {
        "post": {
          "summary": "Login user",
          "tags": [
            "Users"
          ],
          "description": "Login user in system",
          "parameters": [
            {
              "name": "user",
              "in": "body",
              "description": "Login user",
              "schema": {
                "$ref": "#/definitions/User"
              }
            }
          ],
          "produces": [
            "application/json"
          ],
          "responses": {
            "200": {
              "description": "Login Success",
              "schema": {
                "$ref": "#/definitions/User"
              }
            },
            "401":{
              "description": "Login details are not valid!!"
            },
            "404":{
              "description": "Email is not registered!"
            },
            "500":{
              "description": "User login failed!!"
            }
          }
        }
      }
    },

    "definitions": {

      "User": {
        "properties": {
          "email": {
            "type": "string"
          },
          "password": {
            "type": "string"
          }
        }
      },
      "userEmail":{
        "properties": {
          "email": {
            "type": "string"
          }
        }
      }

    }
  }
</code>```

You can add/change swagger.json according to your API.

Now simply open http://localhost:5000/api-docs

It will work like a champ!

Hope this will help!

Body:
I have a simple nodeJS project and want to add swagger into it.
I have required swaggerUI and swaggerJSDoc

Here is my app.js file.

// requires
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const postsRoutes = require("./routes/posts/posts");
const userRoutes = require("./routes/auth/user");
const swaggerUi = require("swagger-ui-express");
const swaggerJSDoc = require("swagger-jsdoc");

// https://swagger.io/specification/v2/
const swaggerOptions = {
  swaggerDefinition: {
    info: {
      title: "Post API",
      description: "This is a sample Post API",
      contact: {
        name: "Test ",
        url: "http://www.swagger.io/support",
        email: "test@gmail.com"
      },
      servers: ["http://localhost:3850/"]
    }
  },
  swagger: "2.0",
  apis: ["/backend/routes/posts/posts.js"]
};

const app = express();
let options = {
  explorer: true
};

// swagger
const swaggerDocs = swaggerJSDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs, options));

// MONGOOSE CONNECT
mongoose
  .connect(
    "mongodb+srv://"
  )
  .then(() => {
    console.log("####-connected to MongoDB");
  })
  .catch(error => {
    console.log("Connection ERROR!", error);
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join("backend/images")));

// CORS
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

// ROUTES
app.use("/api/posts", postsRoutes);
app.use("/api/user", userRoutes);

module.exports = app;

I have a couple of routes, also a post.js route file. This file is included in the array, with the definition of swagger.

// express router
const router = express.Router();

// get posts endpoint
/**
 * @swagger
 * /api/posts:
 *  get:
 *   description use to request all posts
 *   responses:
 *   '200':
 *     description: a successful response
 */
router.get("", PostController.getPosts);

Unfortunately I don't see any api definition in the browser.

Can somebody help me?

Grz,
Pete

Body:
Its very simple to add swagger in your project. just follow the steps:-

Install the module "swagger-ui-express"

npm install swagger-ui-express

In your app.js file add:-

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

create swagger.json file (I have added simple login API and classes) looks like:-

{
    "swagger": "2.0",
    "info": {
      "version": "1.0.0",
      "title": "Parveen App API",
      "description": "Find out how your APIs work",
      "license": {
        "name": "MIT",
        "url": "https://opensource.org/licenses/MIT"
      }
    },
    "host": "localhost:5000",
    "basePath": "/api/v1",
    "tags": [
      {
        "name": "Users",
        "description": "API for users in the system"
      }

    ],
    "schemes": [
      "http",
      "https"
    ],
    "consumes": [
      "application/json"
    ],
    "produces": [
      "application/json"
    ],
    "securityDefinitions": {
        "ApiKeyAuth":{
          "type": "apiKey",
          "in": "headers",
          "name": "authorization"
        }
    },
    "paths": {
      "/users/login": {
        "post": {
          "summary": "Login user",
          "tags": [
            "Users"
          ],
          "description": "Login user in system",
          "parameters": [
            {
              "name": "user",
              "in": "body",
              "description": "Login user",
              "schema": {
                "$ref": "#/definitions/User"
              }
            }
          ],
          "produces": [
            "application/json"
          ],
          "responses": {
            "200": {
              "description": "Login Success",
              "schema": {
                "$ref": "#/definitions/User"
              }
            },
            "401":{
              "description": "Login details are not valid!!"
            },
            "404":{
              "description": "Email is not registered!"
            },
            "500":{
              "description": "User login failed!!"
            }
          }
        }
      }
    },

    "definitions": {

      "User": {
        "properties": {
          "email": {
            "type": "string"
          },
          "password": {
            "type": "string"
          }
        }
      },
      "userEmail":{
        "properties": {
          "email": {
            "type": "string"
          }
        }
      }

    }
  }

You can add/change swagger.json according to your API.

Now simply open http://localhost:5000/api-docs

It will work like a champ!

Hope this will help!


问:
WildFly - getting resource from WAR
I am using the following method to get a resource from WAR file in WildFly:

```<code>this.getClass().getResource(relativePath)
</code>```

It works when the application is deployed as exploded WAR. It used to work with compressed WAR, too. Yesterday, I did a clean and rebuild of project in Eclipse, and it just stopped working.

When I check the resource root:

```<code>logger.info(this.getClass().getResource("/").toExternalForm());
</code>```

I get this:

```<code>file:/C:/JBoss/wildfly8.1.0.CR1/modules/system/layers/base/org/jboss/as/ejb3/main/timers/
</code>```

So, no wonder it doesn't work. It probably has something to do with JBoss module loading, but I don't know if this is a bug or normal behavior.

I found various similar problems on StackOverflow, but no applicable solution. One of the suggestions is to use ServletContext like so:

```<code>@Resource
private WebServiceContext wsContext;
...
ServletContext servletContext = (ServletContext)this.wsContext.getMessageContext()
        .get(MessageContext.SERVLET_CONTEXT);
servletContext.getResource(resourcePath);
</code>```

But, when I try to obtain MessageContext in this manner, I get an IllegalStateException. So I am basically stuck. Any ideas?

答:
I decided so:</p>

```<code>@Autowired
private final ApplicationContext ctx;
private final Path path = Paths.get("testfiles/load")

ctx.getRosource("classpath:" + path);
</code>```

Title: WildFly - getting resource from WAR

Body:
I am using the following method to get a resource from WAR file in WildFly:

this.getClass().getResource(relativePath)

It works when the application is deployed as exploded WAR. It used to work with compressed WAR, too. Yesterday, I did a clean and rebuild of project in Eclipse, and it just stopped working.

When I check the resource root:

logger.info(this.getClass().getResource("/").toExternalForm());

I get this:

file:/C:/JBoss/wildfly8.1.0.CR1/modules/system/layers/base/org/jboss/as/ejb3/main/timers/

So, no wonder it doesn't work. It probably has something to do with JBoss module loading, but I don't know if this is a bug or normal behavior.

I found various similar problems on StackOverflow, but no applicable solution. One of the suggestions is to use ServletContext like so:

@Resource
private WebServiceContext wsContext;
...
ServletContext servletContext = (ServletContext)this.wsContext.getMessageContext()
        .get(MessageContext.SERVLET_CONTEXT);
servletContext.getResource(resourcePath);

But, when I try to obtain MessageContext in this manner, I get an IllegalStateException. So I am basically stuck. Any ideas?

Body:
I decided so:

@Autowired
private final ApplicationContext ctx;
private final Path path = Paths.get("testfiles/load")

ctx.getRosource("classpath:" + path);


问:
VS Code : how do I disable copy on selection
I'm using VS Code 1.32 on ubuntu, which i access as a remote client app through ssh on windows.

Whenever I select text using the mouse or the clipboard, it is automatically copied in the clipboard. The only plugins i have are prettier and eslint.

How can i disable that behavior ?

答: Settings: Editor: Selection Clipboard - uncheck</p>


答:
The EXISTS operator is a logical operator that allows you to check whether a subquery returns any row.
The EXISTS operator returns TRUE if the subquery returns at least one or more row.

So, since every row in Order table with FREIGHT_CHARGES = 2 will return TRUE for EXISTS statement (does not matter if it is TOP 2, 1 would be enough) the result includes every records in Customers table with proper CUST_ID's in Orders.

In your case, EXISTS won't be a good choice for you.

Please check this link:
https://www.sqlservertutorial.net/sql-server-basics/sql-server-exists/

Title: EXISTS clause ISSUE with TOP clause in sub query


问:
Enable submit button with validation
Here is my code.
The problem I encountered is how do I make the submit button work only when it is 10?

```<code><input type="text" name="qty>
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

<script>
   $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[id="qty"]').on('keyup',function(){
            if($(this).val() == 10)
            $('input[id="button"]').attr('disabled',false);
    });
});
</script>
</code>```

How do i fix it?

答:
Please check, I have updated your code

  $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[name="qty"]').keyup(function(){
            if($(this).val() == 10){
            $('input[id="button"]').removeAttr('disabled');
            }
            else{
              $('input[id="button"]').attr('disabled',true);
            }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button"></code>```

Title: Enable submit button with validation

Body:
Here is my code.
The problem I encountered is how do I make the submit button work only when it is 10?

<input type="text" name="qty>
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

How do i fix it?

Body:
Please check, I have updated your code

  $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[name="qty"]').keyup(function(){
            if($(this).val() == 10){
            $('input[id="button"]').removeAttr('disabled');
            }
            else{
              $('input[id="button"]').attr('disabled',true);
            }
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button">


问:
C# How can I communicate between winfirms app and unity android app?
I'm working on a project for my friend and I need to implement communication between windows forms app and unity android app but I don't know how. Example of my code:

Unity:

```<code>Class program
{

   Public InputField password;

   Public static void Loggin ()
   {

      String localpass = password.text;

      String winpass = //passS from WinForm code

      If (localpass == winpass)
         Mytextbox.text = "success";
      Else
         Mytextbox.text = "wrong password";

   }

}
</code>```

WinForm:

```<code>Public static void myVoid ()
{

   String passS = File.ReadLines(App domain.CurrentDomain.BaseDirectory + @"\\mytextfile.txt").ElementAtOrDefault(3);

}
</code>```

答:
Direct communication

Socket programming is your friend. This means that the two applications are aware of each other, or at least one of them (the client) is aware of the other (the server)

C# example of a tcp/ip listener

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;      //required
using System.Net.Sockets;    //required

namespace ServerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = new TcpListener(IPAddress.Any, 9999);
           // we set our IP address as server's address, and we also set the port: 9999

            server.Start();  // this will start the server

            while (true)   //we wait for a connection
            {
                TcpClient client = server.AcceptTcpClient();  //if a connection exists, the server will accept it

                NetworkStream ns = client.GetStream(); //networkstream is used to send/receive messages

                byte[] hello = new byte[100];   //any message must be serialized (converted to byte array)
                hello = Encoding.Default.GetBytes("hello world");  //conversion string => byte array

                ns.Write(hello, 0, hello.Length);     //sending the message

                while (client.Connected)  //while the client is connected, we look for incoming messages
                {
                    byte[] msg = new byte[1024];     //the messages arrive as byte array
                    ns.Read(msg, 0, msg.Length);   //the same networkstream reads the message sent by the client
                    Console.WriteLine(encoder.GetString(msg).Trim('')); //now , we write the message as string
                }
            }
</code>```

Create an api to communicate

The options are unlimited. Create a rest api using WebApi 2 or any other technology to periodically hit and check for data updates.

This communication is asynchronous and not direct,  so you should account for that in some way.

Use push notifications

Mobile applications can get push notifications. If the communication is not bidirectional, this on its own could be a solution.

If it is, then the mobile application could communicate via an api and the forms application via push notifications

Check https://gamedev.stackexchange.com/questions/157009/how-can-i-send-android-notifications-from-my-unity-game#

Body:
I'm working on a project for my friend and I need to implement communication between windows forms app and unity android app but I don't know how. Example of my code:

Unity:

Class program
{

   Public InputField password;

   Public static void Loggin ()
   {

      String localpass = password.text;

      String winpass = //passS from WinForm code

      If (localpass == winpass)
         Mytextbox.text = "success";
      Else
         Mytextbox.text = "wrong password";

   }

}

WinForm:

Public static void myVoid ()
{

   String passS = File.ReadLines(App domain.CurrentDomain.BaseDirectory + @"\\mytextfile.txt").ElementAtOrDefault(3);

}

Body:
Direct communication

Socket programming is your friend. This means that the two applications are aware of each other, or at least one of them (the client) is aware of the other (the server)

C# example of a tcp/ip listener

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;      //required
using System.Net.Sockets;    //required

namespace ServerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = new TcpListener(IPAddress.Any, 9999);
           // we set our IP address as server's address, and we also set the port: 9999

            server.Start();  // this will start the server

            while (true)   //we wait for a connection
            {
                TcpClient client = server.AcceptTcpClient();  //if a connection exists, the server will accept it

                NetworkStream ns = client.GetStream(); //networkstream is used to send/receive messages

                byte[] hello = new byte[100];   //any message must be serialized (converted to byte array)
                hello = Encoding.Default.GetBytes("hello world");  //conversion string => byte array

                ns.Write(hello, 0, hello.Length);     //sending the message

                while (client.Connected)  //while the client is connected, we look for incoming messages
                {
                    byte[] msg = new byte[1024];     //the messages arrive as byte array
                    ns.Read(msg, 0, msg.Length);   //the same networkstream reads the message sent by the client
                    Console.WriteLine(encoder.GetString(msg).Trim('')); //now , we write the message as string
                }
            }

Create an api to communicate

The options are unlimited. Create a rest api using WebApi 2 or any other technology to periodically hit and check for data updates.

This communication is asynchronous and not direct,  so you should account for that in some way.

Use push notifications

Mobile applications can get push notifications. If the communication is not bidirectional, this on its own could be a solution.

If it is, then the mobile application could communicate via an api and the forms application via push notifications

Check https://gamedev.stackexchange.com/questions/157009/how-can-i-send-android-notifications-from-my-unity-game#


问:
How to pass default value loaded into form input to the payload
I'm making an edit form which inside Modal. Form inputs has defaultValue that comes from props with an name, age and strength as default value. If I change all inputs value, everything works fine, but if I change only one input value when I console.log payload I got and empty strings, but only value that I changed goes to the payload.  How can I make that even I change only one input payload gets inputs default value from props?

My code is here:

```<code>import React, { Component } from 'react';
import './Form.scss';
import axios from 'axios';

class Form extends Component {
    constructor(props){
        super(props);
        this.state = {
            id: this.props.gnomeId,
            submitedName: '',
            submitedAge: '',
            submitedStrength: ''
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value,
        });
    }

    onSubmit(event) {
        event.preventDefault();

        const gnome = {
                name: this.state.submitedName,
                age: this.state.submitedAge,
                strenght: this.state.submitedStrength,
              }
        console.log(gnome);

        axios.post(`${API}/${this.state.id}`, {gnome})
        .then( res => {
            console.log(res);
            console.log(res.data);
        });
    }

    render() {
        return(
            <form onSubmit={this.onSubmit}>
                <div>
                    <label htmlFor="name">Name</label>
                    <input type="text" name="submitedName" id="name" defaultValue={this.props.gnomeName} onChange={this.handleChange}/>
                </div>
                <div>
                    <label htmlFor="age">Age</label>
                    <input type="text" name="submitedAge" id="age" defaultValue={this.props.gnomeAge} onChange={this.handleChange}/>
                </div>
                <div>
                    <label htmlFor="strength">Strength</label>
                    <input type="text" name="submitedStrength" id="strength" defaultValue={this.props.gnomeStrength} onChange={this.handleChange}/>
                </div>
                <button type="submit" className="submit-btn">Submit</button>
            </form>
        )
    }
}

export default Form;
</code>```

答:
You may use Nullish_Coalescing_Operator to give different value from init as null/undefined</p>

```<code>this.state = {
  submitedName: null,
  ...
}

const gnome = {
  name: this.state.submitedName ?? this.props.submitedName,
  ...
}
</code>```

Body:
I'm making an edit form which inside Modal. Form inputs has defaultValue that comes from props with an name, age and strength as default value. If I change all inputs value, everything works fine, but if I change only one input value when I console.log payload I got and empty strings, but only value that I changed goes to the payload.  How can I make that even I change only one input payload gets inputs default value from props?

My code is here:

import React, { Component } from 'react';
import './Form.scss';
import axios from 'axios';

class Form extends Component {
    constructor(props){
        super(props);
        this.state = {
            id: this.props.gnomeId,
            submitedName: '',
            submitedAge: '',
            submitedStrength: ''
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value,
        });
    }

    onSubmit(event) {
        event.preventDefault();

        const gnome = {
                name: this.state.submitedName,
                age: this.state.submitedAge,
                strenght: this.state.submitedStrength,
              }
        console.log(gnome);

        axios.post(`${API}/${this.state.id}`, {gnome})
        .then( res => {
            console.log(res);
            console.log(res.data);
        });
    }

    render() {
        return(
            <form onSubmit={this.onSubmit}>

                    Name
                    <input type="text" name="submitedName" id="name" defaultValue={this.props.gnomeName} onChange={this.handleChange}/>

                    Age
                    <input type="text" name="submitedAge" id="age" defaultValue={this.props.gnomeAge} onChange={this.handleChange}/>

                    Strength
                    <input type="text" name="submitedStrength" id="strength" defaultValue={this.props.gnomeStrength} onChange={this.handleChange}/>

                <button type="submit" className="submit-btn">Submit</button>
            </form>
        )
    }
}

export default Form;

Body:
You may use Nullish_Coalescing_Operator to give different value from init as null/undefined

this.state = {
  submitedName: null,
  ...
}

const gnome = {
  name: this.state.submitedName ?? this.props.submitedName,
  ...
}


答:
I have made some corrections in your code, and now its working. The problem in your code was, you were writing key up event on ID but haven't assigned any id to input box, but you had name property so instead of id I used that name property as a selector for key up event.

$(document).ready(function() {
  $('input[id="button"]').attr('disabled', true);
  $('input[name="qty"]').on('keyup', function() {
    if ($(this).val() == 10) {
      $('input[id="button"]').attr('disabled', false);
    } else {
      $('input[id="button"]').attr('disabled', true);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" name="qty" />
<input type="submit" name="proceedbtn" value="PROCEED" id="button" /></code>```

Title: Enable submit button with validation

Body:
I have made some corrections in your code, and now its working. The problem in your code was, you were writing key up event on ID but haven't assigned any id to input box, but you had name property so instead of id I used that name property as a selector for key up event.

$(document).ready(function() {
  $('input[id="button"]').attr('disabled', true);
  $('input[name="qty"]').on('keyup', function() {
    if ($(this).val() == 10) {
      $('input[id="button"]').attr('disabled', false);
    } else {
      $('input[id="button"]').attr('disabled', true);
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" name="qty" />
<input type="submit" name="proceedbtn" value="PROCEED" id="button" />


问:
How to assign API key in manifest from Constant Value class?
I am trying to assign value to below meta in manifest.

currently i have assign value from string.xml class.

```<code><meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value= "@string/MAPS_API_KEY" />
</code>```

But I want Some thing like this..

```<code><meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value= com.packagename.MyConstantInterface.MAPS_API_KEY />
</code>```

I have search a lot, but haven't find a good solution.

NOTE: I am getting all APIs keys from server, storing keys in snappy db and then assigning keys from snappy db to MyConstantInterface.

答:
You simply can not simply use a java variable.

Instead of it, You need to inject build variables into the manifest

Declaration:

```<code>defaultConfig {
    ...
    manifestPlaceholders = [MAPS_API_KEY_FOR_MANIFEST: "your_maps_key_here"] // TO use in manifest file
    buildConfigField "String", "MAPS_API_KEY", '"your_maps_key_here"' // TO use in java file
}
</code>```

Use in AndroidManifest.xml:

```<code>    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value= "${MAPS_API_KEY_FOR_MANIFEST}" />
</code>```

Java file Usage:

```<code>BuildConfig.MAPS_API_KEY
</code>```

For more information, You can have a look at this and this.

Body:
I am trying to assign value to below meta in manifest.

currently i have assign value from string.xml class.

<meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value= "@string/MAPS_API_KEY" />

But I want Some thing like this..

<meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value= com.packagename.MyConstantInterface.MAPS_API_KEY />

I have search a lot, but haven't find a good solution.

NOTE: I am getting all APIs keys from server, storing keys in snappy db and then assigning keys from snappy db to MyConstantInterface.

Body:
You simply can not simply use a java variable.

Instead of it, You need to inject build variables into the manifest

Declaration:

defaultConfig {
    ...
    manifestPlaceholders = [MAPS_API_KEY_FOR_MANIFEST: "your_maps_key_here"] // TO use in manifest file
    buildConfigField "String", "MAPS_API_KEY", '"your_maps_key_here"' // TO use in java file
}

Use in AndroidManifest.xml:

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value= "${MAPS_API_KEY_FOR_MANIFEST}" />

Java file Usage:

BuildConfig.MAPS_API_KEY

For more information, You can have a look at this and this.


问:
Clear React Native TextInput
Working through the Redux AddTodo example in React Native. The first AddTodo example below uses state to store the TextInput value and works fine.

```<code>class AddTodo extends React.Component{

    constructor(props){
        super(props);
        this.state = { todoText: "" };
    }
    update(e){
        if(this.state.todoText.trim()) this.props.dispatch(addTodo(this.state.todoText));
        this.setState({todoText: "" });
    }
    render(){
        return(
            <TextInput
                value = {this.state.todoText}
                onSubmitEditing = { (e)=> { this.update(e); } }
                onChangeText = { (text) => {this.setState({todoText: text}) } } />
        );
    }
}
</code>```

However following a few of the Redux examples, the following code is much shorter and also works except that the TextInput value is not cleared after submitting

```<code>let AddTodo = ({ dispatch }) => {

  return (
      <TextInput
          onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
      />
  )
}
</code>```

Is there any way I can clear the InputText value from onSubmitEditing?

答:
React-Native Using Input component from native-base.
This worked for me:

```<code><Input ref={input => {this.textInput = input;}}
</code>```

and then:

```<code>this.textInput._root.clear();
</code>```

Note: Did not have to use React.createRef() to initialise.

Title: Clear React Native TextInput

Body:
Working through the Redux AddTodo example in React Native. The first AddTodo example below uses state to store the TextInput value and works fine.

class AddTodo extends React.Component{

    constructor(props){
        super(props);
        this.state = { todoText: "" };
    }
    update(e){
        if(this.state.todoText.trim()) this.props.dispatch(addTodo(this.state.todoText));
        this.setState({todoText: "" });
    }
    render(){
        return(
            <TextInput
                value = {this.state.todoText}
                onSubmitEditing = { (e)=> { this.update(e); } }
                onChangeText = { (text) => {this.setState({todoText: text}) } } />
        );
    }
}

However following a few of the Redux examples, the following code is much shorter and also works except that the TextInput value is not cleared after submitting

let AddTodo = ({ dispatch }) => {

  return (
      <TextInput
          onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
      />
  )
}

Is there any way I can clear the InputText value from onSubmitEditing?

Body:
React-Native Using Input component from native-base.
This worked for me:

<Input ref={input => {this.textInput = input;}}

and then:

this.textInput._root.clear();

Note: Did not have to use React.createRef() to initialise.


答:
```<code>   SELECT Top 2 *
    FROM Customers as C
    WHERE EXISTS (
        SELECT O.CUST_ID
        FROM Orders as O
        where FREIGHT_CHARGES = 2 AND C.CUST_ID = O.CUST_ID
    )
</code>```

Body:
I have a query sub query below (Purpose search top 2 orders from order table whose freight_charges=2 and get the customers of those orders)

Working query with IN clause

    SELECT *
    FROM Customers C
    WHERE C.CUST_ID IN (
      SELECT TOP 2 CUST_ID
      FROM Orders O
      where FREIGHT_CHARGES = 2
    )

However I want to convert the IN clause into a more efficient EXISTS clause

Code not working with exists clause

    SELECT *
    FROM Customers C
    WHERE EXISTS (
        SELECT TOP 2 CUST_ID
        FROM Orders O
        where FREIGHT_CHARGES = 2 AND C.CUST_ID = O.CUST_ID
    )

In case of the second query I am not retrieving the top 2 cust_id BUT all the records.

Please let me know any implementation to get the desired result.

Edited: Using INNER JOIN as suggested in the answers . I am able to get the correct result. However since I don't want to retrieve any record from Orders table I thought exists would be a better approach performance wise.

    SELECT C.*
    FROM Customers C
    INNER JOIN (
      SELECT TOP 2 CUST_ID
      FROM Orders
      where FREIGHT_CHARGES = 2
    ) O ON C.CUST_ID=O.CUST_ID