问:
How do you find which words a trained naive bayes classifier uses to make decisions?
I have created a Naive Bayes classifier that uses the text of tweets from different politicians to predict their party. I used the sklearn MultinomialNB implementation. Here is my implementation:

```<code>Senators_Vectorizer = CountVectorizer(decode_error= 'replace')
senator_counts = Senators_Vectorizer.fit_transform(senator_tweets['text'].values)
senator_targets = senator_tweets['party'].values

senator_counts_train, senator_counts_test, senator_targets_train, senator_targets_test = train_test_split(senator_counts, senator_targets, test_size = .1)

senator_party_clf = MultinomialNB()
senator_party_clf.fit(senator_counts_train, senator_targets_train)
</code>```

How do I find the words that the Naive Bayes classifier is using to make prediction? Is there a way to find which words have the highest probability of being in Democrats'/Republicans' tweets?

I want the probabilities each word in the Senators_Vectorizer not the probability of a specific tweet being from a specific party.

答:
Use the feature_log_prob_/coef_ attribute to get the probabilities for each feature.

From Documentation:

feature_log_prob_: ndarray of shape (n_classes, n_features).

  Empirical log probability of features given a class, P(x_i|y).

coef_: ndarray of shape (n_classes, n_features)

  Mirrors feature_log_prob_ for interpreting MultinomialNB as a linear model.

This tutorial would be help I guess.

Quick example to get the top features for each class:

```<code>categories = ['alt.atheism', 'talk.religion.misc',
              'comp.graphics', 'sci.space']

newsgroups_train = fetch_20newsgroups(subset='train',
                                     remove=('headers', 'footers', 'quotes'),
                                     categories=categories)
vectorizer = TfidfVectorizer(stop_words='english')
vectors = vectorizer.fit_transform(newsgroups_train.data)
clf = MultinomialNB(alpha=.01).fit(vectors, newsgroups_train.target)

import numpy as np
def show_top10(classifier, vectorizer, categories):
    feature_names = np.asarray(vectorizer.get_feature_names())
    for i, category in enumerate(categories):
        top10 = np.argsort(classifier.coef_[i])[-10:]
        print("%s: %s" % (category, " ".join(feature_names[top10])))

show_top10(clf, vectorizer, newsgroups_train.target_names)
</code>```

output:

```<code>alt.atheism: islam does religion atheism say just think don people god
comp.graphics: windows does looking program know file image files thanks graphics
sci.space: earth think shuttle orbit moon just launch like nasa space
talk.religion.misc: objective think just bible don christians christian people Jesus god
</code>```

Body:
I have created a Naive Bayes classifier that uses the text of tweets from different politicians to predict their party. I used the sklearn MultinomialNB implementation. Here is my implementation:

Senators_Vectorizer = CountVectorizer(decode_error= 'replace')
senator_counts = Senators_Vectorizer.fit_transform(senator_tweets['text'].values)
senator_targets = senator_tweets['party'].values

senator_counts_train, senator_counts_test, senator_targets_train, senator_targets_test = train_test_split(senator_counts, senator_targets, test_size = .1)

senator_party_clf = MultinomialNB()
senator_party_clf.fit(senator_counts_train, senator_targets_train)

How do I find the words that the Naive Bayes classifier is using to make prediction? Is there a way to find which words have the highest probability of being in Democrats'/Republicans' tweets?

I want the probabilities each word in the Senators_Vectorizer not the probability of a specific tweet being from a specific party.

Body:
Use the feature_log_prob_/coef_ attribute to get the probabilities for each feature.

From Documentation:

feature_log_prob_: ndarray of shape (n_classes, n_features).

  Empirical log probability of features given a class, P(x_i|y).

coef_: ndarray of shape (n_classes, n_features)

  Mirrors feature_log_prob_ for interpreting MultinomialNB as a linear model.

This tutorial would be help I guess.

Quick example to get the top features for each class:

categories = ['alt.atheism', 'talk.religion.misc',
              'comp.graphics', 'sci.space']

newsgroups_train = fetch_20newsgroups(subset='train',
                                     remove=('headers', 'footers', 'quotes'),
                                     categories=categories)
vectorizer = TfidfVectorizer(stop_words='english')
vectors = vectorizer.fit_transform(newsgroups_train.data)
clf = MultinomialNB(alpha=.01).fit(vectors, newsgroups_train.target)

import numpy as np
def show_top10(classifier, vectorizer, categories):
    feature_names = np.asarray(vectorizer.get_feature_names())
    for i, category in enumerate(categories):
        top10 = np.argsort(classifier.coef_[i])[-10:]
        print("%s: %s" % (category, " ".join(feature_names[top10])))

show_top10(clf, vectorizer, newsgroups_train.target_names)

output:

alt.atheism: islam does religion atheism say just think don people god
comp.graphics: windows does looking program know file image files thanks graphics
sci.space: earth think shuttle orbit moon just launch like nasa space
talk.religion.misc: objective think just bible don christians christian people Jesus god


来源: stackexchange

问:
pass an unsigned variable as reference in java for a method implemented in C dll
I have a dll including some methods like this

```<code>f(DWORD a, DWORD b, ulong *c)
</code>```

I have an example of declaring this method in C# as follows

```<code>f(uint a, ref uint b, ref IntPtr c)
</code>```

now I want to implement the same in java. Neither uint nor ref are not supported by java. I added JOOU library to have UInteger but I do not know how to pass it as reference.

答:
Using jna library we can pass IntByReference instead of ref uint. After calling the method we need only to change that to an unsigned value
So in java we have</p>

```<code>f(UINT a, IntByReference int_b, PointerByReference c)
long b = int_b & 0xFFFFFFFFL;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dll including some methods like this

f(DWORD a, DWORD b, ulong *c)

I have an example of declaring this method in C# as follows

f(uint a, ref uint b, ref IntPtr c)

now I want to implement the same in java. Neither uint nor ref are not supported by java. I added JOOU library to have UInteger but I do not know how to pass it as reference.

Body:
Using jna library we can pass IntByReference instead of ref uint. After calling the method we need only to change that to an unsigned value
So in java we have

f(UINT a, IntByReference int_b, PointerByReference c)
long b = int_b & 0xFFFFFFFFL;


问:
Checking for imports order with pylama
I use autoflake to automatically remove unused imports and variables from my code locally and pylama on Jenkins CI to check the code for multiple things, including unused imports and imported variables (W0611).

Now I would like to introduce isort to the project to sort imports.

Is there a way for pylama to check if imports are properly sorted?

答:
I found isort has already pylama plugin. It's implemented in isort repository and mentioned in pylama help output:

```<code>pylama -h
  ...
  --linters LINTERS, -l LINTERS
                        Select linters. (comma-separated). Choices are mccabe,
                        pep257,pydocstyle,pep8,pycodestyle,pyflakes,isort.
</code>```

It's not enabled by default so you need to configure pylama explicitly

```<code>pylama --linters isort file_to_test
</code>```

or in pylama.ini configuration file

```<code>[pylama]
linters = isort
</code>```

(Default linters are pycodestyle, pyflakes, mccabe).

In contrast to check -c it doesn't provide information which lines are incorrectly imported. If something is wrong it always shows same error message:

```<code>file_to_test.py:0: [I] Incorrectly sorted imports. [isort]
</code>```

Title: Checking for imports order with pylama

Body:
I found isort has already pylama plugin. It's implemented in isort repository and mentioned in pylama help output:

pylama -h
  ...
  --linters LINTERS, -l LINTERS
                        Select linters. (comma-separated). Choices are mccabe,
                        pep257,pydocstyle,pep8,pycodestyle,pyflakes,isort.

It's not enabled by default so you need to configure pylama explicitly

pylama --linters isort file_to_test

or in pylama.ini configuration file

[pylama]
linters = isort

(Default linters are pycodestyle, pyflakes, mccabe).

In contrast to check -c it doesn't provide information which lines are incorrectly imported. If something is wrong it always shows same error message:

file_to_test.py:0: [I] Incorrectly sorted imports. [isort]


问:
Why does a % percentage appear at the end of the output to standard out but not when I use endl?
Why is there a trailing % at the end of this output?  I've tried flushing the stream (not endl), however when I end the stream with a call to endl it gets rid of the %.  Any help here would be much appreciated.

```<code>template<class T>
void print_collection(T * t){
        for(int i = 0; i < t->size()-1; ++i){
                cout << t->at(i) << ", ";
        }
        std::cout<< t->at(t->size() -1);
        std::cout<<flush;
}

