问:
How to query the concrete table when only the parent table id is known
I have an inheritance relationship in my database, where I have a parent table (Table A) that is basically a sequence of auto-incrementing integers (Id column).  From here, I have several tables (Table B,C & D) that also have an Id column, which is a foreign key to the Id column in Table A.

Now my question is, if I have the Id, what is the most efficient way I can go about getting the correct row from table B, C, or D?

EDIT: There will be only ONE row with the Id in either table B, C, or D (there will not be a matching row in the other 2).

答:
You could use union queries ... i.e.:

```<code>select 'TABLE B', a_id from b where a_id = 1
UNION
select 'TABLE C', a_id from c where a_id = 1
UNION
select 'TABLE D', a_id from d where a_id = 1;
</code>```

This would give you a list of tables with an a_id of 1, while also showing the table it resided in.

If all 3 tables have the same structure, you could do something similar:

```<code>select b.* from b where a_id = 1
UNION
select c.* from c where a_id = 1
UNION
select d.* from d where a_id = 1;
</code>```

OwnerDisplayName: questioningquerier

LastEditorDisplayName: questioningquerier

Body:
You could use union queries ... i.e.:

select 'TABLE B', a_id from b where a_id = 1
UNION
select 'TABLE C', a_id from c where a_id = 1
UNION
select 'TABLE D', a_id from d where a_id = 1;

This would give you a list of tables with an a_id of 1, while also showing the table it resided in.

If all 3 tables have the same structure, you could do something similar:

select b.* from b where a_id = 1
UNION
select c.* from c where a_id = 1
UNION
select d.* from d where a_id = 1;

OwnerDisplayName: LuckyLindy

LastEditorDisplayName: LuckyLindy


来源: stackexchange

问:
Django test client http basic auth for post request
everyone. I am trying to write tests for RESTful API implemented using django-tastypie with http basic auth. So, I have the following code:

```<code>def http_auth(username, password):
    credentials = base64.encodestring('%s:%s' % (username, password)).strip()
    auth_string = 'Basic %s' % credentials
    return auth_string

class FileApiTest(TestCase):

    fixtures = ['test/fixtures/test_users.json']

    def setUp(self):
        self.extra = {
            'HTTP_AUTHORIZATION': http_auth('testuser', 'qwerty')
        }

    def test_folder_resource(self):
        response = self.client.get('/api/1.0/folder/', **self.extra)
        self.assertEqual(response.status_code, 200)

    def test_folder_resource_post(self):
        response = self.client.post('/api/1.0/folder/', **self.extra)
        self.assertNotEqual(response.status_code, 401)
</code>```

GET request is done well, returning status code 200. But POST request always returns 401. I am sure I am doing something wrong. Any advice?

答:
I've found a reason of my problem. DjangoAuthorization checks permissions with django premissions framework, since I don't use it in my project — all post/put/delete requests from non superuser are unauthorized. My bad.

Anyway, thanks a lot to you, guys, for responses.

ContentLicense: CC BY-SA 3.0

Body:
everyone. I am trying to write tests for RESTful API implemented using django-tastypie with http basic auth. So, I have the following code:

def http_auth(username, password):
    credentials = base64.encodestring('%s:%s' % (username, password)).strip()
    auth_string = 'Basic %s' % credentials
    return auth_string

class FileApiTest(TestCase):

    fixtures = ['test/fixtures/test_users.json']

    def setUp(self):
        self.extra = {
            'HTTP_AUTHORIZATION': http_auth('testuser', 'qwerty')
        }

    def test_folder_resource(self):
        response = self.client.get('/api/1.0/folder/', **self.extra)
        self.assertEqual(response.status_code, 200)

    def test_folder_resource_post(self):
        response = self.client.post('/api/1.0/folder/', **self.extra)
        self.assertNotEqual(response.status_code, 401)

GET request is done well, returning status code 200. But POST request always returns 401. I am sure I am doing something wrong. Any advice?


问:
Is there a way to generate a combo list of string characters by accessing the dictionary?
key_map = {'1': "'-", '2': 'abc', '3': 'def',
               '4': 'ghi', '5': 'jkl', '6': 'mno',
               '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

Generate a list of all 3-character prefixes that can be
        generated from the beginning key presses.

pt = PText()
      pt.add('234')
      [prefix for prefix in pt.possible_prefixes()]

```<code>    ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']
</code>```

答:
Although I had some trouble reading your question at first, I believe you're looking for a function that will take a string containing keys of the dictionary and find all combinations of characters from the strings under those keys.

Although we could use for loops or list comprehensions to implement this ourselves, what you are looking for is a form of Cartesian product. Python's standard library can already do this, using itertools.product. It takes any number of iterables as an argument and returns all combinations of single elements taken from those iterables.

Thus, your possible_prefixes(keys) could look like

import itertools
def possible_prefixes(keys):
    return ["".join(res) for res in itertools.product(*(key_map[key] for key in keys))]
```

The *() is a generator comprehension that converts each key into its corresponding value, and then expands it so that each entry is a seperate argument of itertools.product. Thus, if we filled in keys = '234' it would expand to itertools.product('abc', 'def', ghi'), which gives the required result. The "".join(res) for res in is a list comprehension that we need because itertools.product actually returns tuples, and you need a list of strings.

ContentLicense: CC BY-SA 4.0

Body:
key_map = {'1': "'-", '2': 'abc', '3': 'def',
               '4': 'ghi', '5': 'jkl', '6': 'mno',
               '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

Generate a list of all 3-character prefixes that can be
        generated from the beginning key presses.

pt = PText()
      pt.add('234')
      [prefix for prefix in pt.possible_prefixes()]

    ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

Body:
Although I had some trouble reading your question at first, I believe you're looking for a function that will take a string containing keys of the dictionary and find all combinations of characters from the strings under those keys.

Although we could use for loops or list comprehensions to implement this ourselves, what you are looking for is a form of Cartesian product. Python's standard library can already do this, using itertools.product. It takes any number of iterables as an argument and returns all combinations of single elements taken from those iterables.

Thus, your possible_prefixes(keys) could look like

import itertools
def possible_prefixes(keys):
    return ["".join(res) for res in itertools.product(*(key_map[key] for key in keys))]

The *() is a generator comprehension that converts each key into its corresponding value, and then expands it so that each entry is a seperate argument of itertools.product. Thus, if we filled in keys = '234' it would expand to itertools.product('abc', 'def', ghi'), which gives the required result. The "".join(res) for res in is a list comprehension that we need because itertools.product actually returns tuples, and you need a list of strings.


问:
Loop over list with and condition
I am trying to write a code for below pseudocode

```<code>for all element in list do
    match and condition
    if all match
       return True
</code>```

for example, List A=[1,2,3,4,5],B=10

What I want is like

```<code>def match():
    for i in range(len(A)):
      if B%A[0]==0 and B%A[1]==0 and B%A[2]==0 and B%A[3]==0 and B%A[4]==0: #Generate all these
        #and condition one by one
        #automatically in this function
          return True
</code>```

How can I do?

NOTE:I am asking about write code match and condition with a loop, not write a remainder

答:
Try this one:</p>

```<code>result = all( [(B%a==0) for a in A] )
</code>```

Title: Loop over list with and condition

Body:
I am trying to write a code for below pseudocode

for all element in list do
    match and condition
    if all match
       return True

for example, List A=[1,2,3,4,5],B=10

What I want is like

def match():
    for i in range(len(A)):
      if B%A[0]==0 and B%A[1]==0 and B%A[2]==0 and B%A[3]==0 and B%A[4]==0: #Generate all these
        #and condition one by one
        #automatically in this function
          return True

How can I do?

NOTE:I am asking about write code match and condition with a loop, not write a remainder

Body:
Try this one:

result = all( [(B%a==0) for a in A] )


问:
Changing sign-in name in AAD B2C
I'm trying to implement Change Sign-in Name flow from AAD B2C samples. Basically the policy works but the problem is that the user is still logged in after changing his e-mail.

In my understanding changing the primary identity must invalidate all issued tokens/sessions immediately and force the user to re-authenticate. How come this can be secure and isn't addressed in the sample? How can I do it? I could redirect the request to the B2C sign-out endpoint but here is another issue:

When a user clicks "Change Sign-In Name" link he gets redirected to the policy endpoint with a specified redirect_uri query string param. In my case it's https://localhost:44300. The problem is he gets redirected back to my site when he finishes the flow and when he cancels the flow and I cannot distinguish between the two as there seems to be nothing in the request to check.

So, how can I get the user back to https://localhost:44300 if he cancels the flow (the email isn't changed) and perform Single Sign-Out if he finishes the flow?

答:
This is a very good question. When the token is generated it has a lifespan of a set time. For example 1 hour.

When you use this token, it is assumed that the user is good-to-go until the token expires and a refresh token is issued.

When the refresh token is consumed is when a new validation will occur and will need to re-authenticate.

Title: Changing sign-in name in AAD B2C


问:
sugarcrm displaying users list in a multiselect
I am using SugarCRM Professional as well as Community version latest ones.

in Create Projects screen, there is Assign To field which popups all the userslist.
But I want those users list in a multiselect dropdown as I want to select multiple without popup window as per the client requirement.

I dont want to add users name manually in the list, it should be dynamic. Please help.

答:
First of I would ask why you want to assign multiple users to a project?  Usually projects are assigned to the project manager and individual project tasks are then assigned onto the team members who will complete them.   Is it for reporting purposes?  So the project teams is aware of what is happening? Another reason?

Sugar will only assign one user per record out of the box, in pro you could use teams to represent multiple users assignment, there are also third party plugins that will also allow this functionality to be added to CE.

However if you are wanting more flexibility than static team assignment the you would have to develop something specifically.

Teams a third party module or custom relation ship from users to projects could be used and using hooks/ajax ect a script could be written to populate a multi select on the project with all users.  These could then be multi selected and on save a new team for the project could be dynamically created.

Hope this has helped you.


问:
How do I mask an email address between the first and the last character before the @ sign?
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

```<code>var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};
</code>```

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

答:
Well, this's what you're looking for, and this will be the output j*****e@abc.com.

var ans = "";
var S = "johndoe@abc.com"; //example
S = S.toLowerCase();
var parts = S.split("@");
var first = "";
for(var i = 0; i < parts[0].length; i++){
  if(i != 0 && i != parts[0].length - 1){
      first += '*';
  }else{
      first += parts[0][i];
  }
}

ans = first +"@"+ parts[1];
console.log(ans); ```

Body:
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?


问:
Install an npm module from a private GitHub repository using GitHub Actions
I am trying to run a build for a Node.js project using GitHub Actions. As part of the npm install, I need to install an npm module directly from a private GitHub repository (not from GPR!).

In the package.json I have:

```<code>"dependencies": {
  ...
  "my-module": "github:<org>/<my-module>#master",
  ...
},
</code>```

However, when running npm install, I get:

npm ERR! git@github.com: Permission denied (publickey).
  npm ERR! fatal: Could not read from remote repository.

The repository is part of my own organization, and locally (i.e. from my machine) it works. How can I make this run?

I have already tried setting the NODE_AUTH_TOKEN environment variable, but it didn't make a difference. Although you find this suggestion quite often, it seems to only address GPR. What I would like to avoid is having to hardcode the token into the package.json file. Any thoughts on this?

答:
This is how I have managed to install dependencies from private GitHub repositories.

Dependencies in package.json can be added as follows. The github: prefix is optional. Specifying the #branch or #tag is also optional.

```<code>    "dependencies": {
        ...
        "myrepo": "username/myrepo#master",
        "myotherrepo": "github:username/myotherrepo"
    },
</code>```

Here is an example workflow. PAT is a repo scoped Personal Access Token. It is important to disable persisted credentials on actions/checkout, otherwise they will override your PAT. Note that the git config change persists between steps so you only need to run it once per job.

```<code>      - uses: actions/checkout@v2
        with:
          persist-credentials: false
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - run: git config --global url."https://${{ secrets.PAT }}@github.com/".insteadOf ssh://git@github.com/
      - run: npm ci
      ...
</code>```

Body:
I am trying to run a build for a Node.js project using GitHub Actions. As part of the npm install, I need to install an npm module directly from a private GitHub repository (not from GPR!).

In the package.json I have:

"dependencies": {
  ...
  "my-module": "github:<org>/<my-module>#master",
  ...
},

However, when running npm install, I get:

npm ERR! git@github.com: Permission denied (publickey).
  npm ERR! fatal: Could not read from remote repository.

The repository is part of my own organization, and locally (i.e. from my machine) it works. How can I make this run?

I have already tried setting the NODE_AUTH_TOKEN environment variable, but it didn't make a difference. Although you find this suggestion quite often, it seems to only address GPR. What I would like to avoid is having to hardcode the token into the package.json file. Any thoughts on this?

Body:
This is how I have managed to install dependencies from private GitHub repositories.

Dependencies in package.json can be added as follows. The github: prefix is optional. Specifying the #branch or #tag is also optional.

    "dependencies": {
        ...
        "myrepo": "username/myrepo#master",
        "myotherrepo": "github:username/myotherrepo"
    },

Here is an example workflow. PAT is a repo scoped Personal Access Token. It is important to disable persisted credentials on actions/checkout, otherwise they will override your PAT. Note that the git config change persists between steps so you only need to run it once per job.

      - uses: actions/checkout@v2
        with:
          persist-credentials: false
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - run: git config --global url."https://${{ secrets.PAT }}@github.com/".insteadOf ssh://git@github.com/
      - run: npm ci
      ...


问:
How do I get the directory for the app itself in xamarin.forms
I have a .txt file in a Resources folder that I created in the Xamarin.Forms project for the app (not the Android or iOS versions), and I want to know how to access that file as soon as the app loads. I tried just creating a StreamReader with the path "Resources/tips.txt" ("tips" is the name of the file), but that doesn't work because apparently, the current directory at that point is nothing. How do I get the directory of the app itself so I can access that folder?</p>

答:
Resources aren't files, you don't use file paths to access them</p>

```<code>// MyClass is a class in the same assembly as your resource
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyClass)).Assembly;

// see linked docs for notes about resource naming
Stream stream = assembly.GetManifestResourceStream("MyResourceName");

string text = "";

using (var reader = new System.IO.StreamReader (stream))
{
    text = reader.ReadToEnd ();
}
</code>```

Body:
Resources aren't files, you don't use file paths to access them

// MyClass is a class in the same assembly as your resource
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyClass)).Assembly;

// see linked docs for notes about resource naming
Stream stream = assembly.GetManifestResourceStream("MyResourceName");

string text = "";

using (var reader = new System.IO.StreamReader (stream))
{
    text = reader.ReadToEnd ();
}


问:
Is there a way to import Components into index.tsx from the same directory of index.tsx
Is it possible to import React components from inside the page's directory ?
I can successfully import from outside /pages/[...]/.
/components/[...]/ works just fine for instance. And that is cool for re-usable components.

But if I want to split a single page's components into separate files as follows :

```<code>/components
- SomeReusableComponent.tsx
/pages/[...]/
- index.tsx
- SomePageComponent.tsx
</code>```

And import it into my main component :

// /pages/[...]/index.tsx
import SomeReusableComp from '../components/SomeReusableComponent'
import SomePageComp from './SomePageComponent'

export default function MyPage(){
// page code
}
```

My build fails : Build optimization failed: found pages without a React Component as default export in
pages/

Is there a trick to do that ? Some setting or else to tell nextjs that this file is a dependency and not a page ?

答:
No, unfortunately that is not possible. All files within the pages directory for a Next.js project must be entry points (that subsequently get turned into routes) and cannot be imported from any other files in your project. Next "collects" all of these files in pages and processes them in a special way, so there is no way to avoid that currently.

Typically for reusable parts that I want to use in multiple pages, I create a component that accepts children as a prop.

For example:

components/layout.js

```<code>export default function Layout({children}) {
  return (
    <div className="some-styling-for-pages">
      {children}
    </div>
  )
}
</code>```

pages/index.js

```<code>import Layout from '../components/layout'

export default function IndexPage() {
  return <Layout>my page content</Layout>
}
</code>```

Body:
Is it possible to import React components from inside the page's directory ?
I can successfully import from outside /pages/[...]/.
/components/[...]/ works just fine for instance. And that is cool for re-usable components.

But if I want to split a single page's components into separate files as follows :

/components
- SomeReusableComponent.tsx
/pages/[...]/
- index.tsx
- SomePageComponent.tsx

And import it into my main component :

// /pages/[...]/index.tsx
import SomeReusableComp from '../components/SomeReusableComponent'
import SomePageComp from './SomePageComponent'

export default function MyPage(){
// page code
}

My build fails : Build optimization failed: found pages without a React Component as default export in
pages/

Is there a trick to do that ? Some setting or else to tell nextjs that this file is a dependency and not a page ?

Body:
No, unfortunately that is not possible. All files within the pages directory for a Next.js project must be entry points (that subsequently get turned into routes) and cannot be imported from any other files in your project. Next "collects" all of these files in pages and processes them in a special way, so there is no way to avoid that currently.

Typically for reusable parts that I want to use in multiple pages, I create a component that accepts children as a prop.

For example:

components/layout.js

export default function Layout({children}) {
  return (
    <div className="some-styling-for-pages">
      {children}
    </div>
  )
}

pages/index.js

import Layout from '../components/layout'

export default function IndexPage() {
  return <Layout>my page content</Layout>
}


问:
A pattern that matches all except starting with a word
How can I set a regex pattern which matches all words but the strings which starts with

/word

/word/

/word/ following by anything else.

I think the pattern starts with  \A but I don'0t know how to tell that should not follow a word

Thanks

答:
Use this kind of negate regex and replace word by your word.</p>

```<code>^((?!word).)*$
</code>```

Body:
Use this kind of negate regex and replace word by your word.

^((?!word).)*$


问:
How to install and use VS Code Icon Fonts
I want to believe that the best way of using icons in VS code is via the icon fonts extension (tell me if I'm wrong). Before now, I used to download icons in .png format before using them. The problem is that, the whole process of setting-up the extension (found in marketplace and open-vsx) for use doesn't seem to be clear (especially for a newbie like me). Please, I need a step by step explanation on how to go about this.
OR
If there exist a better alternative let me know. Thank you.</p>

答:
in my opinion, if you use an icon with a .png file format, then it will obviously slow down the performance of your website. do you already know about CSS framework that works with icons? I'll give you a few CSS framework references that work on handling the icons you need

https://fontawesome.com/

https://www.glyphicons.com/

https://materialdesignicons.com/


问:
ReactNative & Expo: Ionicons not rendering
According to the docs, if I have Expo installed I don't need to do anything else besides the import statement.

My component:

```<code>import React, { useContext } from "react"
import { StyleSheet, View, TouchableOpacity } from "react-native"
import { MusicContext } from "../context/MusicContext"
import { Ionicons } from "@expo/vector-icons"