int main(){
        int n_A = 5;
        int A[] = {2, 3, -2, 34, -29};

        vector<int> vec(A, A + n_A);
        sort(vec.begin(), vec.end());

        print_collection(&vec);
        return 0;
}

OUTPUT
-29, -2, 2, 3, 34%
</code>```

Here is more information about the compiler, I'm using macOS 10.15.4:

```<code>g++ -Wall -std=c++11 array.cpp -o array

g++ Information:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
</code>```

答:
Duplicate question.  Thanks @WBuck!

@Kevin states:
When (non-null) output from a program doesn't include a trailing newline, zsh adds that color-inverted % to indicate that and moves to the next line before printing the prompt; it's generally more convenient than bash's behavior, just starting the command prompt where the output ended.

Getting a weird percent sign in printf output in terminal with C

Body:
Why is there a trailing % at the end of this output?  I've tried flushing the stream (not endl), however when I end the stream with a call to endl it gets rid of the %.  Any help here would be much appreciated.

template<class T>
void print_collection(T * t){
        for(int i = 0; i < t->size()-1; ++i){
                cout << t->at(i) << ", ";
        }
        std::cout<< t->at(t->size() -1);
        std::cout<<flush;
}

int main(){
        int n_A = 5;
        int A[] = {2, 3, -2, 34, -29};

        vector<int> vec(A, A + n_A);
        sort(vec.begin(), vec.end());

        print_collection(&vec);
        return 0;
}

OUTPUT
-29, -2, 2, 3, 34%

Here is more information about the compiler, I'm using macOS 10.15.4:

g++ -Wall -std=c++11 array.cpp -o array

g++ Information:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin


问:
Some basic doubts about AWS DynamoDB 'Keys'
I've seen these terms everywhere -

Primary Key

Sort Key

Partition Key

Secondary Key

But I seem to get confused with the names :

Are the Partition Key and Primary Key the same thing? What are they?

Does the same go with Sort Key and Secondary Index? What role would secondary key play if I add it?

Also, at the time of creating creating a DynamoDB table, I added 'Order ID' as the Primary Key - now, I need to replace it with 'User ID', and make 'Order ID' as the secondary key.

So, Order ID would be the 'Secondary Key', and User ID would be the 'Primary Key'
How can this be achieved?

Any help is appreciated! :) Thanks!

答:
Are the Partition Key and Primary Key the same thing? What are they?

No.

A Primary Key is what uniquely identifies each item in the table.

A Partition Key is one possible kind of Primary Key, the other being Partition Key + Sort Key (i.e., a "composite" primary key, as you'd call it in other DB systems).

Does the same go with Sort Key and Secondary Index? What role would secondary key play if I add it?

Sort key and Secondary Index are also different things.

A Sort Key can be used as a "second element" in a "composite key" in a Primary Key. In other words, a Primary Key can be of type "Partition Key" or "Partition Key + Sort Keu".

A Secondary Index is something else entirely. A secondary index allows you to perform different kinds of optimized queries on your table. It needs to know how you want to partition and sort your items: for a Local Secondary Index, you only specify a Sort Key since it will implicitly use the same Partition Key as the Primary Key. For a Global Secondary Index, you must specify a Partition Key and you can, optionally, specify a Sort Key (so in a sense a GSI is defined in a similar way to a Primary Key).

Take a look at this: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html

It explains all that with a lot of examples.

at the time of creating creating a DynamoDB table, I added 'Order ID' as the Primary Key - now, I need to replace it with 'User ID', and make 'Order ID' as the secondary key.

You can't do it.

It's not possible to change the Primary Key of a DynamoDB table.

Here's the relevant docs: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateTable.html

I've seen these terms everywhere - [...]

As a final comment, just be aware that you may also see a few other terms, too. In the old days, DynamoDB used different terms for "Partition Key" and "Sort Key". They used to be called, respectively, "Hash Key" and "Range Key". You'll probably see a lot of reference to those names in SDKs, CLI parameters, etc.


问:
Need to grep file with specific extension and move to another folder
I want to write a bash command that greps all *.txt file with a pattern in current folder to another folder. Should I use find or for loop? I tried using find but it seems to complicate things.

Edit: I want to copy files with a specific pattern to a different folder. For example:

```<code>A.txt
B.txt
C.txt
</code>```

all have the word "foo" in them. I want grep to remove "foo" and send it to a different folder with the same name. I don't want to change the original file in any way.

答:
Using for would probably be a lot easier for this than find. Something like this:

```<code>otherdir='your_other_directory'
for file in *.txt; do
    grep -q 'foo' $file && grep -v 'foo' < $file > $otherdir/$file
done
</code>```

If your grep doesn't understand -q then:

```<code>otherdir='your_other_directory'
for file in *.txt; do
    grep 'foo' $file > /dev/null && grep -v 'foo' < $file > $otherdir/$file
done
</code>```

In any case, grep returns a true value to the shell if it finds a match and the X && Y construct executes the Y command if X returns a true value.

UPDATE: The above solution assumes (as noted by Johnsyweb) that you want to remove any lines that contain "foo". If you just want to remove "foo" without removing whole lines, then sed is your friend:

```<code>otherdir='your_other_directory'
for file in *.txt; do
    grep -q 'foo' $file && sed 's/foo//g' < $file > $otherdir/$file
done
</code>```

Or:

```<code>otherdir='your_other_directory'
for file in *.txt; do
    grep 'foo' $file > /dev/null && sed 's/foo//g' < $file > $otherdir/$file
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to write a bash command that greps all *.txt file with a pattern in current folder to another folder. Should I use find or for loop? I tried using find but it seems to complicate things.

Edit: I want to copy files with a specific pattern to a different folder. For example:

A.txt
B.txt
C.txt

all have the word "foo" in them. I want grep to remove "foo" and send it to a different folder with the same name. I don't want to change the original file in any way.

Body:
Using for would probably be a lot easier for this than find. Something like this:

otherdir='your_other_directory'
for file in *.txt; do
    grep -q 'foo' $file && grep -v 'foo' < $file > $otherdir/$file
done

If your grep doesn't understand -q then:

otherdir='your_other_directory'
for file in *.txt; do
    grep 'foo' $file > /dev/null && grep -v 'foo' < $file > $otherdir/$file
done

In any case, grep returns a true value to the shell if it finds a match and the X && Y construct executes the Y command if X returns a true value.

UPDATE: The above solution assumes (as noted by Johnsyweb) that you want to remove any lines that contain "foo". If you just want to remove "foo" without removing whole lines, then sed is your friend:

otherdir='your_other_directory'
for file in *.txt; do
    grep -q 'foo' $file && sed 's/foo//g' < $file > $otherdir/$file
done

Or:

otherdir='your_other_directory'
for file in *.txt; do
    grep 'foo' $file > /dev/null && sed 's/foo//g' < $file > $otherdir/$file
done


问:
Can programs be written that can quit from Chrome browser?
If I visit a site, I want to close the Chrome Web Browser. Is it possible to write such a program?</p>

答:
Under normal operation, this should not be possible. However, there have been cases where browsers have had well known bugs that could be exploited. To be clear though, I'm referring to crashing the browser. There is no supported API or method of asking the browser to close.

For instance, a simple line of CSS could crash Internet Explorer 6. Something like this on Chrome would probably not work anyways, since Chrome runs each tab in its own process.

There is a way to close a browser window (tab) via script if your script opened the window, simply by calling window.close() (where window is the child window). Please see https://developer.mozilla.org/en-US/docs/Web/API/Window/close for more information.


问:
Not able to get response with @Controller, while @RestController works fine
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
```

<p>The above code returns a 404 when I try to access <code>localhost:8080/function/hash</code>.</p>

<p>I also tried</p>

<pre class="lang-java prettyprint-override"><code>@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

答:
Return "/html/hashcode.html"(prefix /),
and create <project-root>/src/main/resources/static/html/hashcode.html

```<code>@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(final Model m) {
        return "/html/hashcode.html";
    }
}
</code>```

When return "html/hashcode.html":

```<code>o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/function/html/hashcode.html", parameters={}
</code>```

On the other hand, when return "/html/hashcode.html":

```<code>o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/html/hashcode.html", parameters={}
</code>```

Body:
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

The above code returns a 404 when I try to access localhost:8080/function/hash.

I also tried

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

Body:
Return "/html/hashcode.html"(prefix /),
and create <project-root>/src/main/resources/static/html/hashcode.html

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(final Model m) {
        return "/html/hashcode.html";
    }
}

When return "html/hashcode.html":

o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/function/html/hashcode.html", parameters={}

On the other hand, when return "/html/hashcode.html":

o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/html/hashcode.html", parameters={}


问:
2 Tables 1 Result, a tricky SQL
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

```<code>CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)
</code>```

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")
</code>```