export const MusicPlayer = () => {
  const { previousTrack, pauseAndPlay, nextTrack, isPlaying } = useContext(MusicContext)

  return (
    <View style={styles.musicPlayerContainer}>
      <View style={styles.controls}>
        <TouchableOpacity style={styles.control} onPress={previousTrack}>
          <Ionicons name="md-skip-backward" size={24} color="black" />
        </TouchableOpacity>

        <TouchableOpacity style={styles.control} onPress={pauseAndPlay}>
          {isPlaying ? (
            <Ionicons name="md-pause" size={24} color="black" />
          ) : (
            <Ionicons name="md-play-circle" size={24} color="black" />
          )}
        </TouchableOpacity>

        <TouchableOpacity style={styles.control} onPress={nextTrack}>
          <Ionicons name="md-skip-forward" size={24} color="black" />
        </TouchableOpacity>
      </View>
    </View>
  )
}
</code>```

According to the icon directory, https://icons.expo.fyi/, I got all I need, but the icons don't render.

They appear as little boxes with X's in them.

How can I fix this?  Thanks!

答: make sure you are using the appropriate babel preset. initialize a new project and compare the babel.config.js with the one in your project </p>

Body:
According to the docs, if I have Expo installed I don't need to do anything else besides the import statement.

My component:

import React, { useContext } from "react"
import { StyleSheet, View, TouchableOpacity } from "react-native"
import { MusicContext } from "../context/MusicContext"
import { Ionicons } from "@expo/vector-icons"

export const MusicPlayer = () => {
  const { previousTrack, pauseAndPlay, nextTrack, isPlaying } = useContext(MusicContext)

  return (
    <View style={styles.musicPlayerContainer}>
      <View style={styles.controls}>
        <TouchableOpacity style={styles.control} onPress={previousTrack}>
          <Ionicons name="md-skip-backward" size={24} color="black" />
        </TouchableOpacity>

        <TouchableOpacity style={styles.control} onPress={pauseAndPlay}>
          {isPlaying ? (
            <Ionicons name="md-pause" size={24} color="black" />
          ) : (
            <Ionicons name="md-play-circle" size={24} color="black" />
          )}
        </TouchableOpacity>

        <TouchableOpacity style={styles.control} onPress={nextTrack}>
          <Ionicons name="md-skip-forward" size={24} color="black" />
        </TouchableOpacity>
      </View>
    </View>
  )
}

According to the icon directory, https://icons.expo.fyi/, I got all I need, but the icons don't render.

They appear as little boxes with X's in them.

How can I fix this?  Thanks!


问:
Median of Multiple Columns of a DF in R (all values together)
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

```<code>    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352
</code>```

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

答:
Select the columns that you want to take median of, you can do that by column names or column number, unlist and take median of all values.

```<code>cols <- 4:7
median(unlist(df[cols]), na.rm = TRUE)
#Or
#median(as.matrix(df[cols]), na.rm = TRUE)
#[1] 3312.746
</code>```

Body:
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

Body:
Select the columns that you want to take median of, you can do that by column names or column number, unlist and take median of all values.

cols <- 4:7
median(unlist(df[cols]), na.rm = TRUE)
#Or
#median(as.matrix(df[cols]), na.rm = TRUE)
#[1] 3312.746


问:
Modal not showing up react-boostrap
i am using react-boostrap. The code seems to be o, but Modal does not appear. I suspect it appears but i cant see it.

I need to see the modal appear in the center. I am using bootstrap version 3 .3 and react-bootstrap 1.0.1

Feel free to see the sandbox

https://codesandbox.io/s/autumn-paper-l4tzj?file=/src/components/Menu.jsx:0-2147

thanks

```<code>import React, {Component} from "react";
import {Modal} from "react-bootstrap";

class Menu extends Component {
  state={

    addModalShow:false,

  };

  ModalShow=()=>{
    this.setState({addModalShow:true})
   };

ModalClose=()=>{
 this.setState({addModalShow:false})
};

  stylesList={
  display: 'inline-block',
  background:"#C8C8C8",
  width:'500px',
  height:'50px'

  };

  onhover=(e)=> {
    e.target.style.background = 'red';

  };

  offhover=(e)=> {
    e.target.style.background = '#C8C8C8 ';
  };

  render() {

    return (
<div className="container-fluid">

            {this.Mapping_Type()}

      </div>
    );

  }

  Mapping_Type (){

    let result_type = this.props.Objs_Type.map(a => a.FoodType);
    let result_menu = this.props.Objs_Type.map(a => a.Menu);
    let result_price=this.props.Objs_Type.map(a=>a.Price);

    let newFoodtype=[];
    let newMenu=[];
    let FoodType_Menu=[];
    let Price_new=[];
    for (let i=0;i<result_type.length; i++){

      let temp1=(<h1> Menu {result_type[i]}</h1>);
      let temp2=result_menu[i].map((item,idx)=>

      <div style={this.stylesList}>
      <ul style={{padding:0}}>
      <li style={{listStyleType:'none'}} key={item.id}
      className={"listitems"}
      onMouseOver={this.onhover}
      onMouseOut={this.offhover}
      onClick={this.ModalShow}
      > {item} {result_price[i][idx]}  </li>

    <Modal

      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      show={this.state.addModalShow}
      onHide={this.ModalClose}
    >

        <Modal.Header closeButton>
          <Modal.Title id="contained-modal-title-vcenter">
            Large Modal
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="container">
            Menu Quantity
          </div>
          </Modal.Body>

      </Modal>

     </ul>

      </div>

)

        FoodType_Menu.push(temp1,temp2);

        }
        return FoodType_Menu
            };

}

export default Menu;**strong text**
</code>```

答:
Try add a style in modal, setting opacity:

```<code><Modal style={{opacity: 1}} >
    {/* ... */}