which works well as long as I only query by one ROLE.

To query for more than one role, I do

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")
</code>```

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")
</code>```

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post

答:
You could use two exists  subqueries, one for each role:

```<code>select u.*
from users u
where
    exists (
        select 1
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = r.uname
            and r.agr_name = 'ZTEST_ROLE'
    )
    and exists (
        select 1
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = u.bname
            and r.agr_name = 'ZTEST_ROLE2'
    )
</code>```

Also it seems quite convoluted, it should be an efficient option, especially if you have an index on roles(sysid, mandt, uname, agr_name).

Another solution is to filter with an aggregate query:

```<code>select u.*
from users u
where
    exists (
        select count(*)
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = r.uname
            and r.agr_name in ('ZTEST_ROLE', 'ZTEST_ROLE2')
    )  = 2
</code>```

The upside of the second approach is that it is easier to extend to check for more roles at once: you just need to expand the list on the right side of the in operator, and accordingly increment the target count.

Title: 2 Tables 1 Result, a tricky SQL

Body:
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")

which works well as long as I only query by one ROLE.

To query for more than one role, I do

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post

Body:
You could use two exists  subqueries, one for each role:

select u.*
from users u
where
    exists (
        select 1
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = r.uname
            and r.agr_name = 'ZTEST_ROLE'
    )
    and exists (
        select 1
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = u.bname
            and r.agr_name = 'ZTEST_ROLE2'
    )

Also it seems quite convoluted, it should be an efficient option, especially if you have an index on roles(sysid, mandt, uname, agr_name).

Another solution is to filter with an aggregate query:

select u.*
from users u
where
    exists (
        select count(*)
        from roles r
        where
            r.ysid = u.sysid
            and r.mandt = u.mandt
            and r.uname = r.uname
            and r.agr_name in ('ZTEST_ROLE', 'ZTEST_ROLE2')
    )  = 2

The upside of the second approach is that it is easier to extend to check for more roles at once: you just need to expand the list on the right side of the in operator, and accordingly increment the target count.


问:
Unable to Connecting to Amazon instance EC2
I'm Using AWS - Amazon Web Services and running commands from MAC Terminal

http://ec2-52-xx-x-xx.us-west-2.compute.amazonaws.com

But I am getting this error :

Gateway Timeout: can't connect to remote host

I'm unable to access the site anymore because of this error
there is a security group applied to this instance
and port 22 for ssh is listed under this security group

答:
```<code>To connect using the SSH, ssh should be installed correctly on your machine

just type **"SSH"** if something like this comes up that means your machine has ssh

*usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-E log_file] [-e escape_char]
           [-F configfile] [-I pkcs11] [-i identity_file]
           [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
           [user@]hostname [command]*

Mostly **Linux and macOS X** have already installed if not then go to the
[here][1]

For **Windows Server** 2019 and Windows 10 [Openssh in Windows][2]

The first check is there any problem with your ssh is allowed from the security group of that particular instance

like is it allowing to connect from ssh or not

once that is confirmed you have to enter the correct syntax to connect the AWS instance

Using Public DNS that is available under the running instance

**ssh -i /path/my-key-pair.pem my-instance-user-name@my-instance-public-dns-name**

Using ipv6 similarly, ipv4 can be done

**ssh -i /path/my-key-pair.pem my-instance-user-name@my-instance-IPv6-address**

in place of **my-instance-user-name** you can through documentation provided by AWs[1]

  [1]: http://www.openssh.com
  [2]: https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_overview
</code>```


问:
set image wallpaper to fit screen "
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code</p>

```<code>item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});
</code>```

答:
The bitmap that are you setting with wallpaperManager may not same as the Display size so, you need to scale that bitmap before passing to wallpaperManager

Try With

```<code>item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        int height = getResources().getDisplayMetrics().heightPixels;
                        int width = getResources().getDisplayMetrics().widthPixels;
                        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});
</code>```

Title: set image wallpaper to fit screen "

Body:
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code

item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});

Body:
The bitmap that are you setting with wallpaperManager may not same as the Display size so, you need to scale that bitmap before passing to wallpaperManager

Try With

item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        int height = getResources().getDisplayMetrics().heightPixels;
                        int width = getResources().getDisplayMetrics().widthPixels;
                        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});


问:
UITextField Programmatically won't convert into string or take any binary operators Xcode
Prior to having this issue, I was using storyboards and outlets for text fields. However, I found it easier to work on my app programmatically.  Unfortunately, as I began to convert my app such as by programmatically making a text field I ran into some issues as I still have some functions such as my login function that was made for the text fields from the storyboards.  I'm still new swift so any solutions would be helpful.

I declared my email text field as such:

```<code>    var emailTxt: UITextField!
</code>```

The other aspects of the email text field are as such in the view did load function:

```<code>    emailTxt = UITextField(frame: CGRect(x: 77.0, y: 306.0, width: 262, height: 34))
    emailTxt.backgroundColor = .white
    emailTxt.borderStyle = .roundedRect
    emailTxt.keyboardAppearance = .light
    emailTxt.keyboardType = .emailAddress
    emailTxt.placeholder = "Email"
    emailTxt.font = UIFont.systemFont(ofSize: 14.0)
    emailTxt.textColor = .systemGreen
    emailTxt.tintColor = .systemGreen
    emailTxt.delegate = self

    self.view.addSubview(emailTxt)
</code>```

Text field functions outside the view did load:

```<code>func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
}
</code>```

Finally the area where I get the issues.

First, it says that for the guard statement there must be an else statement.

Then it says (Binary operator '!=' cannot be applied to operands of type 'UITextField?' and 'String') Then in the else statement it says (Closure expression is unused)

Finally, in the auth statement it gives the error: Cannot convert value of type 'UITextField' to expected argument type 'String' while underlining the email

Here is the code for that:

```<code>    guard let email = emailTxt
    email != "",
    let password = passwordTxt
    password != ""
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return

    }

    Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
        guard error == nil else {
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
</code>```

答:
You are missing the .text property.

```<code>guard let email = emailTxt.text, !email.isEmpty else {
    // show alert
    return
}
</code>```

As of iOS 10, it can also simply be written as:

```<code>guard emailTxt.hasText else {
    // show alert
    return
}
</code>```

Credit to @LeoDabus for pointing that out

Body:
Prior to having this issue, I was using storyboards and outlets for text fields. However, I found it easier to work on my app programmatically.  Unfortunately, as I began to convert my app such as by programmatically making a text field I ran into some issues as I still have some functions such as my login function that was made for the text fields from the storyboards.  I'm still new swift so any solutions would be helpful.

I declared my email text field as such:

    var emailTxt: UITextField!

The other aspects of the email text field are as such in the view did load function:

    emailTxt = UITextField(frame: CGRect(x: 77.0, y: 306.0, width: 262, height: 34))
    emailTxt.backgroundColor = .white
    emailTxt.borderStyle = .roundedRect
    emailTxt.keyboardAppearance = .light
    emailTxt.keyboardType = .emailAddress
    emailTxt.placeholder = "Email"
    emailTxt.font = UIFont.systemFont(ofSize: 14.0)
    emailTxt.textColor = .systemGreen
    emailTxt.tintColor = .systemGreen
    emailTxt.delegate = self

    self.view.addSubview(emailTxt)

Text field functions outside the view did load:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
}

Finally the area where I get the issues.

First, it says that for the guard statement there must be an else statement.

Then it says (Binary operator '!=' cannot be applied to operands of type 'UITextField?' and 'String') Then in the else statement it says (Closure expression is unused)

Finally, in the auth statement it gives the error: Cannot convert value of type 'UITextField' to expected argument type 'String' while underlining the email

Here is the code for that:

    guard let email = emailTxt
    email != "",
    let password = passwordTxt
    password != ""
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return

    }

    Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
        guard error == nil else {
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }

Body:
You are missing the .text property.

guard let email = emailTxt.text, !email.isEmpty else {
    // show alert
    return
}

As of iOS 10, it can also simply be written as:

guard emailTxt.hasText else {
    // show alert
    return
}

Credit to @LeoDabus for pointing that out


问:
Recursive function Error getting text from an element
im trying to do a recursive function like this:

```<code>function recurse(index, items) {
    if(index<items.length) {
        items[index].getText().then(function(itemtext) {
            items[index].click().then(function() {
                browser.params.utils.waitForElement('disappear', browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER, waitLongTime, 'present').then(function() {
                    element.all(by.className('ui-grid-cell ng-scope ui-grid-disable-selection ui-grid-coluiGrid-00YV darkness-cell-row')).then(function(itemtotext) {
                        itemtotext[0].getText().then(function(text) {
                            expect(itemtext).toBe(text);
                            browser.element(by.className('glyphicon glyphicon-remove')).click().then(function() {
                                browser.params.utils.waitForElement('disappear', browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER, waitLongTime, 'present');
                            });
                        });
                    });
                });
            });
        });
        recurse(index+1,items);
    } else {

    }
}
</code>```

I got the error in the second getText(): Cannot read property 'getText' of undefined so i don't know why I got this error.

Thank you all in advance.

答:
Remove the unnecessary nested then() to make code more readable.
Recommend to use await/async

```<code>function resurse(index, items) {
  class_name = 'ui-grid-cell ng-scope ui-grid-disable-selection ' +
               'ui-grid-coluiGrid-00YV darkness-cell-row';

  if (index < items.length) {
    itemtext = items[index].getText();
    items[index].click();
    browser.params.utils.waitForElement(
      'disappear',
      browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER,
      waitLongTime,
      'present'
    );
    itemtotext = element.all(by.className(class_name)).first().getText();

    promise.all([itemtext, itemtotext]).then(function(values){
      expct(values[0]).toEqual(values[1])
    });

    element(by.className('glyphicon glyphicon-remove')).click();

    browser.params.utils.waitForElement(
      'disappear',
      browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER,
      waitLongTime, 'present'
    );

    browser.getTitle().then(function(){
       recurse(index + 1, items);
    });

  }
}
</code>```

Body:
im trying to do a recursive function like this:

function recurse(index, items) {
    if(index<items.length) {
        items[index].getText().then(function(itemtext) {
            items[index].click().then(function() {
                browser.params.utils.waitForElement('disappear', browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER, waitLongTime, 'present').then(function() {
                    element.all(by.className('ui-grid-cell ng-scope ui-grid-disable-selection ui-grid-coluiGrid-00YV darkness-cell-row')).then(function(itemtotext) {
                        itemtotext[0].getText().then(function(text) {
                            expect(itemtext).toBe(text);
                            browser.element(by.className('glyphicon glyphicon-remove')).click().then(function() {
                                browser.params.utils.waitForElement('disappear', browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER, waitLongTime, 'present');
                            });
                        });
                    });
                });
            });
        });
        recurse(index+1,items);
    } else {

    }
}

I got the error in the second getText(): Cannot read property 'getText' of undefined so i don't know why I got this error.

Thank you all in advance.

Body:
Remove the unnecessary nested then() to make code more readable.
Recommend to use await/async

function resurse(index, items) {
  class_name = 'ui-grid-cell ng-scope ui-grid-disable-selection ' +
               'ui-grid-coluiGrid-00YV darkness-cell-row';

  if (index < items.length) {
    itemtext = items[index].getText();
    items[index].click();
    browser.params.utils.waitForElement(
      'disappear',
      browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER,
      waitLongTime,
      'present'
    );
    itemtotext = element.all(by.className(class_name)).first().getText();

    promise.all([itemtext, itemtotext]).then(function(values){
      expct(values[0]).toEqual(values[1])
    });

    element(by.className('glyphicon glyphicon-remove')).click();

    browser.params.utils.waitForElement(
      'disappear',
      browser.params.constants.GENERALPATHS.ALERTS_AND_COLLISIONS.SPINNER,
      waitLongTime, 'present'
    );

    browser.getTitle().then(function(){
       recurse(index + 1, items);
    });

  }
}


问:
java.io.IOException: Server returned HTTP response code: 406 for URL

java.io.IOException: Server returned HTTP response code: 406 for URL:
  https://aa09616289afe6a25ea1f7f6fbf12073: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@mfaisal1521.myshopify.com/admin/api/2020-04/products.json
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at
  sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1045)   at
  javaapplication9.Send_HTTP_Request2.call_me(Send_HTTP_Request2.java:33)
    at
  javaapplication9.Send_HTTP_Request2.main(Send_HTTP_Request2.java:21)

myCode:

```<code>URL url = new URL("https://aa09616289afe6a25ea1f7f6fbf12073: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@mfaisal1521.myshopify.com/admin/api/2020-04/products.json");

BufferedReader read = new BufferedReader(
    new InputStreamReader(url.openStream()));
    String i;
    while ((i = read.readLine()) != null)
        System.out.println(i);
    read.close();
</code>```

答:
I Done this by using restfull API. Thanks Rahkumar

OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
  .url("https://mfaisal1521.myshopify.com/admin/api/2020-04/products/4517591449687.json")
  .method("GET", null)
  .addHeader("Authorization", "Basic YWEwOTYxNjI4OWFmZTZhMjVlYTFmN2Y2ZmJmMTIwNzM6c2hwcGFfZjVmZDQ3YTY1M2Q0OWQ2NmU4ODY0MzY1NzhjNTQxODc=").build();

Response response = client.newCall(request).execute();

Body:
java.io.IOException: Server returned HTTP response code: 406 for URL:
  https://aa09616289afe6a25ea1f7f6fbf12073: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@mfaisal1521.myshopify.com/admin/api/2020-04/products.json
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at
  sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1045)   at
  javaapplication9.Send_HTTP_Request2.call_me(Send_HTTP_Request2.java:33)
    at
  javaapplication9.Send_HTTP_Request2.main(Send_HTTP_Request2.java:21)

myCode:

URL url = new URL("https://aa09616289afe6a25ea1f7f6fbf12073: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@mfaisal1521.myshopify.com/admin/api/2020-04/products.json");

BufferedReader read = new BufferedReader(
    new InputStreamReader(url.openStream()));
    String i;
    while ((i = read.readLine()) != null)
        System.out.println(i);
    read.close();


问:
Flutter: How to sort ListView (data from Json) in decreasing order or alphabetically?
This is JSON file

```<code>[
  {
    "id": 1,
    "country": "United States",
    "population": 328200000
  },
  {
    "id": 2,
    "country": "Germany",
    "population": 83020000
  },
  {
    "id": 3,
    "country": "United Kingdom",
    "population": 66650000
  }
]
</code>```

I want that after press the RaisedButton, it will sort in order ('Country Name' => decrease; 'Country Population' => alphabetically) (image preview). How to do that ?

This is main file:

```<code>import 'dart:convert';
import 'dart:core';
import 'package:ask/country.dart';
import 'package:ask/country_service.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Country> _country = [];

  @override
  void initState() {
    CountryServices.getCountry().then((value) {
      setState(() {
        _country = value;
      });
    });
    super.initState();
  }

  Widget build(BuildContext context) {
    return new MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: Text('Country')),
            body: Container(
                child: Column(children: <Widget>[
                  Row(children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: RaisedButton(
                            child: Text('Country Name'),
                            onPressed: () {}, // Sort alphabetically
                          )),
                      Expanded(
                          flex: 1,
                          child: RaisedButton(
                            child: Text('Country Population'),
                            onPressed: () {}, // Sort in decreasing order
                          ))]),
                   Container(
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemCount: _country.length,
                        itemBuilder: (context, index) {
                          return _listCountry(index);
                        }))
            ]))));
  }

  _listCountry(index) {
    Country country = _country[index];
    return Row(
      children: <Widget>[
        Expanded(
            flex: 1,
            child: Text(
              country.country,
              textAlign: TextAlign.center,
            )),
        Expanded(
            flex: 1,
            child: Text('${country.population}', textAlign: TextAlign.center)),
      ],
    );
  }
}

</code>```

答:
This official document will provide information on how to sort.

Try out the following.

```<code>CountryServices.getCountry().then((value) {

    setState(() {
        _country = value;
        _country.sort((a, b) => a.population.compareTo(b.population));
    });
});
</code>```