</Modal>
</code>```

Title: Modal not showing up react-boostrap

Body:
i am using react-boostrap. The code seems to be o, but Modal does not appear. I suspect it appears but i cant see it.

I need to see the modal appear in the center. I am using bootstrap version 3 .3 and react-bootstrap 1.0.1

Feel free to see the sandbox

https://codesandbox.io/s/autumn-paper-l4tzj?file=/src/components/Menu.jsx:0-2147

thanks

import React, {Component} from "react";
import {Modal} from "react-bootstrap";

class Menu extends Component {
  state={

    addModalShow:false,

  };

  ModalShow=()=>{
    this.setState({addModalShow:true})
   };

ModalClose=()=>{
 this.setState({addModalShow:false})
};

  stylesList={
  display: 'inline-block',
  background:"#C8C8C8",
  width:'500px',
  height:'50px'

  };

  onhover=(e)=> {
    e.target.style.background = 'red';

  };

  offhover=(e)=> {
    e.target.style.background = '#C8C8C8 ';
  };

  render() {

    return (

            {this.Mapping_Type()}

    );

  }

  Mapping_Type (){

    let result_type = this.props.Objs_Type.map(a => a.FoodType);
    let result_menu = this.props.Objs_Type.map(a => a.Menu);
    let result_price=this.props.Objs_Type.map(a=>a.Price);

    let newFoodtype=[];
    let newMenu=[];
    let FoodType_Menu=[];
    let Price_new=[];
    for (let i=0;i<result_type.length; i++){

      let temp1=(
 Menu {result_type[i]}
);
      let temp2=result_menu[i].map((item,idx)=>

 {item} {result_price[i][idx]}

    <Modal

      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      show={this.state.addModalShow}
      onHide={this.ModalClose}
    >

        <Modal.Header closeButton>
          <Modal.Title id="contained-modal-title-vcenter">
            Large Modal
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>

            Menu Quantity

          </Modal.Body>

      </Modal>

)

        FoodType_Menu.push(temp1,temp2);

        }
        return FoodType_Menu
            };

}

export default Menu;**strong text**

Body:
Try add a style in modal, setting opacity:

<Modal style={{opacity: 1}} >
    {/* ... */}
</Modal>


问:
Display (values of) DataAnnotations - Swashbuckle - Swagger page
Is it possible to display the DataAnnotations of parameters on the Swagger page, e.g. the minimum and maximum values?

I've already tried setting the ShowExtensions and ShowCommonExtension to true or calling ShowExtensions(), but it doesn't solve the problem. The Range attribute and/or e.g. MaxLength(20) of a string isn't displayed on the Swagger page.

Startup (code snippet)

```<code>    app.UseSwaggerUI(
        options =>
        {
            options.ConfigObject = new ConfigObject
            {
                ShowCommonExtensions = true,
                ShowExtensions = true
            };

            options.ConfigObject.AdditionalItems.Add("showCommonExtensions", true);

            options.ShowExtensions();
</code>```

Frameworks/Packages

.NET Core 3.1

Swashbuckle.AspNetCore (5.4.1)

Swashbuckle.AspNetCore.SwaggerGen (5.4.1)

Controller (code snippet)

```<code> [HttpGet]
 public IEnumerable<string> GetMethod([Required] [Range(1, 10)] int value)
 {
</code>```

Swagger UI

答:
I did some more digging...

They do have checks for multiple attributes:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/316ddd0fe6768f470c274a0e93c789b65cf658b9/src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/OpenApiSchemaExtensions.cs#L12

```<code>if (attribute is DefaultValueAttribute defaultValue && defaultValue.Value != null)
{
    schema.Default = OpenApiAnyFactory.CreateFor(schema, defaultValue.Value);
}
else if (attribute is RegularExpressionAttribute regex)
{
    schema.Pattern = regex.Pattern;
}
else if (attribute is RangeAttribute range)
{
    schema.Maximum = decimal.TryParse(range.Maximum.ToString(), out decimal maximum)
        ? maximum
        : schema.Maximum;

    schema.Minimum = decimal.TryParse(range.Minimum.ToString(), out decimal minimum)
        ? minimum
        : schema.Minimum;
}
</code>```

But the only UnitTest using range I see is on a model:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/47684caeeaaeb4d887236e61a2ea35e4dc76b958/test/Swashbuckle.AspNetCore.TestSupport/Fixtures/DataAnnotatedViaMetadataType.cs#L26

```<code>    public class MetadataType
    {
        [Required]
        public string StringWithRequired { get; set; }

        [Required]
        public int IntWithRequired { get; set; }

        [Range(1, 12)]
        public int IntWithRange { get; set; }

        [RegularExpression("^[3-6]?\\d{12,15}$")]
        public string StringWithRegularExpression { get; set; }
    }
</code>```

If this is something you truly care about fill in a bug report:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/new

Body:
Is it possible to display the DataAnnotations of parameters on the Swagger page, e.g. the minimum and maximum values?

I've already tried setting the ShowExtensions and ShowCommonExtension to true or calling ShowExtensions(), but it doesn't solve the problem. The Range attribute and/or e.g. MaxLength(20) of a string isn't displayed on the Swagger page.

Startup (code snippet)

    app.UseSwaggerUI(
        options =>
        {
            options.ConfigObject = new ConfigObject
            {
                ShowCommonExtensions = true,
                ShowExtensions = true
            };

            options.ConfigObject.AdditionalItems.Add("showCommonExtensions", true);

            options.ShowExtensions();

Frameworks/Packages

.NET Core 3.1

Swashbuckle.AspNetCore (5.4.1)

Swashbuckle.AspNetCore.SwaggerGen (5.4.1)

Controller (code snippet)

 [HttpGet]
 public IEnumerable<string> GetMethod([Required] [Range(1, 10)] int value)
 {

Swagger UI

Body:
I did some more digging...

They do have checks for multiple attributes:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/316ddd0fe6768f470c274a0e93c789b65cf658b9/src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/OpenApiSchemaExtensions.cs#L12

if (attribute is DefaultValueAttribute defaultValue && defaultValue.Value != null)
{
    schema.Default = OpenApiAnyFactory.CreateFor(schema, defaultValue.Value);
}
else if (attribute is RegularExpressionAttribute regex)
{
    schema.Pattern = regex.Pattern;
}
else if (attribute is RangeAttribute range)
{
    schema.Maximum = decimal.TryParse(range.Maximum.ToString(), out decimal maximum)
        ? maximum
        : schema.Maximum;

    schema.Minimum = decimal.TryParse(range.Minimum.ToString(), out decimal minimum)
        ? minimum
        : schema.Minimum;
}

But the only UnitTest using range I see is on a model:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/47684caeeaaeb4d887236e61a2ea35e4dc76b958/test/Swashbuckle.AspNetCore.TestSupport/Fixtures/DataAnnotatedViaMetadataType.cs#L26

    public class MetadataType
    {
        [Required]
        public string StringWithRequired { get; set; }

        [Required]
        public int IntWithRequired { get; set; }

        [Range(1, 12)]
        public int IntWithRange { get; set; }

        [RegularExpression("^[3-6]?\\d{12,15}$")]
        public string StringWithRegularExpression { get; set; }
    }

If this is something you truly care about fill in a bug report:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/new


问:
How to verify element/text is present in dropdown list using selenium java
How to verify element/text is present in drop down list using selenium java</p>

```<code>new Select(driver.findElement(By.id("airlineid"))).selectByVisibleText("Delta");
</code>```

答:
This helped me :</p>

```<code>Select select = new Select(select_drop_down);
List<WebElement> all_options = select.getOptions();
boolean found = false;

for (WebElement we : all_options) {
    if (facility.equalsIgnoreCase(we.getAttribute("value"))) {
        select.selectByValue(facility);
        found = true;
        break;
    }
}
</code>```

Body:
How to verify element/text is present in drop down list using selenium java

new Select(driver.findElement(By.id("airlineid"))).selectByVisibleText("Delta");

Body:
This helped me :

Select select = new Select(select_drop_down);
List<WebElement> all_options = select.getOptions();
boolean found = false;

for (WebElement we : all_options) {
    if (facility.equalsIgnoreCase(we.getAttribute("value"))) {
        select.selectByValue(facility);
        found = true;
        break;
    }
}


问:
My flask application factory returns URL not found
My flask app is based on Miguel Grinberg's mega tutorial XIV with some extra stuff and it was all working fine and could be accessed from browser on localhost:5000. I decided to switch to an application factory approach as per Grinberg's XV tutorial BUT with no blueprints. Now when I enter localhost:5000 I get a URL not found. I am guessing my routes.py is not being picked up for some reason.

I have thoroughly worked through Grinberg's XV tutorial and the associated code and aligned everything less blueprints. These are the links I have explored that I have based my current app on: -

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure

http://flask.pocoo.org/docs/1.0/tutorial/factory/

Dave W Smith's answer in Configure Python Flask App to use "create_app" factory and use database in model class

and others.

From what I have read implementing an application factory should be really simple. The examples work.

The flask server starts from the command prompt in a venv as always.

Here is my directory structure.

```<code>myapp
    app.py
    config.py
    ...
    /app
        __init__.py
        routes.py
        models.py
        forms.py
        ...
</code>```

Here is the code slightly simplified for clarity.

```<code># app.py
#=============================================
from app import create_app, db
from app.models import User, Post

app = create_app()

@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'User': User, 'Post' :Post}

# __init__.py
#=============================================
...
import os
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
...
from config import Config

db = SQLAlchemy()
migrate = Migrate()
...

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    ...

    # logging, email servers, etc configured

    return app

from app import models

# routes.py
#=============================================
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, \
    jsonify, current_app
...
from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm,
     PostForm,ResetPassword,RequestForm, ResetPasswordForm
from app.models import User, Post
...

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    form = PostForm()
    if form.validate_on_submit():
        ...
    page = request.args.get('page', 1, type=int)
    ...
    return render_template('index.html', title=_('Home'), form=form,
                           posts=posts.items, next_url=next_url,
                           prev_url=prev_url)

@app.route ....

# models.py
#=============================================
from datetime import datetime
from hashlib import md5
from time import time
from flask import current_app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
from app import db, login

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    ...

</code>```

This may be irrelevant but it is one thing I tried. Note in routes.py that I have from app import app, db, if I remove app and add from flask import current_app then the @app  decorators show as undefined.

Another point, because its a problem with routes. If I change the last line of __init__.py to from app import routes, models I get a different error.

```<code>flask.cli.NoAppException
flask.cli.NoAppException: While importing "metapplica", an ImportError was raised:

Traceback (most recent call last):
  File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\cli.py", line 236, in locate_app
    __import__(module_name)
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\metapplica.py", line 1, in <module>
    from app import create_app, db, cli
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\__init__.py", line 75, in <module>
    from app import routes, models
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\routes.py", line 8, in <module>
    from app import app, db
ImportError: cannot import name 'app' from 'app' (C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\__init__.py)
</code>```

It was this error that led me to try the current_app change mentioned above.

I start the app like this.

```<code>cd C:\Users\...\myapp
venv\Scripts\activate
set FLASK_APP=app.py
set FLASK_DEBUG=1
flask run
</code>```

I know the problem is probably really basic but can anyone see why the above code would give a URL not found or not be able to find the routes?

=== NEXT PHASE ================
Following the recommendations from @silver below my new names are: -

```<code>myapp
    runapp.py
    ...
    /mapp
        __init__.py
        ...
</code>```

I went through all my code and changed from app[.xxx] import yyy to from myapp[.xxx] import yyy. This flushed out a few new errors where I was referencing app which I fixed by substituting current_app.
My new error is

```<code>RuntimeError
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

Traceback (most recent call last)
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\runapp.py", line 1, in <module>
from mapp import create_app, db, cli
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\mapp\__init__.py", line 75, in <module>
from mapp import routes, models
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\mapp\routes.py", line 16, in <module>
@current_app.before_request
</code>```

答:
I just ran into this issue too with Miguel Grinberg's tutorial. It's a pretty fantastic tutorial till some of the later sections which feel rushed.

Anyway.
You need to pass the context.
In the factory function you need to do.

```<code>    def create_app(config_class=Config):
        app = Flask(__name__)
        with app.app_context():
            from app import routes
</code>```

Then like the person posted above.
for routes.py change all the @app to @current_app

```<code>    from flask import current_app
    @current_app.route('/')
    @current_app.route('/index', methods=['GET', 'POST'])
    @login_required
    def index():
</code>```

this works for me.

Body:
My flask app is based on Miguel Grinberg's mega tutorial XIV with some extra stuff and it was all working fine and could be accessed from browser on localhost:5000. I decided to switch to an application factory approach as per Grinberg's XV tutorial BUT with no blueprints. Now when I enter localhost:5000 I get a URL not found. I am guessing my routes.py is not being picked up for some reason.

I have thoroughly worked through Grinberg's XV tutorial and the associated code and aligned everything less blueprints. These are the links I have explored that I have based my current app on: -

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure

http://flask.pocoo.org/docs/1.0/tutorial/factory/

Dave W Smith's answer in Configure Python Flask App to use "create_app" factory and use database in model class

and others.

From what I have read implementing an application factory should be really simple. The examples work.

The flask server starts from the command prompt in a venv as always.

Here is my directory structure.

myapp
    app.py
    config.py
    ...
    /app
        __init__.py
        routes.py
        models.py
        forms.py
        ...

Here is the code slightly simplified for clarity.

# app.py
#=============================================
from app import create_app, db
from app.models import User, Post

app = create_app()

@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'User': User, 'Post' :Post}

# __init__.py
#=============================================
...
import os
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
...
from config import Config

db = SQLAlchemy()
migrate = Migrate()
...

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    ...

    # logging, email servers, etc configured

    return app

from app import models

# routes.py
#=============================================
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, \
    jsonify, current_app
...
from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm,
     PostForm,ResetPassword,RequestForm, ResetPasswordForm
from app.models import User, Post
...

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    form = PostForm()
    if form.validate_on_submit():
        ...
    page = request.args.get('page', 1, type=int)
    ...
    return render_template('index.html', title=_('Home'), form=form,
                           posts=posts.items, next_url=next_url,
                           prev_url=prev_url)

@app.route ....

# models.py
#=============================================
from datetime import datetime
from hashlib import md5
from time import time
from flask import current_app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
from app import db, login

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    ...

This may be irrelevant but it is one thing I tried. Note in routes.py that I have from app import app, db, if I remove app and add from flask import current_app then the @app  decorators show as undefined.

Another point, because its a problem with routes. If I change the last line of __init__.py to from app import routes, models I get a different error.

flask.cli.NoAppException
flask.cli.NoAppException: While importing "metapplica", an ImportError was raised:

Traceback (most recent call last):
  File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\cli.py", line 236, in locate_app
    __import__(module_name)
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\metapplica.py", line 1, in <module>
    from app import create_app, db, cli
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\__init__.py", line 75, in <module>
    from app import routes, models
  File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\routes.py", line 8, in <module>
    from app import app, db
ImportError: cannot import name 'app' from 'app' (C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\__init__.py)

It was this error that led me to try the current_app change mentioned above.

I start the app like this.

cd C:\Users\...\myapp
venv\Scripts\activate
set FLASK_APP=app.py
set FLASK_DEBUG=1
flask run

I know the problem is probably really basic but can anyone see why the above code would give a URL not found or not be able to find the routes?

=== NEXT PHASE ================
Following the recommendations from @silver below my new names are: -

myapp
    runapp.py
    ...
    /mapp
        __init__.py
        ...

I went through all my code and changed from app[.xxx] import yyy to from myapp[.xxx] import yyy. This flushed out a few new errors where I was referencing app which I fixed by substituting current_app.
My new error is

RuntimeError
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

Traceback (most recent call last)
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\runapp.py", line 1, in <module>
from mapp import create_app, db, cli
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\mapp\__init__.py", line 75, in <module>
from mapp import routes, models
File "C:\Users\Mark Kortink\Dropbox\Python\projects\myapp\mapp\routes.py", line 16, in <module>
@current_app.before_request

Body:
I just ran into this issue too with Miguel Grinberg's tutorial. It's a pretty fantastic tutorial till some of the later sections which feel rushed.

Anyway.
You need to pass the context.
In the factory function you need to do.

    def create_app(config_class=Config):
        app = Flask(__name__)
        with app.app_context():
            from app import routes

Then like the person posted above.
for routes.py change all the @app to @current_app

    from flask import current_app
    @current_app.route('/')
    @current_app.route('/index', methods=['GET', 'POST'])
    @login_required
    def index():

this works for me.


问:
How to test an endpoint exception using flask and pytest?
I have an endpoint that returns a list from my database. If something goes wrong along the way, I return an internal_server_error, which has 500 status_code and a message as a parameter.

def get_general_ranking():
    try:
        ranking_list = GamificationService.get_general_ranking()
        return basic_response(ranking_list, 200)
    except Exception as e:
        logging.error(str(e))
        cache.delete()
        return internal_server_error_response('Could not get ranking. Check log for reasons.')
```

<p>I am implementing an unit test to this endpoint. So, right now, I have this implementation:</p>

<pre class="lang-py prettyprint-override"><code>class TestGamificationController(unittest.TestCase):

    def setUp(self):
        """
        Function called when the class is initialized.
        """
        test_app = app.test_client()
        self.general_ranking = test_app.get('/v1/gamification/general_ranking')

    def test_endpoint_general_ranking(self):
        """
        Testing the endpoint '/v1/gamification/general_ranking'.
        """
        assert self.general_ranking.status_code == 200, "Wrong status code."
        assert len(self.general_ranking.json) > 0, "/v1/gamification/general_ranking is returning an empty list."
        assert self.general_ranking.content_type == 'application/json', "Wrong content_type"
</code>```

But, as you can see below, when I run the test with coverage to check if I am covering 100% of my code, I get 75%. The missing lines are the exception ones.

```<code>---------- coverage: platform darwin, python 3.8.0-final-0 -----------
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
api/controller/GamificationController.py      16      4    75%   18-21

</code>```

Missing lines:

    except Exception as e:
        logging.error(str(e))
        cache.delete()
        return internal_server_error_response('Could not get ranking. Check log for reasons.')
```

How can I cover this exception too using pytest? Or should I use something else?

答:
I see three possible fixes for this:

Create a custom route in your app that just raises said exception.

Programmatically add this custom route in your app when you start your tests.

Move your global error handler function to its own file and ignore it from your coverage.

Now personally 1 is the easiest with just applying a debug/dev environment check that just throws a route not found error if it's off.

2 is doable if you use your Flask app factory to generate an app and generate the custom route all on the test execution although I'm not sure if this is enough to pass the AssertionError that Flask throws if you make any modification to its app routes after the first request is received. Which is usually the case when you instantiate your app on your conftest.py.

3 is kind of cheating I suppose.

Hope you got this sorted out. Would like to know how you solved this.

Update: The best way I've found in doing this is by using the sessionstart hook of pytest that runs before any tests. I use this to initialize the custom error endpoints. This approach works best since you won't have to pollute the codebase with test-specific logic.

Body:
I have an endpoint that returns a list from my database. If something goes wrong along the way, I return an internal_server_error, which has 500 status_code and a message as a parameter.

def get_general_ranking():
    try:
        ranking_list = GamificationService.get_general_ranking()
        return basic_response(ranking_list, 200)
    except Exception as e:
        logging.error(str(e))
        cache.delete()
        return internal_server_error_response('Could not get ranking. Check log for reasons.')

I am implementing an unit test to this endpoint. So, right now, I have this implementation:

class TestGamificationController(unittest.TestCase):

    def setUp(self):
        """
        Function called when the class is initialized.
        """
        test_app = app.test_client()
        self.general_ranking = test_app.get('/v1/gamification/general_ranking')

    def test_endpoint_general_ranking(self):
        """
        Testing the endpoint '/v1/gamification/general_ranking'.
        """
        assert self.general_ranking.status_code == 200, "Wrong status code."
        assert len(self.general_ranking.json) > 0, "/v1/gamification/general_ranking is returning an empty list."
        assert self.general_ranking.content_type == 'application/json', "Wrong content_type"

But, as you can see below, when I run the test with coverage to check if I am covering 100% of my code, I get 75%. The missing lines are the exception ones.

---------- coverage: platform darwin, python 3.8.0-final-0 -----------
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
api/controller/GamificationController.py      16      4    75%   18-21

Missing lines:

    except Exception as e:
        logging.error(str(e))
        cache.delete()
        return internal_server_error_response('Could not get ranking. Check log for reasons.')

How can I cover this exception too using pytest? Or should I use something else?


问:
SQL check or uniqueness in one column in multipe tables
I have a 'unique' column, 'GID_New' that is in multiple tables. Is there a way to check if it's unique across all the tables in the QGIS project in SQL?

Can it be done in one SQL search without merging the tables into one and then running something like

```<code>SELECT A.GID_New, count(*), A.TableName
FROM "Water_Merged" as A
Group by A.GID_New
</code>```

And then checking for a count >1

I would like to know which table the non-unique GID_New's are from as well.

The data is in a geopackage in QGIS so the code needs to work in QGIS SQL implementation.

答:
You can use union all:

```<code>select gid_new, count(*) no_matches
from (
    select gid_new from table1
    union all select gid_new from table2
    union all select gid_new from table3
) t
group by gid
having count(*) > 1
</code>```

If you want to know in which table duplicates exists, then one option is string concatenation. Assuming that your database uses string_agg(), that would look like:

```<code>select gid_new, count(*) no_matches, string_agg(which, ',') which_tables
from (
    select 'table1' which, gid_new from table1
    union all select 'table2', gid_new from table2
    union all select 'table3', gid_new from table3
) t
group by gid
having count(*) > 1
</code>```

Body:
I have a 'unique' column, 'GID_New' that is in multiple tables. Is there a way to check if it's unique across all the tables in the QGIS project in SQL?

Can it be done in one SQL search without merging the tables into one and then running something like

SELECT A.GID_New, count(*), A.TableName
FROM "Water_Merged" as A
Group by A.GID_New

And then checking for a count >1

I would like to know which table the non-unique GID_New's are from as well.

The data is in a geopackage in QGIS so the code needs to work in QGIS SQL implementation.

Body:
You can use union all:

select gid_new, count(*) no_matches
from (
    select gid_new from table1
    union all select gid_new from table2
    union all select gid_new from table3
) t
group by gid
having count(*) > 1

If you want to know in which table duplicates exists, then one option is string concatenation. Assuming that your database uses string_agg(), that would look like:

select gid_new, count(*) no_matches, string_agg(which, ',') which_tables
from (
    select 'table1' which, gid_new from table1
    union all select 'table2', gid_new from table2
    union all select 'table3', gid_new from table3
) t
group by gid
having count(*) > 1


问:
how to wait for input at end when running / debugging c++ in visual studio
I am looking to compete in the Google KickStart programming competition. I am using C++ in Visual Studio. (not visual studio code) Input parameters are given here as Console arguments, where they can be read with std::cin.

I want to paste the test input parameters into a text file and have the IDE pass them to the program as console arguments (held in the cin buffer). I have done this as defined here

But with this method the command line window will close immediately after the program finishes instead of asking for any key to be pressed. I have tried waiting for dummy input but this does not fix the closing error

答:
You may easily implement your own wait "Press enter to continue..." at the end of your routine for testing.</p>

```<code>int main(int argc, char** argv)
{
...
    int _tmp;
    std::cout << "Press enter to continue..." << std::endl;
    std::cin >> _tmp;
    return 0;
}
</code>```

Body:
You may easily implement your own wait "Press enter to continue..." at the end of your routine for testing.

int main(int argc, char** argv)
{
...
    int _tmp;
    std::cout << "Press enter to continue..." << std::endl;
    std::cin >> _tmp;
    return 0;
}


问:
Full screen tkinter canvas python
Hello how can I make a full screen tkinter.Canvas? Can you help me? This is my code:

```<code>import tkinter
import datetime
import sys
import os

uvodcanvas = tkinter.Canvas(width=400,height=200,bg="white")
uvodcanvas.pack()

tkinter.mainloop()
</code>```

答:
You need to make your main window full-screen, then configure the canvas to occupy the whole main window:</p>

```<code>import tkinter as tk

root = tk.Tk()
root.attributes('-fullscreen', True) # make main window full-screen

canvas = tk.Canvas(root, bg='white', highlightthickness=0)
canvas.pack(fill=tk.BOTH, expand=True) # configure canvas to occupy the whole main window

root.mainloop()
</code>```

Title: Full screen tkinter canvas python

Body:
Hello how can I make a full screen tkinter.Canvas? Can you help me? This is my code:

import tkinter
import datetime
import sys
import os

uvodcanvas = tkinter.Canvas(width=400,height=200,bg="white")
uvodcanvas.pack()

tkinter.mainloop()

Body:
You need to make your main window full-screen, then configure the canvas to occupy the whole main window:

import tkinter as tk

root = tk.Tk()
root.attributes('-fullscreen', True) # make main window full-screen

canvas = tk.Canvas(root, bg='white', highlightthickness=0)
canvas.pack(fill=tk.BOTH, expand=True) # configure canvas to occupy the whole main window

root.mainloop()


问:
Text comparison based on numbers/digits
I would need to compare texts by extracting only numbers from the following two texts:

```<code>text_1="source="The previous low was 27,523, recorded in May 1900. The 1.35 trillion ($22.5 million ) program could start in October. The number of people who left the country plunged 99.8 percent from a year earlier to 2,750, according to the data from the agency."

text_2="The subsidies, totalling 1.35tn, are expected to form part of a second budget. New plans to allocate $22.5 billion to a new reimbursement programme."
</code>```

However, it seems also to be relevant the next words (for example trillion /tn, billion).
Do you know how I could get this information?

I have tried with

```<code>t_1=[int(s) for s in text_1.split() if s.isdigit()]
t_2=[int(s) for s in text_2.split() if s.isdigit()]
</code>```

then to compare them, but it gives me not all numbers in texts.

Expected output:

```<code>differences

text_1: {27,523, 1900, 99.8, 2,750}

text_2: {}

common
    {1.35,22.5}
</code>```

答:
It is not impossible to it do the way you propose, but that is best achieved with regular expressions:

```<code>import re

text_1="The previous low was 27,523, recorded in May 1900. The 1.35 trillion ($22.5 million ) program could start in October. The number of people who left the country plunged 99.8 percent from a year earlier to 2,750, according to the data from the agency."

print(re.findall("\d+[,.\d]\d+", text_1))
</code>```

In case you are not familiar with it, check cheatsheet and try it with tester. Once you got that, it is straight forward to get your expected output:

```<code>nums_1 = re.findall("\d+[,.\d]\d+", text_1)
nums_2 = re.findall("\d+[,.\d]\d+", text_2)

common_nums = []
for num in nums_1:
  if num in nums_2: common_nums.append(num)

print(common_nums)
</code>```

Title: Text comparison based on numbers/digits

Body:
I would need to compare texts by extracting only numbers from the following two texts:

text_1="source="The previous low was 27,523, recorded in May 1900. The 1.35 trillion ($22.5 million ) program could start in October. The number of people who left the country plunged 99.8 percent from a year earlier to 2,750, according to the data from the agency."

text_2="The subsidies, totalling 1.35tn, are expected to form part of a second budget. New plans to allocate $22.5 billion to a new reimbursement programme."

However, it seems also to be relevant the next words (for example trillion /tn, billion).
Do you know how I could get this information?

I have tried with

t_1=[int(s) for s in text_1.split() if s.isdigit()]
t_2=[int(s) for s in text_2.split() if s.isdigit()]

then to compare them, but it gives me not all numbers in texts.

Expected output:

differences

text_1: {27,523, 1900, 99.8, 2,750}

text_2: {}

common
    {1.35,22.5}

Body:
It is not impossible to it do the way you propose, but that is best achieved with regular expressions:

import re

text_1="The previous low was 27,523, recorded in May 1900. The 1.35 trillion ($22.5 million ) program could start in October. The number of people who left the country plunged 99.8 percent from a year earlier to 2,750, according to the data from the agency."

print(re.findall("\d+[,.\d]\d+", text_1))

In case you are not familiar with it, check cheatsheet and try it with tester. Once you got that, it is straight forward to get your expected output:

nums_1 = re.findall("\d+[,.\d]\d+", text_1)
nums_2 = re.findall("\d+[,.\d]\d+", text_2)

common_nums = []
for num in nums_1:
  if num in nums_2: common_nums.append(num)

print(common_nums)


问:
why doesnt everyone use frameworks
well lot of forums and even this site is full of questions where people don't use any framework(whetever language they use) and they are stuck on code for common tasks like logins,database accesses,etc while frameworks provide code that works correctly for these routine tasks. Then why do people still go without frameworks? i want to know this because i am trying to build something of substantial scale so i was deciding if i really need a framework or a homegrown solution would be better? a homegrown solution can be a great learning experience but is there something more to it? </p>

答:
Some reasons:

Some tasks are so small that it's easier to do them without a framework, which:

would have to be bundled;

would take up an order of magnitude more space than the app itself;

would impose a lot of requirements both for the app and the hosting platform;

would provide unnecessary overhead because of a lot of features which are unused in the particular app;

Wanting to find out about how things work;

Homework assignments;

Not being able to use the framework for some reason (constrained space, not enough permissions, etc.)

Not knowing about these frameworks;

Reducing dependencies on external libraries;

Legacy reasons (the app is old, it was started before any serious frameworks were out);

Title: why doesnt everyone use frameworks


问:
How to install latest python version for SQL Server
I have installed SQL Server 2017 with Python but it came with Python 3.5.2 and Anaconda 4.2.0. Is there a way to upgrade the Python to 3.7?

This is the only official document I found and tried

https://learn.microsoft.com/en-us/sql/advanced-analytics/r/use-sqlbindr-exe-to-upgrade-an-instance-of-sql-server?view=sql-server-2017 but even this installed 3.5

Please help.

Thanks,
Avinash

答:
It may be easiest to open https://www.python.org/downloads/ and install the latest release. If you have Visual Studio 2017/2019, open the solution explorer, open your python project (or import a new one into a Python Application) and point your application to this latest version. Either way, the latest version will exist on the machine. Note that some versions may be 32 bit and not 64 bit.
PyCharm Community Edition is another option.</p>


问:
protection in v8 of google app script fails
I have this code which was working ok till I have allowed the google app script to upgrade to v8.
This code is used for adding another user programatically.

```<code>var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.addEditor(eMailID);
</code>```

in v8 it gives me the following error.

```<code>[20-06-01 06:12:16:027 IST] Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Protection.addEditor.
at EnableShare(EnableAccess:51:18)
</code>```

Important observation is that when I disable the runtime v8 and switch to the earlier version, code gets executed without any error and the spreadsheet adds the eMailID as another editor.

Any corrections in the syntax in the new version?

答:
How about this modification?

From your explanation, in your script, if eMailID is an array, I think that when V8 is enabled, such error occurs. So how about the following modification?

From:

```<code>protection.addEditor(eMailID);
</code>```

To:

```<code>protection.addEditor(eMailID[0]);
</code>```

or

```<code>protection.addEditors(eMailID);
</code>```

Note:

In this modification, it supposes that eMailID is an array like ["###email address###"].

References:

addEditor(user)

addEditors(emailAddresses)

Body:
I have this code which was working ok till I have allowed the google app script to upgrade to v8.
This code is used for adding another user programatically.

var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.addEditor(eMailID);

in v8 it gives me the following error.

[20-06-01 06:12:16:027 IST] Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Protection.addEditor.
at EnableShare(EnableAccess:51:18)

Important observation is that when I disable the runtime v8 and switch to the earlier version, code gets executed without any error and the spreadsheet adds the eMailID as another editor.

Any corrections in the syntax in the new version?

Body:
How about this modification?

From your explanation, in your script, if eMailID is an array, I think that when V8 is enabled, such error occurs. So how about the following modification?

From:

protection.addEditor(eMailID);

To:

protection.addEditor(eMailID[0]);

or

protection.addEditors(eMailID);

Note:

In this modification, it supposes that eMailID is an array like ["###email address###"].

References:

addEditor(user)

addEditors(emailAddresses)


问:
dhall-to-yaml funtion Text output is being output in double quotes
I have the following function which its output get enclosed with double quotes when processed via dhall-to-yaml yet a static string injected in a record is not enclosed in quotes, how can I control what get enclosed in double quotes and what doesn't?

```<code>let base64 = \(encode : Text) -> "!Base64 ${encode}"
let john : Profile =
    { person =
        { name = base64 "test"
        , age  = 67
        }
    , address =
        { country = "United States"
        , state   = "Pennsylvania"
        , city    = "Philadelphia"
        }
    }
</code>```

Output

```<code>address:
  city: Philadelphia
  country: United States
  state: Pennsylvania
person:
  age: 67
  name: "!Base64 test"
</code>```

Desired Output:

```<code>address:
  city: Philadelphia
  country: United States
  state: Pennsylvania
person:
  age: 67
  name: !Base64 test
</code>```

答:
Currently the dhall-to-yaml and dhall-to-yaml-ng commands quote string fields if they have special characters in order to ensure that Dhall Text values can only be interpreted as plain data when converted to YAML.  Also, there is not yet an option to omit the quoting behavior if you desire unescaped text (such as for emitting tags), nor is there a standard way to specify tags, either.

You might want to open an issue at https://github.com/dhall-lang/dhall-haskell/issues to discuss possible ways to resolve your problem since I imagine you're not the only one who would like to emit tags in the YAML output.

Body:
I have the following function which its output get enclosed with double quotes when processed via dhall-to-yaml yet a static string injected in a record is not enclosed in quotes, how can I control what get enclosed in double quotes and what doesn't?

let base64 = \(encode : Text) -> "!Base64 ${encode}"
let john : Profile =
    { person =
        { name = base64 "test"
        , age  = 67
        }
    , address =
        { country = "United States"
        , state   = "Pennsylvania"
        , city    = "Philadelphia"
        }
    }

Output

address:
  city: Philadelphia
  country: United States
  state: Pennsylvania
person:
  age: 67
  name: "!Base64 test"

Desired Output:

address:
  city: Philadelphia
  country: United States
  state: Pennsylvania
person:
  age: 67
  name: !Base64 test


问:
Nginx cache file by mime type
I use nginx as frontend, apache as backend. I need cache pictures, but by default nginx is caching file by extentions. Apache takes pictures from db and send it without extentions. Can nginx cache files by mime type and how?</p>

答:
You need something like this.</p>

```<code>if ($upstream_http_content_type ~* "image/") {
    DEFINE_YOUR_CACHE_SETTINGS
}
</code>```

Title: Nginx cache file by mime type

Body:
You need something like this.

if ($upstream_http_content_type ~* "image/") {
    DEFINE_YOUR_CACHE_SETTINGS
}


问:
R find intervals in data.table
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

```<code>x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))
</code>```

I have already the breakpoint or rowindices:

```<code>pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))
</code>```

Here i can find the interval for group "A" with:

```<code>findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)
</code>```

How can i do this for each group. In this case "A" and "B"?

答:
We can nest the pos data into list by b and join with x and use findInterval to get corresponding groups.

```<code>library(dplyr)

pos %>%
   tidyr::nest(data = bp) %>%
   right_join(x, by = 'b') %>%
   group_by(b) %>%
   mutate(interval = findInterval(a, data[[1]][[1]])) %>%
   select(-data)

#    b        a interval
#   <chr> <int>    <int>
# 1 A         1        0
# 2 A         2        0
# 3 A         3        1
# 4 A         4        1
# 5 A         5        2
# 6 A         6        2
# 7 A         7        2
# 8 A         8        2
# 9 B         1        0
#10 B         2        1
#11 B         3        1
#12 B         4        2
#13 B         5        2
#14 B         6        2
#15 B         7        2
#16 B         8        2
</code>```

Title: R find intervals in data.table

Body:
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))

I have already the breakpoint or rowindices:

pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))

Here i can find the interval for group "A" with:

findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)

How can i do this for each group. In this case "A" and "B"?

Body:
We can nest the pos data into list by b and join with x and use findInterval to get corresponding groups.

library(dplyr)

pos %>%
   tidyr::nest(data = bp) %>%
   right_join(x, by = 'b') %>%
   group_by(b) %>%
   mutate(interval = findInterval(a, data[[1]][[1]])) %>%
   select(-data)

#    b        a interval
#   <chr> <int>    <int>
# 1 A         1        0
# 2 A         2        0
# 3 A         3        1
# 4 A         4        1
# 5 A         5        2
# 6 A         6        2
# 7 A         7        2
# 8 A         8        2
# 9 B         1        0
#10 B         2        1
#11 B         3        1
#12 B         4        2
#13 B         5        2
#14 B         6        2
#15 B         7        2
#16 B         8        2


问:
Using Java Stream API, finding highest value of variable, with the stream of the changes made to the variable

Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

```<code>enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}
</code>```

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

```<code>// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0
</code>```

Bob's highest balance is 1700.

答:
Here is another Stream solution:</p>

```<code>    AtomicInteger balance = new AtomicInteger(0);
    int highestBalance = transactions
            .stream()
            .mapToInt(transaction -> {
                int amount = transaction.getAmount();
                if (transaction.getAction() == TransactionAction.WITHDRAW) {
                    amount = -amount;
                }
                return balance.accumulateAndGet(amount, Integer::sum);
            })
            .max()
            .orElse(0);
</code>```