Note : The above code is untested. You might need to tweak a bit.

Body:
This is JSON file

[
  {
    "id": 1,
    "country": "United States",
    "population": 328200000
  },
  {
    "id": 2,
    "country": "Germany",
    "population": 83020000
  },
  {
    "id": 3,
    "country": "United Kingdom",
    "population": 66650000
  }
]

I want that after press the RaisedButton, it will sort in order ('Country Name' => decrease; 'Country Population' => alphabetically) (image preview). How to do that ?

This is main file:

import 'dart:convert';
import 'dart:core';
import 'package:ask/country.dart';
import 'package:ask/country_service.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Country> _country = [];

  @override
  void initState() {
    CountryServices.getCountry().then((value) {
      setState(() {
        _country = value;
      });
    });
    super.initState();
  }

  Widget build(BuildContext context) {
    return new MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: Text('Country')),
            body: Container(
                child: Column(children: <Widget>[
                  Row(children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: RaisedButton(
                            child: Text('Country Name'),
                            onPressed: () {}, // Sort alphabetically
                          )),
                      Expanded(
                          flex: 1,
                          child: RaisedButton(
                            child: Text('Country Population'),
                            onPressed: () {}, // Sort in decreasing order
                          ))]),
                   Container(
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemCount: _country.length,
                        itemBuilder: (context, index) {
                          return _listCountry(index);
                        }))
            ]))));
  }

  _listCountry(index) {
    Country country = _country[index];
    return Row(
      children: <Widget>[
        Expanded(
            flex: 1,
            child: Text(
              country.country,
              textAlign: TextAlign.center,
            )),
        Expanded(
            flex: 1,
            child: Text('${country.population}', textAlign: TextAlign.center)),
      ],
    );
  }
}

Body:
This official document will provide information on how to sort.

Try out the following.

CountryServices.getCountry().then((value) {

    setState(() {
        _country = value;
        _country.sort((a, b) => a.population.compareTo(b.population));
    });
});

Note : The above code is untested. You might need to tweak a bit.


问:
MappedListIterable is not a SubType
I'm new to flutter and dart and trying to fetch data from firestore as a stream and feed to my ListView but I keep getting this error:

```<code>type 'MappedListIterable<DocumentSnapshot, Product>' is not a subtype
of type 'List<Product>'
</code>```

I have seen a couple of other posts on stackoverflow like this but they either do not help me or do not apply to my situation.

This is my products page widget:

```<code>import 'package:xxx/models/Product.dart';
import 'package:agrogator/screens/products/widgets/products_list.dart';
import 'package:xxx/services/product.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsScreen extends StatelessWidget {
  ProductsScreen({Key key}) : super(key: key);

  final product = ProductService();

  // This widget is the productsucts page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  @override
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return StreamProvider<List<Product>>.value(
      value: product.streamProducts(),
      child: new Scaffold(
        appBar: new AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: new Text("xxx"),
        ),
        body: new ProductsList(),
        floatingActionButton: new FloatingActionButton(
          onPressed: () {},
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}
</code>```

This is my ProductsList widget:

```<code>import 'package:xxx/models/Product.dart';
import 'package:xxx/screens/products/widgets/product_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var products = Provider.of<List<Product>>(context);

    return Container(
      height: 100,
      child: ListView(
        children: products.map((product) {
          return new ProductItem(product: product);
        }).toList(),
      ),
    );
  }
}
</code>```

This is my ProductItem widget:

```<code>import 'package:xxx/models/Product.dart';
import 'package:flutter/material.dart';

class ProductItem extends StatelessWidget {
  final Product product;

  ProductItem({this.product});

  @override
  Widget build(BuildContext context) {
    return Text(product.name, style: TextStyle(color: Colors.black));
  }
}
</code>```

This is my Product Model:

```<code>import 'package:cloud_firestore/cloud_firestore.dart';

class Product {
  String uid;
  String name;
  String unit;
  int avgQuantity;
  double avgWeight;
  double previousAvgPrice;
  double currentAvgPrice;
  String lastUpdatedBy;
  String lastUpdatedAt;
  String remarks;

  Product(
      {this.uid,
      this.name,
      this.unit,
      this.avgQuantity,
      this.avgWeight,
      this.previousAvgPrice,
      this.currentAvgPrice,
      this.lastUpdatedBy,
      this.lastUpdatedAt,
      this.remarks});

  factory Product.fromFirestore(DocumentSnapshot doc) {
    Map data = doc.data;

    return Product(
        uid: doc.documentID,
        name: data["name"],
        unit: data["unit"],
        avgQuantity: data["avgQuantity"],
        avgWeight: data["avgWeight"],
        previousAvgPrice: data["previousAvgPrice"],
        currentAvgPrice: data["ccurrentAvgPrice"],
        lastUpdatedBy: data["lastUpdatedBy"],
        lastUpdatedAt: data["lastUpdatedAt"],
        remarks: data["remarks"]);
  }
}
</code>```

And my service:

```<code>import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
  final Firestore _db = Firestore.instance;

  Stream<List<Product>> streamProducts() {
    var ref = _db.collection("products");

    return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc)));
  }
}
</code>```

答:
In your Service add .toList()

Like this below

```<code>import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
    final Firestore _db = Firestore.instance;

    Stream<List<Product>> streamProducts() {
        var ref = _db.collection("products");

        return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc))).toList(); // <= here
   }
}
</code>```

Title: MappedListIterable is not a SubType

Body:
I'm new to flutter and dart and trying to fetch data from firestore as a stream and feed to my ListView but I keep getting this error:

type 'MappedListIterable<DocumentSnapshot, Product>' is not a subtype
of type 'List<Product>'

I have seen a couple of other posts on stackoverflow like this but they either do not help me or do not apply to my situation.

This is my products page widget:

import 'package:xxx/models/Product.dart';
import 'package:agrogator/screens/products/widgets/products_list.dart';
import 'package:xxx/services/product.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsScreen extends StatelessWidget {
  ProductsScreen({Key key}) : super(key: key);

  final product = ProductService();

  // This widget is the productsucts page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  @override
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return StreamProvider<List<Product>>.value(
      value: product.streamProducts(),
      child: new Scaffold(
        appBar: new AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: new Text("xxx"),
        ),
        body: new ProductsList(),
        floatingActionButton: new FloatingActionButton(
          onPressed: () {},
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}

This is my ProductsList widget:

import 'package:xxx/models/Product.dart';
import 'package:xxx/screens/products/widgets/product_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var products = Provider.of<List<Product>>(context);

    return Container(
      height: 100,
      child: ListView(
        children: products.map((product) {
          return new ProductItem(product: product);
        }).toList(),
      ),
    );
  }
}

This is my ProductItem widget:

import 'package:xxx/models/Product.dart';
import 'package:flutter/material.dart';

class ProductItem extends StatelessWidget {
  final Product product;

  ProductItem({this.product});

  @override
  Widget build(BuildContext context) {
    return Text(product.name, style: TextStyle(color: Colors.black));
  }
}

This is my Product Model:

import 'package:cloud_firestore/cloud_firestore.dart';

class Product {
  String uid;
  String name;
  String unit;
  int avgQuantity;
  double avgWeight;
  double previousAvgPrice;
  double currentAvgPrice;
  String lastUpdatedBy;
  String lastUpdatedAt;
  String remarks;

  Product(
      {this.uid,
      this.name,
      this.unit,
      this.avgQuantity,
      this.avgWeight,
      this.previousAvgPrice,
      this.currentAvgPrice,
      this.lastUpdatedBy,
      this.lastUpdatedAt,
      this.remarks});

  factory Product.fromFirestore(DocumentSnapshot doc) {
    Map data = doc.data;

    return Product(
        uid: doc.documentID,
        name: data["name"],
        unit: data["unit"],
        avgQuantity: data["avgQuantity"],
        avgWeight: data["avgWeight"],
        previousAvgPrice: data["previousAvgPrice"],
        currentAvgPrice: data["ccurrentAvgPrice"],
        lastUpdatedBy: data["lastUpdatedBy"],
        lastUpdatedAt: data["lastUpdatedAt"],
        remarks: data["remarks"]);
  }
}

And my service:

import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
  final Firestore _db = Firestore.instance;

  Stream<List<Product>> streamProducts() {
    var ref = _db.collection("products");

    return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc)));
  }
}