Body:
Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0

Bob's highest balance is 1700.

Body:
Here is another Stream solution:

    AtomicInteger balance = new AtomicInteger(0);
    int highestBalance = transactions
            .stream()
            .mapToInt(transaction -> {
                int amount = transaction.getAmount();
                if (transaction.getAction() == TransactionAction.WITHDRAW) {
                    amount = -amount;
                }
                return balance.accumulateAndGet(amount, Integer::sum);
            })
            .max()
            .orElse(0);


问:
Exception rasied when signing message with RSA key
I've been getting the following error message on macOS and Ubuntu when trying to sign a message with a rsa key and BLAKE2b hash.

```<code>InternalError: Unknown OpenSSL error. This error is commonly encountered
when another library is not cleaning up the OpenSSL error stack. If you
are using cryptography with another library that uses OpenSSL try
disabling it before reporting a bug. Otherwise please file an issue at
https://github.com/pyca/cryptography/issues with information on how to
reproduce this. ([])
</code>```

I'm kinda lost as to where to start debugging this. Is there something I'm missing here? Can you not use BLAKE2b hashing with rsa signing?

```<code>In [1]: from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import padding, rsa

In [2]: private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=4096,
            backend=default_backend()
        )

In [3]: message = b'The quick brown fox jumps over the lazy dog'
        signature = private_key.sign(
            message,
            padding.PSS(
                mgf=padding.MGF1(hashes.BLAKE2b(64)),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.BLAKE2b(64)
        )
</code>```