Body:
In your Service add .toList()

Like this below

import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
    final Firestore _db = Firestore.instance;

    Stream<List<Product>> streamProducts() {
        var ref = _db.collection("products");

        return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc))).toList(); // <= here
   }
}


问:
How to get arbitrary alignment of array in VS2019?
This code does not give the correct alignment:

```<code>alignas(4096) int* p = new int[1024];
printf(“%x”, p);
</code>```

This should print

```<code>0x......000
</code>```

with three zeros at the end. I can’t get it to work. Is this even possible?

答:
Your current code is aligning the pointer int* to be aligned to a 4096 byte boundary. What you want to do is align the memory allocated by new to be aligned to the boundary.

The only standard way to do this is with C++17 or above, using either operator new with the std::aligned_val_t argument, or std::aligned_alloc. E.g:

int* p = new(std::align_val_t{4096}) int[1024];
...
delete [] p;

// or a more C-style way
int* p = static_cast<int*>(std::aligned_alloc(4096, sizeof(int)*1024));
...
std::free(p);
```

Here's a working example using GCC on compiler explorer; and the same example failing with MSVC is here.

If you aren't using C++17, you will be required to use OS-specific alignment-allocating functions, such as posix_memalign for POSIX-compliant operating systems, or _aligned_malloc on Windows.

Alternatively, if your system has C11 headers installed, you can make use of the C-standard aligned_alloc defined in <stdlib.h>. This is the same as the std::aligned_alloc equivalent, except the std:: namespace qualified one is only guaranteed to be made available with C++17 or above.

Edit: It seems that MSVC does not allow the first-form using operator new due to what they perceive to be an ambiguity in the standard (see the comment section here for more detail). If you are working with MSVC, or are looking for the most portable code -- you should make use std::aligned_alloc instead.

Body:
This code does not give the correct alignment:

alignas(4096) int* p = new int[1024];
printf(“%x”, p);

This should print

0x......000

with three zeros at the end. I can’t get it to work. Is this even possible?

Body:
Your current code is aligning the pointer int* to be aligned to a 4096 byte boundary. What you want to do is align the memory allocated by new to be aligned to the boundary.

The only standard way to do this is with C++17 or above, using either operator new with the std::aligned_val_t argument, or std::aligned_alloc. E.g:

int* p = new(std::align_val_t{4096}) int[1024];
...
delete [] p;

// or a more C-style way
int* p = static_cast<int*>(std::aligned_alloc(4096, sizeof(int)*1024));
...
std::free(p);

Here's a working example using GCC on compiler explorer; and the same example failing with MSVC is here.

If you aren't using C++17, you will be required to use OS-specific alignment-allocating functions, such as posix_memalign for POSIX-compliant operating systems, or _aligned_malloc on Windows.

Alternatively, if your system has C11 headers installed, you can make use of the C-standard aligned_alloc defined in <stdlib.h>. This is the same as the std::aligned_alloc equivalent, except the std:: namespace qualified one is only guaranteed to be made available with C++17 or above.

Edit: It seems that MSVC does not allow the first-form using operator new due to what they perceive to be an ambiguity in the standard (see the comment section here for more detail). If you are working with MSVC, or are looking for the most portable code -- you should make use std::aligned_alloc instead.


问:
How to improve the behavior of ConnectionRequest?
I wrote this code:

```<code>public static Slider downloadStorageFile(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) {

        final String filename = getNewStorageFilename();

        ConnectionRequest cr = Rest.get(url).fetchAsBytes(response -> CN.callSerially(() -> filesavedCallback.completed(filename)));
        cr.setDestinationStorage(filename);

        Slider slider = new Slider();
        slider.addDataChangedListener((int type, int index) -> {
            CN.callSerially(() -> percentageCallback.completed(slider.getProgress()));
        });
        sliderBridgeMap.put(cr, slider);
        SliderBridge.bindProgress(cr, slider);

        return slider;
    }
</code>```

Basically, as you can guess, it asynchronously downloads a file, it offers two callbacks that will run on the EDT and it immediately returns a Slider that keep track of the download progress.

On Android, the download continues and ends even when the app is in background. On iOS, on the other hand, the app must remain active and foregrounded at all time.

Is it possible to complete the download even on iOS when the app goes to the background?

Alternatively, can I get ConnectionRequest.retry(), which is automatically invoked by my network error handler when the app returns to foreground on iOS, to restart where the download arrived at, rather than restart it from scratch?

Even better, can I get both points 1 and 2?

答:
This is problematic on Android too as the OS may suddenly kill your ongoing download when the system is constrained. E.g. in the developer tools just turn on the kill activities immediately and see your download die the moment you minimize the app.

Most devices don't do that but if a device is running in battery saving mode that might happen.

The solution is to use background fetch when going into the background. The problem is that this doesn't provide the nice sort of UI you would get with the regular foreground download so you need to pick and choose which one to use.

See the JavaDoc for the class here: https://www.codenameone.com/javadoc/com/codename1/background/BackgroundFetch.html

And the slightly out of date blog post on the subject: https://www.codenameone.com/blog/background-fetch.html

Body:
I wrote this code:

public static Slider downloadStorageFile(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) {

        final String filename = getNewStorageFilename();

        ConnectionRequest cr = Rest.get(url).fetchAsBytes(response -> CN.callSerially(() -> filesavedCallback.completed(filename)));
        cr.setDestinationStorage(filename);

        Slider slider = new Slider();
        slider.addDataChangedListener((int type, int index) -> {
            CN.callSerially(() -> percentageCallback.completed(slider.getProgress()));
        });
        sliderBridgeMap.put(cr, slider);
        SliderBridge.bindProgress(cr, slider);

        return slider;
    }

Basically, as you can guess, it asynchronously downloads a file, it offers two callbacks that will run on the EDT and it immediately returns a Slider that keep track of the download progress.

On Android, the download continues and ends even when the app is in background. On iOS, on the other hand, the app must remain active and foregrounded at all time.

Is it possible to complete the download even on iOS when the app goes to the background?

Alternatively, can I get ConnectionRequest.retry(), which is automatically invoked by my network error handler when the app returns to foreground on iOS, to restart where the download arrived at, rather than restart it from scratch?

Even better, can I get both points 1 and 2?


问:
Is it possible to detect Android app uninstall?
My app is using Google's C2DM (push notification) to notify users about new activity from friends. Once they install the app I register the device with C2DM servers and store user's phone number. So I know that the user is using my app and I can send him/her the push notifications. But what happens if users uninstalls my app, is there a way to catch it in my app? Or the only way is to catch an error on my server when I send a C2DM and it's unreachable, then mark a user as inactive?

I would love to notify users when their friends are using an app and when they no longer do.

What's is the best solution for this scenario?

答:
Unfortunately the ACTION_PACKAGE_REMOVED intent will be sent out to all receivers except for your own. This is confirmed here.

Some questions for your C2DM plan, since I'm not very familiar with it. If the user just leaves their device off for a long period of time, will that trigger the error condition you use? How does C2DM actually report an "unreachable" device? Is that a condition that only occurs when it attempts to send the push notification and fails or is it when it somehow determines it reaches the device but fails to be handled properly? Obviously in the second scenario your plan would work, but I can see some "false positives" occurring otherwise.

Older SO question for reference: android not receiving Intent ACTION_PACKAGE_REMOVED in the removed package


问:
Subtract months from year in Python
implement function subtract_months to subtract n number of months from a given year and month.

Inputs: Is a list of tuples [(year1, month1, months_to_subtract1), (year2, month2, months_to_subtract2), ...]
where, year is a 4 digit integer
month is an integer value between 1 to 12, 1=January, 2=February, ... 12=December) and
months_to_subtract is an integer

Output: Is a list of tuples [(result_year1, result_month1), (result_year2, result_month2), ...]
year (4 digit integer) month (integer value between 1 to 12, 1=January, 2=February, ... 12=December)

For example: subtract 3 months from May 2020. This should result in an output Feb 2020
In this example inputs: year=2020 month=5
output: year=2020 month=2

```<code>def subtract_months(input_list):
    output_list = []
    #TODO: implement your code here

    return output_list
</code>```

答:
Solution I have come up with and it works well for all cases.

def subtract_Months(year,month,month_to_subtract) :

```<code>result_month = 0
result_year = 0
if month > (month_to_subtract % 12):
    result_month = (month - month_to_subtract) % 12
    result_year = year - month_to_subtract // 12
else:
    result_month = 12 - (month_to_subtract % 12) + month
    result_year = year - (month_to_subtract // 12 + 1)

return (result_year, result_month)
</code>```

subtract_Months(2010,5,7)

(2009,10)

Title: Subtract months from year in Python

Body:
implement function subtract_months to subtract n number of months from a given year and month.

Inputs: Is a list of tuples [(year1, month1, months_to_subtract1), (year2, month2, months_to_subtract2), ...]
where, year is a 4 digit integer
month is an integer value between 1 to 12, 1=January, 2=February, ... 12=December) and
months_to_subtract is an integer

Output: Is a list of tuples [(result_year1, result_month1), (result_year2, result_month2), ...]
year (4 digit integer) month (integer value between 1 to 12, 1=January, 2=February, ... 12=December)

For example: subtract 3 months from May 2020. This should result in an output Feb 2020
In this example inputs: year=2020 month=5
output: year=2020 month=2

def subtract_months(input_list):
    output_list = []
    #TODO: implement your code here

    return output_list

Body:
Solution I have come up with and it works well for all cases.

def subtract_Months(year,month,month_to_subtract) :

result_month = 0
result_year = 0
if month > (month_to_subtract % 12):
    result_month = (month - month_to_subtract) % 12
    result_year = year - month_to_subtract // 12
else:
    result_month = 12 - (month_to_subtract % 12) + month
    result_year = year - (month_to_subtract // 12 + 1)

return (result_year, result_month)

subtract_Months(2010,5,7)

(2009,10)


问:
How to send Javascript array as Json combined with a html form?
I am creating a restaurant menu app that a waiter can use to input orders.

I have a Js array called itemOrderList that I am storing item names in. I want to be able to send that list of item names as Json array with customer name form input field and item price to back end to be stored in my DB. I am having issues going about doing this. What should I do? Google dev tools says "ReferenceError: itemOrderList is not defined" where I am trying to stringify the Js array.

AngularJs code

```<code> .controller('orderAddCtrl', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {

            $scope.itemOrderList = [];
            $scope.totalItemPrices = 0;

            $scope.addOrderToList = function (item) {
                console.log(item.itemName);
                $scope.addPricesToTotalItemPrices(item.itemPrice);
                $scope.itemOrderList.push(item.itemName);
            };

            $scope.addPricesToTotalItemPrices = function (price) {
                console.log(price);
                $scope.totalItemPrices += price ;
            };

            $scope.removeFromOrderToList = function (index) {
                console.log(index);
                $scope.itemOrderList.splice(index, 1);
            };

            $scope.createOrder = function (order) {
                var myJson = JSON.stringify(itemOrderList);
                order.orderPrice = totalItemPrices;
                order.orderItems = myJson;
                dataService.addOrder(order).then(function () {
                    $location.path('/');
                });
            };
</code>```

Html

```<code><form class="form-horizontal" ng-init="getItems()">
    <div class="row">
        <div class="col-6">
            <div class="form-group">
                <div>
                    <input ng-click="createOrder(order)" class="btn  btn-success" value="Create" />
                    <a href="#/" class="btn  btn-success">Back</a>
                </div>
            </div>
        </div>

        <div class="col-6">
            <div class="form-group">
                <label class="control-label">Customer Name</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" ng-model="order.customerName" />
                </div>
            </div>
        </div>
    </div>

    <div>
        <h1>Total Price: ${{totalItemPrices}}</h1>
    </div>

    <div class="">
        <h2>Food Items</h2>
        <div class="row">
            <button class="btn btn-success col-3" ng-repeat="i in Items" ng-click="addOrderToList(i)">{{i.itemName}}</button>
        </div>
    </div>

    <div class="">
        <h2>Order Items</h2>
        <ul>
            <li ng-repeat="i in itemOrderList track by $index">
                <p>{{i}}/<p>
                    <button ng-click="removeFromOrderToList($index)">Remove</button>
            </li>
        </ul>
    </div>
    </div>
</form>
</code>```

答:
I bet you need to specify you're using vars declared in $scope as so...</p>

```<code>$scope.createOrder = function (order) {
  var myJson = JSON.stringify($scope.itemOrderList);
  order.orderPrice = $scope.totalItemPrices;
  order.orderItems = myJson;
  dataService.addOrder(order).then(function () {
    $location.path('/');
  });
};
</code>```

Body:
I am creating a restaurant menu app that a waiter can use to input orders.

I have a Js array called itemOrderList that I am storing item names in. I want to be able to send that list of item names as Json array with customer name form input field and item price to back end to be stored in my DB. I am having issues going about doing this. What should I do? Google dev tools says "ReferenceError: itemOrderList is not defined" where I am trying to stringify the Js array.

AngularJs code

 .controller('orderAddCtrl', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {

            $scope.itemOrderList = [];
            $scope.totalItemPrices = 0;

            $scope.addOrderToList = function (item) {
                console.log(item.itemName);
                $scope.addPricesToTotalItemPrices(item.itemPrice);
                $scope.itemOrderList.push(item.itemName);
            };

            $scope.addPricesToTotalItemPrices = function (price) {
                console.log(price);
                $scope.totalItemPrices += price ;
            };

            $scope.removeFromOrderToList = function (index) {
                console.log(index);
                $scope.itemOrderList.splice(index, 1);
            };

            $scope.createOrder = function (order) {
                var myJson = JSON.stringify(itemOrderList);
                order.orderPrice = totalItemPrices;
                order.orderItems = myJson;
                dataService.addOrder(order).then(function () {
                    $location.path('/');
                });
            };

Html

<form class="form-horizontal" ng-init="getItems()">

                    <input ng-click="createOrder(order)" class="btn  btn-success" value="Create" />
                    Back

                Customer Name

                    <input type="text" class="form-control" ng-model="order.customerName" />

Total Price: ${{totalItemPrices}}

Food Items

            <button class="btn btn-success col-3" ng-repeat="i in Items" ng-click="addOrderToList(i)">{{i.itemName}}</button>

Order Items

{{i}}/

                    <button ng-click="removeFromOrderToList($index)">Remove</button>

</form>

Body:
I bet you need to specify you're using vars declared in $scope as so...

$scope.createOrder = function (order) {
  var myJson = JSON.stringify($scope.itemOrderList);
  order.orderPrice = $scope.totalItemPrices;
  order.orderItems = myJson;
  dataService.addOrder(order).then(function () {
    $location.path('/');
  });
};


问:
Order and Growth Function of Loops
I'm trying to find the order and growth function of this for loop inside a function which takes in an array of length n > 2.

This function orders the array in ascending order. I'm trying to find the order for a worst case scenario: when the array is ordered initially in descending order and the function therefore has to iterate through the array many times to sort it.

Here is the loop:

```<code>        for (int next = 1; next < array.length; next++) {
            int value = array[next];
            int index = next;
            while (index > 0 && value < array[index - 1]) {
                array[index] = array[index - 1];
                index--;
            }
            array[index] = value;
        }
</code>```

I've been racking my brains trying to figure it out. Writing tests, writing tons of functions down and I get close, but never right on. How would you go through such a loop to find it's order and growth function?

Any direction would greatly be appreciated. Thank you so much.

答:
Let n be the array length. This loop is of worst-case running time O(n^2). The simple way to see this is as follows:

When next = 1, the number of operations done by the while loop is at most 1. When next = 2, the number of operations is at most 2, and so on until next = (n - 1). We can ignore the other operations done by the for loop because they constitute lower order terms which are irrelevant to growth.

So now, the number of operations is k * (1 + 2 + 3 + 4 + ... + (n - 1)) = k*(n*(n - 1)/2) = kn^2 - kn/2 where k is a constant factor.

Therefore, the growth of the function is of order n^2.

Edit:

To address the comment, we usually do not count the total number of statements because there is no standard to do so.

For example, would you count one iteration of the follow loop as one statement (a single print statement) or two statements (the print statement and incrementing i)?

```<code>for (int i = 0; i < n; i++)
{
    print(i);
}
</code>```

In addition, it is frankly not a very useful metric. In most cases, we only care about the highest order term of an algorithm.

However, to answer your question, I would count the loop as performing these many statements:
2n^2 + 2n - 3.

Title: Order and Growth Function of Loops

Body:
I'm trying to find the order and growth function of this for loop inside a function which takes in an array of length n > 2.

This function orders the array in ascending order. I'm trying to find the order for a worst case scenario: when the array is ordered initially in descending order and the function therefore has to iterate through the array many times to sort it.

Here is the loop:

        for (int next = 1; next < array.length; next++) {
            int value = array[next];
            int index = next;
            while (index > 0 && value < array[index - 1]) {
                array[index] = array[index - 1];
                index--;
            }
            array[index] = value;
        }

I've been racking my brains trying to figure it out. Writing tests, writing tons of functions down and I get close, but never right on. How would you go through such a loop to find it's order and growth function?

Any direction would greatly be appreciated. Thank you so much.

Body:
Let n be the array length. This loop is of worst-case running time O(n^2). The simple way to see this is as follows:

When next = 1, the number of operations done by the while loop is at most 1. When next = 2, the number of operations is at most 2, and so on until next = (n - 1). We can ignore the other operations done by the for loop because they constitute lower order terms which are irrelevant to growth.

So now, the number of operations is k * (1 + 2 + 3 + 4 + ... + (n - 1)) = k*(n*(n - 1)/2) = kn^2 - kn/2 where k is a constant factor.

Therefore, the growth of the function is of order n^2.

Edit:

To address the comment, we usually do not count the total number of statements because there is no standard to do so.

For example, would you count one iteration of the follow loop as one statement (a single print statement) or two statements (the print statement and incrementing i)?

for (int i = 0; i < n; i++)
{
    print(i);
}

In addition, it is frankly not a very useful metric. In most cases, we only care about the highest order term of an algorithm.

However, to answer your question, I would count the loop as performing these many statements:
2n^2 + 2n - 3.


问:
ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve com.github.lzyzsd:circleprogress:1.2.1
Whenever I try to include any dependency Build Fails, I have tried many solutions such ass clean project and rebuild, invalidate cache even reinstalled android studio
enter image description here</p>

答:
Add this to your project level build.gradle file

maven { url "https://jitpack.io" }


问:
Provider cannot be found. It may not be properly installed when using ADO driver instead of DAO
I've installed on my Windows 10 machine an Oracle ODBC Instant Client 12 in order to connect my Excel macro to an Oracle database. My application is capable to connect to Oracle database by using DAO or ADO drivers. The connection to database works fine with DAO however when I try to use the ADO driver I'm getting the following error:

Provider cannot be found.It may not be properly installed

How I a ADO connection is being setup in Excel macro:

```<code>Set Connection = VBA.CreateObject("ADODB.Connection")
Connection.ConnectionString = IDatenbank_BuildConnectionString(ODBCConnection)
Call Connection.Open

IDatenbank_BuildConnectionString = "ODBC" & _
                                    ";DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password
</code>```

Any advice on how to work with ADO driver and avoid the error "Provider cannot be found. It may not be properly installed."

Excel 2016 is running on 32 bites on a Windows 10 machine used as a server. Microsoft ODBC is installed on 32 bits as the Excel instance.

What I have done until now:

Installed and Oracle Client for ODBC 32 bits;

Installed Access Database Engine for 32 bites;

Microsoft Data Access Components (MDAC)

In client machine they can run together however seems not be true when server is used.

答:
You don't need the "ODBC" in front of your connection string if you are using standard Oracle ODBC.

From your code, it contains the "ODBC":

```<code>'ODBC;DSN=xxx;Uid=yyy;Pwd=zzz
IDatenbank_BuildConnectionString = "ODBC" & _
                                    ";DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password

'It should be "DSN=xxx;Uid=yyy;Pwd=zzz" only without "ODBC" in front
IDatenbank_BuildConnectionString = "DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password
</code>```

Body:
I've installed on my Windows 10 machine an Oracle ODBC Instant Client 12 in order to connect my Excel macro to an Oracle database. My application is capable to connect to Oracle database by using DAO or ADO drivers. The connection to database works fine with DAO however when I try to use the ADO driver I'm getting the following error:

Provider cannot be found.It may not be properly installed

How I a ADO connection is being setup in Excel macro:

Set Connection = VBA.CreateObject("ADODB.Connection")
Connection.ConnectionString = IDatenbank_BuildConnectionString(ODBCConnection)
Call Connection.Open

IDatenbank_BuildConnectionString = "ODBC" & _
                                    ";DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password

Any advice on how to work with ADO driver and avoid the error "Provider cannot be found. It may not be properly installed."

Excel 2016 is running on 32 bites on a Windows 10 machine used as a server. Microsoft ODBC is installed on 32 bits as the Excel instance.

What I have done until now:

Installed and Oracle Client for ODBC 32 bits;

Installed Access Database Engine for 32 bites;

Microsoft Data Access Components (MDAC)

In client machine they can run together however seems not be true when server is used.

Body:
You don't need the "ODBC" in front of your connection string if you are using standard Oracle ODBC.

From your code, it contains the "ODBC":

'ODBC;DSN=xxx;Uid=yyy;Pwd=zzz
IDatenbank_BuildConnectionString = "ODBC" & _
                                    ";DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password

'It should be "DSN=xxx;Uid=yyy;Pwd=zzz" only without "ODBC" in front
IDatenbank_BuildConnectionString = "DSN=" & ODBCConnection.Name & _
                                    ";Uid=" & ODBCConnection.User & _
                                    ";Pwd=" & ODBCConnection.Password


问:
Tcl_AsyncDelete with pynput and pyautogui
In a simplified version of the code:

from pynput import keyboard
import time
import pyautogui

class Test:
    def __init__(self):
        self.paused = False

    def on_activate(self):
        if self.paused:
            pyautogui.alert(text='was paused', title='title', button='button')
            self.paused = False
        elif self.paused is False:
            pyautogui.alert(text='was not paused', title='title', button='button')
            self.paused = True

test = Test()
pyautogui.alert(text='test', title='title', button='button')
hotkey = keyboard.GlobalHotKeys({
    '<ctrl>+a': test.on_activate
})
hotkey.start()

while True:
    time.sleep(1)
```

I will get the error Tcl_AsyncDelete: async handler deleted by the wrong thread.

Now I understand that this comes from issues handling threading, or rather the lack of said handling. I noticed that if the code runs without the alert() below the class declaration; there is never any such error.

I believe I understand that this comes from pynput working on another thread than the first pyautogui call was made; however since I no longer have a use for for alert boxes there is there a way to "properly close" it in that thread and operate it on the other?

I am at a slight loss and any input or help would be greatly appreciated.

答:
I've managed to find a workaround solution it seems. The 'solution' as it stands it to simply not use pyautogui for those prompts and to build a unique tkinter box per call for those listener calls. My resulting end code is:

from pynput import keyboard
import time
import pyautogui
import tkinter as tk
import tkinter.messagebox as messagebox

def send_alert(text, title):
    root = tk.Tk()
    root.withdraw()
    messagebox.showinfo(title, text)
    root.destroy()

class Test:
    def __init__(self):
        self.paused = False

    def on_activate(self):
        if self.paused:
            send_alert('paused', 'title')
            self.paused = False
        elif self.paused is False:
            send_alert('not paused', 'title')
            self.paused = True

test = Test()
pyautogui.alert(text='test', title='title', button='button')

hotkey = keyboard.GlobalHotKeys({
    '<ctrl>+a': test.on_activate
})
hotkey.start()

while True:
    time.sleep(1)
```

Body:
In a simplified version of the code:

from pynput import keyboard
import time
import pyautogui

class Test:
    def __init__(self):
        self.paused = False

    def on_activate(self):
        if self.paused:
            pyautogui.alert(text='was paused', title='title', button='button')
            self.paused = False
        elif self.paused is False:
            pyautogui.alert(text='was not paused', title='title', button='button')
            self.paused = True

test = Test()
pyautogui.alert(text='test', title='title', button='button')
hotkey = keyboard.GlobalHotKeys({
    '<ctrl>+a': test.on_activate
})
hotkey.start()

while True:
    time.sleep(1)

I will get the error Tcl_AsyncDelete: async handler deleted by the wrong thread.

Now I understand that this comes from issues handling threading, or rather the lack of said handling. I noticed that if the code runs without the alert() below the class declaration; there is never any such error.

I believe I understand that this comes from pynput working on another thread than the first pyautogui call was made; however since I no longer have a use for for alert boxes there is there a way to "properly close" it in that thread and operate it on the other?

I am at a slight loss and any input or help would be greatly appreciated.