Traceback

```<code><ipython-input-3-6b4492bdbf5d> in <module>()
      6         salt_length=padding.PSS.MAX_LENGTH
      7     ),
----> 8     hashes.BLAKE2b(64)
      9 )

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in sign(self, data, padding, algorithm)
    413             self._backend, data, algorithm
    414         )
--> 415         return _rsa_sig_sign(self._backend, padding, algorithm, self, data)
    416
    417

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in _rsa_sig_sign(backend, padding, algorithm, private_key, data)
    220     pkey_ctx = _rsa_sig_setup(
    221         backend, padding, algorithm, private_key, data,
--> 222         backend._lib.EVP_PKEY_sign_init
    223     )
    224     buflen = backend._ffi.new("size_t *")

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in _rsa_sig_setup(backend, padding, algorithm, key, data, init_func)
    191     padding_enum = _rsa_sig_determine_padding(backend, key, padding, algorithm)
    192     evp_md = backend._lib.EVP_get_digestbyname(algorithm.name.encode("ascii"))
--> 193     backend.openssl_assert(evp_md != backend._ffi.NULL)
    194     pkey_ctx = backend._lib.EVP_PKEY_CTX_new(key._evp_pkey, backend._ffi.NULL)
    195     backend.openssl_assert(pkey_ctx != backend._ffi.NULL)

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py in openssl_assert(self, ok)
    104
    105     def openssl_assert(self, ok):
--> 106         return binding._openssl_assert(self._lib, ok)
    107
    108     def activate_builtin_random(self):

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/bindings/openssl/binding.py in _openssl_assert(lib, ok)
     73             "issues with information on how to reproduce "
     74             "this. ({0!r})".format(errors_with_text),
---> 75             errors_with_text
     76         )
     77
</code>```

答: if your python version is 3.7, try to pip install cryptography==2.7

Body:
I've been getting the following error message on macOS and Ubuntu when trying to sign a message with a rsa key and BLAKE2b hash.

InternalError: Unknown OpenSSL error. This error is commonly encountered
when another library is not cleaning up the OpenSSL error stack. If you
are using cryptography with another library that uses OpenSSL try
disabling it before reporting a bug. Otherwise please file an issue at
https://github.com/pyca/cryptography/issues with information on how to
reproduce this. ([])

I'm kinda lost as to where to start debugging this. Is there something I'm missing here? Can you not use BLAKE2b hashing with rsa signing?

In [1]: from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import padding, rsa

In [2]: private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=4096,
            backend=default_backend()
        )

In [3]: message = b'The quick brown fox jumps over the lazy dog'
        signature = private_key.sign(
            message,
            padding.PSS(
                mgf=padding.MGF1(hashes.BLAKE2b(64)),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.BLAKE2b(64)
        )

Traceback

<ipython-input-3-6b4492bdbf5d> in <module>()
      6         salt_length=padding.PSS.MAX_LENGTH
      7     ),
----> 8     hashes.BLAKE2b(64)
      9 )

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in sign(self, data, padding, algorithm)
    413             self._backend, data, algorithm
    414         )
--> 415         return _rsa_sig_sign(self._backend, padding, algorithm, self, data)
    416
    417

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in _rsa_sig_sign(backend, padding, algorithm, private_key, data)
    220     pkey_ctx = _rsa_sig_setup(
    221         backend, padding, algorithm, private_key, data,
--> 222         backend._lib.EVP_PKEY_sign_init
    223     )
    224     buflen = backend._ffi.new("size_t *")

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py in _rsa_sig_setup(backend, padding, algorithm, key, data, init_func)
    191     padding_enum = _rsa_sig_determine_padding(backend, key, padding, algorithm)
    192     evp_md = backend._lib.EVP_get_digestbyname(algorithm.name.encode("ascii"))
--> 193     backend.openssl_assert(evp_md != backend._ffi.NULL)
    194     pkey_ctx = backend._lib.EVP_PKEY_CTX_new(key._evp_pkey, backend._ffi.NULL)
    195     backend.openssl_assert(pkey_ctx != backend._ffi.NULL)

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py in openssl_assert(self, ok)
    104
    105     def openssl_assert(self, ok):
--> 106         return binding._openssl_assert(self._lib, ok)
    107
    108     def activate_builtin_random(self):

/usr/local/lib/python3.6/site-packages/cryptography/hazmat/bindings/openssl/binding.py in _openssl_assert(lib, ok)
     73             "issues with information on how to reproduce "
     74             "this. ({0!r})".format(errors_with_text),
---> 75             errors_with_text
     76         )
     77


问:
MongoDB c# driver: Case Insensitive Compare using in or contains on a list using linq
I am using the MongoDB C# driver and I want to do a linq where clause on the collection that compares the lower cased version of a property to the lower case version of a list I have in memory. like this;

```<code>items = items.Where(i => listToCheck.Contains(i.Property.ToLower()));
</code>```

I have also tried...

```<code>items = items.Where(i => i.Property.ToLower().In(listToCheck));
</code>```

I think that this is actually correct and should work but possibly hasn't been implemented.

I get an error saying 'Unsupported where clause' relating to the ToLower() command. From what I can see the driver currently can't accomplish this because it would have to do an 'IN' query with Regex which I can't see being possible.

What I would like to know is if it is possible and if so, how?

答:
I ran across this same problem, and had to piece together a solution from several different SO answers, including this one.

I was already using IQueryable everywhere in the solution, along with a repository pattern, so I really didn't want to drop back to using .Find()

My solution was to extend the filter definition builder with a three-parameter .In() overload which would provide case insensitivity. Then, I use .Where(_ => filter.Inject()) to add the filter to the query, while still keeping it as IQueryable.

The extension:

```<code>public static class MongoExtensions
{
    public static FilterDefinition<TDocument> In<TDocument>(
        this FilterDefinitionBuilder<TDocument> builder,
        Expression<Func<TDocument, object>> expr,
        IEnumerable<string> values,
        bool ignoreCase)
    {
        if (!ignoreCase)
        {
            return builder.In(expr, values);
        }

        var filters = values
            .Select(v => builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i")));

        return builder.Or(filters);
    }
}
</code>```

With the original code from the question, it would look something like:

```<code>var filter = Builders<MyCollection>.Filter.In(i => i.Property, listToCheck, true);
items = items.Where(_ => filter.Inject());
</code>```

Body:
I am using the MongoDB C# driver and I want to do a linq where clause on the collection that compares the lower cased version of a property to the lower case version of a list I have in memory. like this;

items = items.Where(i => listToCheck.Contains(i.Property.ToLower()));

I have also tried...

items = items.Where(i => i.Property.ToLower().In(listToCheck));

I think that this is actually correct and should work but possibly hasn't been implemented.

I get an error saying 'Unsupported where clause' relating to the ToLower() command. From what I can see the driver currently can't accomplish this because it would have to do an 'IN' query with Regex which I can't see being possible.

What I would like to know is if it is possible and if so, how?

Body:
I ran across this same problem, and had to piece together a solution from several different SO answers, including this one.

I was already using IQueryable everywhere in the solution, along with a repository pattern, so I really didn't want to drop back to using .Find()

My solution was to extend the filter definition builder with a three-parameter .In() overload which would provide case insensitivity. Then, I use .Where(_ => filter.Inject()) to add the filter to the query, while still keeping it as IQueryable.

The extension:

public static class MongoExtensions
{
    public static FilterDefinition<TDocument> In<TDocument>(
        this FilterDefinitionBuilder<TDocument> builder,
        Expression<Func<TDocument, object>> expr,
        IEnumerable<string> values,
        bool ignoreCase)
    {
        if (!ignoreCase)
        {
            return builder.In(expr, values);
        }

        var filters = values
            .Select(v => builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i")));

        return builder.Or(filters);
    }
}

With the original code from the question, it would look something like:

var filter = Builders<MyCollection>.Filter.In(i => i.Property, listToCheck, true);
items = items.Where(_ => filter.Inject());


问:
How to handle NavigationView PaneFooter Settings item click
When adding a NavigationView a 'Settings' item is automatically added at the bottom of the NavigationView. How can a click event be added to this item since it doesn't appear to be accessible from XAML?

```<code><Page
    x:Class="My_Project.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <NavigationView>
            <NavigationView.PaneFooter>
            </NavigationView.PaneFooter>
        </NavigationView>
    </Grid>
</Page>
</code>```

答:
How can a click event be added to this item since it doesn't appear to be accessible from XAML?

The Settings button click event is already handled by the NavigationView.ItemInvoked Event. This is mentioned in the document NavigationView as "When the user taps on a navigation item, the navigation view shows that item as selected and raises an ItemInvoked event. "

So you just need to handle the NavigationView.ItemInvoked Event and check the NavigationViewItemInvokedEventArgs.IsSettingsInvoked Property.

Here is the code that you could refer to:

```<code> <Grid>
    <NavigationView ItemInvoked="NavigationView_ItemInvoked">
        <NavigationView.PaneFooter>
        </NavigationView.PaneFooter>
    </NavigationView>
</Grid>
</code>```

In code behind:

```<code> private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
    {
        if (args.IsSettingsInvoked == true)
        {
           //do something

        }
    }
</code>```

Update

If you want to check if the item is a specific one, you could set a tag property in the Xaml for the navigationview item and then check this property in the  ItemInvoked event.

In xaml:

```<code> <NavigationViewItem Tag="home" Icon="Home" Content="Home"/>
</code>```

In code behind:

```<code>  private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
    {
        var navItemTag = args.InvokedItemContainer.Tag.ToString();
        if (navItemTag.Equals("home"))
        {
            // do something
            Debug.WriteLine("test");
        }
    }
</code>```

Body:
When adding a NavigationView a 'Settings' item is automatically added at the bottom of the NavigationView. How can a click event be added to this item since it doesn't appear to be accessible from XAML?

<Page
    x:Class="My_Project.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <NavigationView>
            <NavigationView.PaneFooter>
            </NavigationView.PaneFooter>
        </NavigationView>
    </Grid>
</Page>

Body:
How can a click event be added to this item since it doesn't appear to be accessible from XAML?

The Settings button click event is already handled by the NavigationView.ItemInvoked Event. This is mentioned in the document NavigationView as "When the user taps on a navigation item, the navigation view shows that item as selected and raises an ItemInvoked event. "

So you just need to handle the NavigationView.ItemInvoked Event and check the NavigationViewItemInvokedEventArgs.IsSettingsInvoked Property.

Here is the code that you could refer to:

 <Grid>
    <NavigationView ItemInvoked="NavigationView_ItemInvoked">
        <NavigationView.PaneFooter>
        </NavigationView.PaneFooter>
    </NavigationView>
</Grid>

In code behind:

 private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
    {
        if (args.IsSettingsInvoked == true)
        {
           //do something

        }
    }

Update

If you want to check if the item is a specific one, you could set a tag property in the Xaml for the navigationview item and then check this property in the  ItemInvoked event.

In xaml:

 <NavigationViewItem Tag="home" Icon="Home" Content="Home"/>

In code behind:

  private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
    {
        var navItemTag = args.InvokedItemContainer.Tag.ToString();
        if (navItemTag.Equals("home"))
        {
            // do something
            Debug.WriteLine("test");
        }
    }