问:
Find pixel indices within a shape: Opencv and Python
Suppose I have a mask of a hollow, curved (and not necessarily convex) shape that I've received from my pre-processing steps:

I now want to try and select all pixels that occur inside that shape and add them to the mask, as so:

How can I do this in Python?

Code for generating the examples:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Parameters for creating the circle
COLOR_BLUE = (255, 0, 0)
IMAGE_SHAPE = (256, 256, 3)
CIRCLE_CENTER = tuple(np.array(IMAGE_SHAPE) // 2)[:-1]
CIRCLE_RADIUS = 30
LINE_THICKNESS = 5 # Change to -1 for example of filled circle

# Draw on a circle
img = np.zeros(IMAGE_SHAPE, dtype=np.uint8)
img_circle = cv2.circle(img, CIRCLE_CENTER, CIRCLE_RADIUS, COLOR_BLUE, LINE_THICKNESS)
circle_mask = img_circle[:, :, 0]

# Show the image
plt.axis("off")
plt.imshow(circle_mask)
plt.show()
```

答:
Use floodFill to fill the outside of the circle. Then use np.where to find the pixels within the circle

```<code>cv2.floodFill(circle_mask, None, (0, 0), 1)
np.where(circle_mask == 0)
</code>```

Body:
Use floodFill to fill the outside of the circle. Then use np.where to find the pixels within the circle

cv2.floodFill(circle_mask, None, (0, 0), 1)
np.where(circle_mask == 0)


来源: stackexchange

问:
Clear Fragment Backstack except top fragment
In my app I have some menu items in a Navigation Drawer. When the user taps one of these items and navigates to the corresponding fragment, I want the fragment backstack to be cleared EXCEPT for the fragment they just navigated to. Let me illustrate:

In my nav drawer the user has options to open fragments F1, F2, F3, F4, F5, F6. When the app is first opened, the user starts on F1. Let's say from F1, the user opens fragments F7 -> F8 -> F9 -> F10 using buttons within the fragment views themselves. At this point, the backstack looks like:

F1 -> F7 -> F8 -> F9 -> F10

Suppose from here, the user opens the nav drawer and selects F2. What I want to happen is that the above backstack is cleared and is populated with ONLY F2, so that they user can't go back to F10 from F2. In otherwords, the backstack should become:

Not this: F1 -> F7 -> F8 -> F9 -> F10 -> F2

But this: F2

How can I accomplish this?

EDIT 1:
One of my attempted solutions was to add an OnNavigationItemSelectedListener to the navigationView when the activity is loading that would clear the backstack when one of the items was pressed. My solution worked, but in the process I overrode the default code that actually changes to the new fragment. I snooped through the Android API and found this:

navigationView.setNavigationItemSelectedListener(
    new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        boolean handled = onNavDestinationSelected(item, navController);
        if (handled) {
            ViewParent parent = navigationView.getParent();
            if (parent instanceof DrawerLayout) {
                ((DrawerLayout) parent).closeDrawer(navigationView);
            } else {
                BottomSheetBehavior bottomSheetBehavior =
                                    findBottomSheetBehavior(navigationView);
                if (bottomSheetBehavior != null) {
                     bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        }
        return handled;
    }
});
```

This is NOT my code. This is the native code that handles selection of menu items on the navigation drawer (found in the NavigationUI class). If I want to add my own OnNavigationItemSelectedListener I would have to recreate the functionality shown above, which I can't do since some of the methods in there are protected. So that's why I don't believe this solution will work.

答:
I hope you are setting all this fragment in the same activity. If yes, then it will not be very hard to achieve whatever you want to achieve.

Make sure whenever you set your fragment in suppose MainActivity, follow this code.

```<code>val fragmentTransaction = supportFragmentManager.beginTransaction()
if (fragment == null) {
    fragment = Frag2.newInstance()
    fragmentTransaction.replace(R.id.container, fragment, Frag2.TAG)
} else {
    fragmentTransaction.show(fragment)
}
    fragmentTransaction.commit()
</code>```

Main logic to achieve required behaviour is behind fragmentTransaction.replace().
So, whenever you set another fragment in a container, use replace() rather than add().

So, try this and give me feedback about it.
Happy coding..!

ContentLicense: CC BY-SA 4.0

Body:
In my app I have some menu items in a Navigation Drawer. When the user taps one of these items and navigates to the corresponding fragment, I want the fragment backstack to be cleared EXCEPT for the fragment they just navigated to. Let me illustrate:

In my nav drawer the user has options to open fragments F1, F2, F3, F4, F5, F6. When the app is first opened, the user starts on F1. Let's say from F1, the user opens fragments F7 -> F8 -> F9 -> F10 using buttons within the fragment views themselves. At this point, the backstack looks like:

F1 -> F7 -> F8 -> F9 -> F10

Suppose from here, the user opens the nav drawer and selects F2. What I want to happen is that the above backstack is cleared and is populated with ONLY F2, so that they user can't go back to F10 from F2. In otherwords, the backstack should become:

Not this: F1 -> F7 -> F8 -> F9 -> F10 -> F2

But this: F2

How can I accomplish this?

EDIT 1:
One of my attempted solutions was to add an OnNavigationItemSelectedListener to the navigationView when the activity is loading that would clear the backstack when one of the items was pressed. My solution worked, but in the process I overrode the default code that actually changes to the new fragment. I snooped through the Android API and found this:

navigationView.setNavigationItemSelectedListener(
    new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        boolean handled = onNavDestinationSelected(item, navController);
        if (handled) {
            ViewParent parent = navigationView.getParent();
            if (parent instanceof DrawerLayout) {
                ((DrawerLayout) parent).closeDrawer(navigationView);
            } else {
                BottomSheetBehavior bottomSheetBehavior =
                                    findBottomSheetBehavior(navigationView);
                if (bottomSheetBehavior != null) {
                     bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        }
        return handled;
    }
});

This is NOT my code. This is the native code that handles selection of menu items on the navigation drawer (found in the NavigationUI class). If I want to add my own OnNavigationItemSelectedListener I would have to recreate the functionality shown above, which I can't do since some of the methods in there are protected. So that's why I don't believe this solution will work.

Body:
I hope you are setting all this fragment in the same activity. If yes, then it will not be very hard to achieve whatever you want to achieve.

Make sure whenever you set your fragment in suppose MainActivity, follow this code.

val fragmentTransaction = supportFragmentManager.beginTransaction()
if (fragment == null) {
    fragment = Frag2.newInstance()
    fragmentTransaction.replace(R.id.container, fragment, Frag2.TAG)
} else {
    fragmentTransaction.show(fragment)
}
    fragmentTransaction.commit()

Main logic to achieve required behaviour is behind fragmentTransaction.replace().
So, whenever you set another fragment in a container, use replace() rather than add().

So, try this and give me feedback about it.
Happy coding..!


问:
Determine the probability of all outcomes of rolling a loaded die twice in R
new to R. I have a standard 6-sided die loaded so that "4" is twice as likely as any other face, so my random variable would look something like:

X1 = {[1, 1/7], [2, 1/7], [3, 1/7], [4, 2/7], [5, 1/7], [6, 1/7]}

I would like to find the entire probability density function of a random variable (X2) that sums the result of two rolls (X1+X1), so the output would be X2 = {[2, 1/49], [3, 1/49], ... , [12, 1/49]}. The output can be a dataframe, table, or whatever you think is most appropriate.

I have attempted the following:

```<code>dice <- c(1,2,3,4,5,6)
probs <- c(1/7, 1/7, 1/7, 2/7, 1/7, 1/7)
c <- expand.grid(probs, probs)
d <- c[,1]*c[,2]
table(d)
</code>```

However, this obviously doesn't tie the resulting probabilities to their respective outcome. How would I go about doing that?

答:
Building on what you've already done, one way to proceed is: </p>

```<code>dice <- 1:6
probs <- c(1/7, 1/7, 1/7, 2/7, 1/7, 1/7)

df <- data.frame(
    val = apply(expand.grid(dice, dice), 1, sum),
    prob = apply(expand.grid(probs, probs), 1, prod)
)
# solution 1: using split()/lapply()
tmp <- split(df$prob, df$val) # check this out!
res <- lapply(tmp, sum)
## solution 3: using aggregate()
res <- aggregate(prob~val, df, sum)
</code>```

Body:
new to R. I have a standard 6-sided die loaded so that "4" is twice as likely as any other face, so my random variable would look something like:

X1 = {[1, 1/7], [2, 1/7], [3, 1/7], [4, 2/7], [5, 1/7], [6, 1/7]}

I would like to find the entire probability density function of a random variable (X2) that sums the result of two rolls (X1+X1), so the output would be X2 = {[2, 1/49], [3, 1/49], ... , [12, 1/49]}. The output can be a dataframe, table, or whatever you think is most appropriate.

I have attempted the following:

dice <- c(1,2,3,4,5,6)
probs <- c(1/7, 1/7, 1/7, 2/7, 1/7, 1/7)
c <- expand.grid(probs, probs)
d <- c[,1]*c[,2]
table(d)

However, this obviously doesn't tie the resulting probabilities to their respective outcome. How would I go about doing that?

Body:
Building on what you've already done, one way to proceed is:

dice <- 1:6
probs <- c(1/7, 1/7, 1/7, 2/7, 1/7, 1/7)

df <- data.frame(
    val = apply(expand.grid(dice, dice), 1, sum),
    prob = apply(expand.grid(probs, probs), 1, prod)
)
# solution 1: using split()/lapply()
tmp <- split(df$prob, df$val) # check this out!
res <- lapply(tmp, sum)
## solution 3: using aggregate()
res <- aggregate(prob~val, df, sum)


问:
Express Handlebars Won't Render Data
I am working with NodeJS and Express using Express-Handlebars template engine.

Handlebars is throwing the following error when trying to render a template:

Handlebars: Access has been denied to resolve the property "username"
  because it is not an  "own property" of its parent. You can add a
  runtime option to disable the check or this warning: See
  https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access
  for details

According to the above link:

From version 4.6.0 on, Handlebars forbids accessing prototype properties and methods of the context object by default. The reason are various security issues that arise from this possibility.

My app.js contains the following:

```<code>const exphbs = require('express-handlebars');
const express = require('express');
// Init Express
const app = express();
// VIEW ENGINE
app.engine('handlebars', exphbs({
  defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
</code>```

My route file fetches from MongoDB via Mongoose:

//@GET - View
router.get('/', authMiddleware, (req, res, next) => {
  // Mongoose
  Model.find({ user: req.user._id })
    .sort({ date: -1 })
    .then(model => {
      res.render('/overview', { model: model })
    })
    .catch(err => {
      if (err) throw err;
      req.flash('error_msg', 'No Model Found');
    })

})```

model is an array of objects

This issue only started happening after I began to mess around with adding handlebar helpers. I have removed the helpers and reverted to my original configuration settings (above) to no avail. I've tried deleting node_modules folder and reinstalling npm.

What's being sent is an array of objects, and I am trying to loop over the properties of the objects using the {{#each model}} helper and reference the individual properties via {{prop1}} within the each.

According to Handlebars, this disabling of proto properties is false by default, and this change shouldn't break anything.

My question:

Am I sending data to handlebars incorrectly? If so, what is the correct method (not exposing my server to security holes) to send data to the express-handlebars template for rendering?

Thank you in advance.

答:
I had the same issue when I upgraded the handlebars package. To get your system back online as quick as possible remove the handlebars entry in package.json  And then insert this line in its place.

```<code>"handlebars": "4.5.3",
</code>```

From version 4.6.0 onward Handlebars forbids accessing prototype properties and methods of the context object by default. This is related to a security issue described here:
https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html

Refer to
https://github.com/wycats/handlebars.js/issues/1642

An example from the above URL shows the Mongoose response converted into JSON:

```<code>app.get('/test', function (_req, res) {
    Kitten.find({}).then(kittens => {
        res.render('test.hbs', {
            kittens: kittens.map(kitten => kitten.toJSON())
        })
    })
});
</code>```

If you are certain that only trusted developers and no end users have access to the handlebars templates it's possible to allow prototype access by installing the following package:

```<code>npm install @handlebars/allow-prototype-access
</code>```

Here is an example of it's use:

```<code>const express = require('express');
const Handlebars = require('handlebars')
const expressHandlebars = require('express-handlebars');
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access')

const app = express();

app.engine('handlebars', expressHandlebars({
    handlebars: allowInsecurePrototypeAccess(Handlebars)
}));
app.set('view engine', 'handlebars');
...
</code>```

Another option is to use the mongoose .lean() function. This has the benefit of being much faster than a traditional mongoose query. But it does have some cons as well. By default, Mongoose queries return an instance of the Mongoose Document class. These objects contain a lot of internal state for change tracking and have additional methods such as .save(). Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just return the plain javascript object.

Title: Express Handlebars Won't Render Data

Body:
I am working with NodeJS and Express using Express-Handlebars template engine.

Handlebars is throwing the following error when trying to render a template:

Handlebars: Access has been denied to resolve the property "username"
  because it is not an  "own property" of its parent. You can add a
  runtime option to disable the check or this warning: See
  https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access
  for details

According to the above link:

From version 4.6.0 on, Handlebars forbids accessing prototype properties and methods of the context object by default. The reason are various security issues that arise from this possibility.

My app.js contains the following:

const exphbs = require('express-handlebars');
const express = require('express');
// Init Express
const app = express();
// VIEW ENGINE
app.engine('handlebars', exphbs({
  defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');

My route file fetches from MongoDB via Mongoose:

//@GET - View
router.get('/', authMiddleware, (req, res, next) => {
  // Mongoose
  Model.find({ user: req.user._id })
    .sort({ date: -1 })
    .then(model => {
      res.render('/overview', { model: model })
    })
    .catch(err => {
      if (err) throw err;
      req.flash('error_msg', 'No Model Found');
    })

})

model is an array of objects

This issue only started happening after I began to mess around with adding handlebar helpers. I have removed the helpers and reverted to my original configuration settings (above) to no avail. I've tried deleting node_modules folder and reinstalling npm.

What's being sent is an array of objects, and I am trying to loop over the properties of the objects using the {{#each model}} helper and reference the individual properties via {{prop1}} within the each.

According to Handlebars, this disabling of proto properties is false by default, and this change shouldn't break anything.

My question:

Am I sending data to handlebars incorrectly? If so, what is the correct method (not exposing my server to security holes) to send data to the express-handlebars template for rendering?

Thank you in advance.

Body:
I had the same issue when I upgraded the handlebars package. To get your system back online as quick as possible remove the handlebars entry in package.json  And then insert this line in its place.

"handlebars": "4.5.3",

From version 4.6.0 onward Handlebars forbids accessing prototype properties and methods of the context object by default. This is related to a security issue described here:
https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html

Refer to
https://github.com/wycats/handlebars.js/issues/1642

An example from the above URL shows the Mongoose response converted into JSON:

app.get('/test', function (_req, res) {
    Kitten.find({}).then(kittens => {
        res.render('test.hbs', {
            kittens: kittens.map(kitten => kitten.toJSON())
        })
    })
});

If you are certain that only trusted developers and no end users have access to the handlebars templates it's possible to allow prototype access by installing the following package:

npm install @handlebars/allow-prototype-access

Here is an example of it's use:

const express = require('express');
const Handlebars = require('handlebars')
const expressHandlebars = require('express-handlebars');
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access')

const app = express();

app.engine('handlebars', expressHandlebars({
    handlebars: allowInsecurePrototypeAccess(Handlebars)
}));
app.set('view engine', 'handlebars');
...

Another option is to use the mongoose .lean() function. This has the benefit of being much faster than a traditional mongoose query. But it does have some cons as well. By default, Mongoose queries return an instance of the Mongoose Document class. These objects contain a lot of internal state for change tracking and have additional methods such as .save(). Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just return the plain javascript object.


问:
google cloud authentication with bearer token via nodejs
My client has a GraphQL API running on Google cloud run.

I have recieved a service account for authentication as well as access to the gcloud command line tool.

When using gcloud command line like so:

```<code>gcloud auth print-identity-token
</code>```

I can generate a token that can be used to make post requests to the api. This works and I can make successful post requests to the api from postman, insomnia and from my nodejs app.

However, when I use JWT authentication with "googleapis" or "google-auth" npm libraries like so :

```<code>var { google } = require('googleapis')

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  ['https://www.googleapis.com/auth/cloud-platform']
)

jwtClient.authorize(function(err, _token) {
  if (err) {
    console.log(err)
    return err
  } else {
    console.log('token obj:', _token)
  }
})
</code>```

This outputs a "bearer" token:

```<code>token obj: {
  access_token: 'ya29.c.Ko8BvQcMD5zU-0raojM_u2FZooWMyhB9Ni0Yv2_dsGdjuIDeL1tftPg0O17uFrdtkCuJrupBBBK2IGfUW0HGtgkYk-DZiS1aKyeY9wpXTwvbinGe9sud0k1POA2vEKiGONRqFBSh9-xms3JhZVdCmpBi5EO5aGjkkJeFI_EBry0E12m2DTm0T_7izJTuGQ9hmyw',
  token_type: 'Bearer',
  expiry_date: 1581954138000,
  id_token: undefined,
  refresh_token: 'jwt-placeholder'
}
</code>```

however this bearer token does not work as the one above and always gives an "unauthorised error 401" when making the same requests as with the gcloud command "gcloud auth print-identity-token".

Please help, I am not sure why the first bearer token works but the one generated with JWT does not.

EDIT

I have also tried to get an identity token instead of an access token like so :

```<code>let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  []
)

jwtClient
  .fetchIdToken('https://my.audience.url')
  .then((res) => console.log('res:', res))
  .catch((err) => console.log('err', err))
</code>```

This prints an identity token, however, using this also just gives a "401 unauthorised" message.

Edit to show how I am calling the endpoint

Just a side note, any of these methods below work with the command line identity token, however when generated via JWT, it returns a 401

Method 1:

```<code> const client = new GraphQLClient(baseUrl, {
        headers: {
          Authorization: 'Bearer ' + _token.id_token
        }
      })
      const query = `{
        ... my graphql query goes here ...
    }`
      client
        .request(query)
        .then((data) => {
          console.log('result from query:', data)
          res.send({ data })
          return 0
        })
        .catch((err) => {
          res.send({ message: 'error ' + err })
          return 0
        })
    }
</code>```

Method 2 (using the "authorized" client I have created with google-auth):

```<code>  const res = await client.request({
    url: url,
    method: 'post',
    data: `{
        My graphQL query goes here ...
    }`
  })
  console.log(res.data)
}
</code>```

答:
Here is an example in node.js that correctly creates an Identity Token with the correct audience for calling a Cloud Run or Cloud Functions service.

Modify this example to fit the GraphQLClient. Don't forget to include the Authorization header in each call.

    // This program creates an OIDC Identity Token from a service account
    // and calls an HTTP endpoint with the Identity Token as the authorization

    var { google } = require('googleapis')
    const request = require('request')

    // The service account JSON key file to use to create the Identity Token
    let privatekey = require('/config/service-account.json')

    // The HTTP endpoint to call with an Identity Token for authorization
    // Note: This url is using a custom domain. Do not use the same domain for the audience
    let url = 'https://example.jhanley.dev'

    // The audience that this ID token is intended for (example Google Cloud Run service URL)
    // Do not use a custom domain name, use the Assigned by Cloud Run url
    let audience = 'https://example-ylabperdfq-uc.a.run.app'

    let jwtClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        audience
    )

    jwtClient.authorize(function(err, _token) {
        if (err) {
            console.log(err)
            return err
        } else {
            // console.log('token obj:', _token)

            request(
                {
                    url: url,
                    headers: {
                        "Authorization": "Bearer " + _token.id_token
                    }
                },
                function(err, response, body) {
                    if (err) {
                        console.log(err)
                        return err
                    } else {
                        // console.log('Response:', response)
                        console.log(body)
                    }
                }
            );
        }
    })
```

Body:
My client has a GraphQL API running on Google cloud run.

I have recieved a service account for authentication as well as access to the gcloud command line tool.

When using gcloud command line like so:

gcloud auth print-identity-token

I can generate a token that can be used to make post requests to the api. This works and I can make successful post requests to the api from postman, insomnia and from my nodejs app.

However, when I use JWT authentication with "googleapis" or "google-auth" npm libraries like so :

var { google } = require('googleapis')

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  ['https://www.googleapis.com/auth/cloud-platform']
)

jwtClient.authorize(function(err, _token) {
  if (err) {
    console.log(err)
    return err
  } else {
    console.log('token obj:', _token)
  }
})

This outputs a "bearer" token:

token obj: {
  access_token: 'ya29.c.Ko8BvQcMD5zU-0raojM_u2FZooWMyhB9Ni0Yv2_dsGdjuIDeL1tftPg0O17uFrdtkCuJrupBBBK2IGfUW0HGtgkYk-DZiS1aKyeY9wpXTwvbinGe9sud0k1POA2vEKiGONRqFBSh9-xms3JhZVdCmpBi5EO5aGjkkJeFI_EBry0E12m2DTm0T_7izJTuGQ9hmyw',
  token_type: 'Bearer',
  expiry_date: 1581954138000,
  id_token: undefined,
  refresh_token: 'jwt-placeholder'
}

however this bearer token does not work as the one above and always gives an "unauthorised error 401" when making the same requests as with the gcloud command "gcloud auth print-identity-token".

Please help, I am not sure why the first bearer token works but the one generated with JWT does not.

EDIT

I have also tried to get an identity token instead of an access token like so :

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  []
)

jwtClient
  .fetchIdToken('https://my.audience.url')
  .then((res) => console.log('res:', res))
  .catch((err) => console.log('err', err))

This prints an identity token, however, using this also just gives a "401 unauthorised" message.

Edit to show how I am calling the endpoint

Just a side note, any of these methods below work with the command line identity token, however when generated via JWT, it returns a 401

Method 1:

 const client = new GraphQLClient(baseUrl, {
        headers: {
          Authorization: 'Bearer ' + _token.id_token
        }
      })
      const query = `{
        ... my graphql query goes here ...
    }`
      client
        .request(query)
        .then((data) => {
          console.log('result from query:', data)
          res.send({ data })
          return 0
        })
        .catch((err) => {
          res.send({ message: 'error ' + err })
          return 0
        })
    }

Method 2 (using the "authorized" client I have created with google-auth):

  const res = await client.request({
    url: url,
    method: 'post',
    data: `{
        My graphQL query goes here ...
    }`
  })
  console.log(res.data)
}


问:
Send flat file feeds through Amazon Merchant Web Services
we are creating an interface between an ERP solution and Amazon Seller Central.
The interface is to use the Amazon MWS to upload new products to Amazon, i.e. the product is not yet "known" to Amazon and it should be added, as our customer is selling it. At the moment, our customer is using the Amazon-provided Excel templates, uploading them manually on the Seller Central web site.

We currently already have a similar solution that uses AMTU, but we want to rewrite this, so we don't have to rely on AMTU anymore.

Having read the documentation on the feed XSDs, I'm of course able to create the respective XML files and upload them through MWS. Out of curiousity, however, I also tried uploading a tab delimited flat file. This resulted in Amazon processing the file and returning a flat file that told me about success or errors.

My questions are:

Is it possible to use flat files instead of XML files to add/update/remove products to/from the Amazon product catalog even though they are, according to the docs, only meant to update the seller's listings (price, quantity available, etc.)?

Will this be a "permanent" feature? I mean: If I make my interface upload flat files, will I have to change it again in a few months - is there any known date when uploading flat files will be deprecated?

答: I got word from Amazon. They basically say that using Flat File uploads is possible and will be possible in the future, even though XML is the "new" and recommended way.</p>

ContentLicense: CC BY-SA 3.0


问:
SQL Query to find closest match on products in the same box
Recently, my company warehouse started receiving bundled products (we call them "kits") which have, in the same box, different products (mostly of the time, different in sizes).

We store them as we receive.

However, when we do not have a single item to ship (not inside a kit) we need to open the kit, and them split all the items into individual boxes.

I'm struggling to make a query which will return the oldest (OK, I can sort by table_ID desc) and the closest match.

My goal is, provided a list of items and quantities, always find the "best match" so in the end, I will have less work (and boxes) to split.

Consider a sample from my inventory (real table has a lot more data and columns like location, warehouse, price, etc, but they are not needed for the example):

In this example, If I'm asked to get 2 small blue shirts, the expected return should be kit number 5 and 6, because:

kits number 5 and 6 is the "closest match" (would have been a "perfect match" IF I also asked for 2 medium blue) - the medium shirt is "collateral damage", and then I will unbox it anyway

kits number 1 to 4 should be discarded, since they are the worst match (they have a LARGE inside)

kit number 7 is also a candidate. However, since the inside shirt is another color, in a tie with the first rule, it should be less preferred

SQL Server is 2016 SP2 - Standard Edition

答:
Do you think the following may work ? ( commented some parts to see the whole picture )</p>

```<code>WITH Temp
AS (SELECT *,
           SUBSTRING(SKU, 1, CHARINDEX('_', SKU) - 1) AS Color,
           SUBSTRING(
                        SKU,
                        CHARINDEX('_', SKU) + 1,
                        CHARINDEX('-', SUBSTRING(SKU, CHARINDEX('_', SKU) + 1, CHARINDEX('-', SKU))) - 1
                    ) AS Product,
           REVERSE(SUBSTRING(REVERSE(SKU), 1, CHARINDEX('-', REVERSE(SKU)) - 1)) AS Size
    FROM dbo.Table_2),
     BestPick
AS (SELECT T.Kit_Number,
           T.QTY,
           T.Color,
           T.Product,
           T.Size,
           COUNT(T.QTY) OVER (PARTITION BY T.Kit_Number) AS Sum_KitCount
    FROM Temp AS T)
SELECT STRING_AGG(B.Kit_Number, ', ') AS BestPick,
       SUM(B.QTY) AS Total_IN_Kits,
       B.Color,
       B.Product,
       B.Size
FROM BestPick AS B
--WHERE B.Color = 'Blue'
--      AND B.Size = 'Small'
GROUP BY B.Color,
         B.Product,
         B.Size,
         B.Sum_KitCount
--HAVING SUM(B.QTY) >= 2
ORDER BY SUM(B.QTY);
</code>```

Body:
Do you think the following may work ? ( commented some parts to see the whole picture )

WITH Temp
AS (SELECT *,
           SUBSTRING(SKU, 1, CHARINDEX('_', SKU) - 1) AS Color,
           SUBSTRING(
                        SKU,
                        CHARINDEX('_', SKU) + 1,
                        CHARINDEX('-', SUBSTRING(SKU, CHARINDEX('_', SKU) + 1, CHARINDEX('-', SKU))) - 1
                    ) AS Product,
           REVERSE(SUBSTRING(REVERSE(SKU), 1, CHARINDEX('-', REVERSE(SKU)) - 1)) AS Size
    FROM dbo.Table_2),
     BestPick
AS (SELECT T.Kit_Number,
           T.QTY,
           T.Color,
           T.Product,
           T.Size,
           COUNT(T.QTY) OVER (PARTITION BY T.Kit_Number) AS Sum_KitCount
    FROM Temp AS T)
SELECT STRING_AGG(B.Kit_Number, ', ') AS BestPick,
       SUM(B.QTY) AS Total_IN_Kits,
       B.Color,
       B.Product,
       B.Size
FROM BestPick AS B
--WHERE B.Color = 'Blue'
--      AND B.Size = 'Small'
GROUP BY B.Color,
         B.Product,
         B.Size,
         B.Sum_KitCount
--HAVING SUM(B.QTY) >= 2
ORDER BY SUM(B.QTY);


问:
holeMenuProgram.cpp:38:1 Error: Expected Primary-Expression before '}' token
I am creating a menu using switch cases but when I got to filter out unavailable choices using a do-while statement I am getting an odd error. Could I get some insight on what I am doing wrong here? Thank you in advance as I am a new programmer. I am aware the case switches have nothing in them but this shouldn't stop it from compiling correctly.</p>

```<code>//Programmer: Lane Floyd  Date: 2/17/2020
//File: holeMenuProgram.cpp
//Description:

#include <iostream>
using namespace std;

int main()
{

int menuChoice;  //User input 1-4 for menu choice.

do
{
  // Below is the menu.
  cout << "       Menu        " << endl;
  cout << "       ----        " << endl;
  cout << "1.  Enter a number    " << endl;
  cout << "2.  Power the number    " << endl;
  cout << "3.  Cube root of the number    " <<endl;
  cout << "4.  Quit"  <<endl;

  cout << "Input Choice: \r";
  cin >> menuChoice;

} while (menuChoice != 1 || menuChoice != 0);

switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
}

return 0;
}
</code>```

答:
A label must precede a statement. You could write for example

```<code>switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
  ;
}
</code>```

placing a null statement before the closing brace in the switch statement.

Or to make the code more readable you could insert at least one break statement like

```<code>switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
      break;
}
</code>```

Body:
I am creating a menu using switch cases but when I got to filter out unavailable choices using a do-while statement I am getting an odd error. Could I get some insight on what I am doing wrong here? Thank you in advance as I am a new programmer. I am aware the case switches have nothing in them but this shouldn't stop it from compiling correctly.

//Programmer: Lane Floyd  Date: 2/17/2020
//File: holeMenuProgram.cpp
//Description:

#include <iostream>
using namespace std;

int main()
{

int menuChoice;  //User input 1-4 for menu choice.

do
{
  // Below is the menu.
  cout << "       Menu        " << endl;
  cout << "       ----        " << endl;
  cout << "1.  Enter a number    " << endl;
  cout << "2.  Power the number    " << endl;
  cout << "3.  Cube root of the number    " <<endl;
  cout << "4.  Quit"  <<endl;

  cout << "Input Choice: \r";
  cin >> menuChoice;

} while (menuChoice != 1 || menuChoice != 0);

switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
}

return 0;
}

Body:
A label must precede a statement. You could write for example

switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
  ;
}

placing a null statement before the closing brace in the switch statement.

Or to make the code more readable you could insert at least one break statement like

switch(menuChoice)
{
  case 1:

  case 2:

  case 3:

  case 4:
      break;
}


问:
Empty body content on TYPO3 page
Encountered an issue today where I made tweaks to the a TYPO3 page and the page became blank. The  tag was empty!

I fixed it by clearing cache, but I also found another page with the same problem later on.

Doing some research I found that the page is empty on the cache_pages table.

What is causing it? I am using TYPO3 4.5.6

答:
It happened to me. and the cause was, in the fluid template?
Instead of using fluid template, i just use the regular html tag if you didn't initiate the view helper or something in your form.</p>

Title: Empty body content on TYPO3 page


问:
Why does Stream.reduce take BinaryOperator<T> rather than BiFunction<T, T, T>?
For my specific case I want to use functional composition in a reduction; for example:

```<code>BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());
</code>```

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator
```

<p>Instead, I need to do:</p>

```ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());
```

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

答:
The reduce operation must take arguments of the same type and return an identical type. If it didn't, there'd be a type mismatch. That's exactly what the BinaryOperator is: BinaryOperator<T> extends BiFunction<T,T,T>

Instead of using a lambda, you can create your BiFunction. Then create a BinaryOperator:

```<code>import java.util.function.BinaryOperator;
import java.util.function.BiFunction;
import java.util.function.Function;

import java.util.stream.Stream;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;

public class StackOverflowTest {
  public static void main(String[] args) {

    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
    Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;

    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);

    BinaryOperator<ImmutableSet<Integer>> biOperator = biFunction::apply;

    ImmutableSet<Integer> intersection =
       Stream.of(ImmutableSet.of(1, 2, 3),
                 ImmutableSet.of(1, 2),
                 ImmutableSet.of(1, 4)) // added a 1
             .reduce(biOperator)
             .orElse(ImmutableSet.of());

    System.out.println(intersection);

/*
prints:
[1]
*/
  }
}
</code>```

Body:
For my specific case I want to use functional composition in a reduction; for example:

BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator

Instead, I need to do:

ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

Body:
The reduce operation must take arguments of the same type and return an identical type. If it didn't, there'd be a type mismatch. That's exactly what the BinaryOperator is: BinaryOperator<T> extends BiFunction<T,T,T>

Instead of using a lambda, you can create your BiFunction. Then create a BinaryOperator:

import java.util.function.BinaryOperator;
import java.util.function.BiFunction;
import java.util.function.Function;

import java.util.stream.Stream;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;

public class StackOverflowTest {
  public static void main(String[] args) {

    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
    Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;

    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);

    BinaryOperator<ImmutableSet<Integer>> biOperator = biFunction::apply;

    ImmutableSet<Integer> intersection =
       Stream.of(ImmutableSet.of(1, 2, 3),
                 ImmutableSet.of(1, 2),
                 ImmutableSet.of(1, 4)) // added a 1
             .reduce(biOperator)
             .orElse(ImmutableSet.of());

    System.out.println(intersection);

/*
prints:
[1]
*/
  }
}


问:
Search arrays then echo with conditionals?
I'm trying to do somthing like this:

```<code>  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }
</code>```

SOLVED:

```<code>$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }
</code>```

Progression:

```<code>$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";
</code>```

答:
You probably want to look at array_intersect:

http://php.net/manual/en/function.array-intersect.php

Body:
I'm trying to do somthing like this:

  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }

SOLVED:

$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }

Progression:

$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";


问:
Multiple Cloud Firestore for single project
I have a project with 2 schemes, one for development and other for production. I am also using firebase, hence I created 2 projects and injected two google plists under different names in the project. I also need to access google cloud platform. I cannot change/modify cloud functions without affecting my production application. Is there a way where I can have two Firestore for single project so that editing/ changing functions in on won't affect other?</p>

答:
It's not possible to have multiple Firestore instances per project.

It's not entirely clear to me what the problem is with your use of Cloud Functions, but the functions running in each projects should automatically use the Firestore instance for the project that they've been deployed to.  If you need to access a different Firestore instance, then you will need to deploy some configuration for your functions so they can initialize an instance of the Cloud SDK that you're using to read and write Firestore


问:
Multiple Button in one Form Request with Flask + Jquery + Ajax
This is my myindex.html file where I have 2 buttons for 2 different requests. Both the buttons share same textarea as input.

```<code><script type="text/javascript">

 jQuery(document).ready(function($)
 {
    var textbox = document.getElementById('textarea');
    var dropdown = document.getElementById('dropdown');

    dropdown.onchange = function() {
     var dropdownValue = dropdown.options[dropdown.selectedIndex].value;
     textarea.value = dropdownValue;
    }
   });
   jQuery(document).ready(function($)
   {
      $.fn.callsm = function()
      {
        alert('You have successfully defined the function!')
      }
      $(".callsm").click(function()
      {
        var request_body = $("#textarea").val()
        console.log(request_body)
        $.ajax
        ({
            type: 'POST',
            url: "/invocations",
            data : request_body,
            headers:
            {
                    'Content-Type': 'text/plain'
            }
         }).done(function(data)
         {
          //DO SOMETHING
         }
            }).fail(function(data)
            {
                console.log('fail: '+data);
            });

     });

    $.fn.calldm = function()
      {
        alert('You have successfully defined the function!')
      }
      $(".calldm").click(function()
      {
         var request_body = $("#textarea").val()
         console.log(request_body)

         $.ajax
         ({
            type: 'POST',
            url: "/invocations",
            data : request_body,
            headers:
            {
                    'Content-Type': 'text/plain'
            }
            }).done(function(data)
            {
                //DO SOMETHING
            }).fail(function(data)
            {
                console.log('fail: '+data);
            });

       });

    });

    </script>

     <form name="myform" action="/invocations" method = "post">

    <select id="dropdown">
        <option value=" ">leer</option>
        <option value=" Hi, I am dataplumber">option1</option>
    </select><br><br>
      <textarea rows="20" cols="50" id="textarea" name="textarea"></textarea><br>
      <button type="button" id="document" class="calldm" name="document">Call DM</button>
      <button type="button" id="sentence" class="callsm" name="sentence">Call SM</button>

    </form>
</code>```

And below is my app.py file

```<code>@app.route("/invocations", methods=["POST"])
def invocations():
    if "document" in request.form:
        url = 'http://XXXX/invocations'
        //DO SOMETHING
        return x.content
    elif "sentence" in request.form:
        //DO Something
        return x.content.decode('utf-8')
    else:
            return render_template('myindex.html')
</code>```

But my python code fails as the ImmutableMultiDict is empty. If I remove if else from python and call document and sentence individually it succeeds..Am I doing something wrong here.

答: You're not submitting the form, so your data will be in request.data instead of request.form.

Body:
This is my myindex.html file where I have 2 buttons for 2 different requests. Both the buttons share same textarea as input.

     <form name="myform" action="/invocations" method = "post">

    <select id="dropdown">
        <option value=" ">leer</option>
        <option value=" Hi, I am dataplumber">option1</option>
    </select>

      <textarea rows="20" cols="50" id="textarea" name="textarea"></textarea>

      <button type="button" id="document" class="calldm" name="document">Call DM</button>
      <button type="button" id="sentence" class="callsm" name="sentence">Call SM</button>

    </form>

And below is my app.py file

@app.route("/invocations", methods=["POST"])
def invocations():
    if "document" in request.form:
        url = 'http://XXXX/invocations'
        //DO SOMETHING
        return x.content
    elif "sentence" in request.form:
        //DO Something
        return x.content.decode('utf-8')
    else:
            return render_template('myindex.html')

But my python code fails as the ImmutableMultiDict is empty. If I remove if else from python and call document and sentence individually it succeeds..Am I doing something wrong here.


问:
How to Implement `Year + 1` in Dataframe
I have a df

```<code>      Date Filing Date Name
0  2013 Q2   8/17/2013  AAA
1  2013 Q3  11/19/2013  BBB
2  2013 Q4    2/2/2014  CCC
3  2014 Q4   2/13/2015  DDD
4  2015 Q1   5/12/2015  EEE
5  2015 Q2    8/7/2015  FFF
6  2015 Q3  11/20/2015  GGG
7  2016 Q4   2/19/2017  HHH
8  2019 Q4    2/4/2020  III
</code>```

where I am updating the Filing Date column based on a mapping:

```<code># Split Date Column into one column for Year, and one for Quarter
df['Year'], df['Quarter'] = df['Date'].str.split(' ', 1).str
# Replace Quarter values with date values
df['Filing Date'] = (df['Quarter'].map({'Q1': '5/15/', 'Q2': '8/15/','Q3': '11/15/', 'Q4': '2/15/'}) + df['Year'])
</code>```

The problem is that for all Q4 entries, the Year of the Filing Date should actually be the Date Year + 1. For example:

```<code>      Date Filing Date Name
2  2013 Q4   2/15/2014  CCC
3  2014 Q4   2/15/2015  DDD
7  2016 Q4   2/15/2017  HHH
8  2019 Q4   2/15/2020  III
</code>```

I know I can probably do this by converting to dateime, loop through each row of the dataframe, and add 1 to the year for each Q4 row. But that seems clunky and I have heard it's best to avoid looping through a dataframe. So is there a more elegant way of doing this?

Body:
I have a df

      Date Filing Date Name
0  2013 Q2   8/17/2013  AAA
1  2013 Q3  11/19/2013  BBB
2  2013 Q4    2/2/2014  CCC
3  2014 Q4   2/13/2015  DDD
4  2015 Q1   5/12/2015  EEE
5  2015 Q2    8/7/2015  FFF
6  2015 Q3  11/20/2015  GGG
7  2016 Q4   2/19/2017  HHH
8  2019 Q4    2/4/2020  III

where I am updating the Filing Date column based on a mapping:

# Split Date Column into one column for Year, and one for Quarter
df['Year'], df['Quarter'] = df['Date'].str.split(' ', 1).str
# Replace Quarter values with date values
df['Filing Date'] = (df['Quarter'].map({'Q1': '5/15/', 'Q2': '8/15/','Q3': '11/15/', 'Q4': '2/15/'}) + df['Year'])

The problem is that for all Q4 entries, the Year of the Filing Date should actually be the Date Year + 1. For example:

      Date Filing Date Name
2  2013 Q4   2/15/2014  CCC
3  2014 Q4   2/15/2015  DDD
7  2016 Q4   2/15/2017  HHH
8  2019 Q4   2/15/2020  III

I know I can probably do this by converting to dateime, loop through each row of the dataframe, and add 1 to the year for each Q4 row. But that seems clunky and I have heard it's best to avoid looping through a dataframe. So is there a more elegant way of doing this?

Body:
Use numpy where to achieve your goal :

dic = {'Q1': '5/15/', 'Q2': '8/15/','Q3': '11/15/', 'Q4': '2/15/'}

df['Filing Date'] = np.where(df.Quarter=='Q4',
                          df['Quarter'].map(dic)+df.Year.add(1).astype(str),
                          df['Quarter'].map(dic)+df.Year.astype(str))

    Year    Quarter Filing Date Name
0   2013    Q2  8/15/2013   AAA
1   2013    Q3  11/15/2013  BBB
2   2013    Q4  2/15/2014   CCC
3   2014    Q4  2/15/2015   DDD
4   2015    Q1  5/15/2015   EEE
5   2015    Q2  8/15/2015   FFF
6   2015    Q3  11/15/2015  GGG
7   2016    Q4  2/15/2017   HHH
8   2019    Q4  2/15/2020   III


问:
Use IPython REPL in VS Code
Using the Python extension of Visual Studio Code, I can select some code, right-click it, and select "Run Selection/Line in Python Terminal" (alternatively, I can hit Shift+Enter). However, this sends the selected code to a plain old Python REPL in the Terminal pane, whereas I'd like to have this code run in IPython instead (not the QtConsole, just the terminal-based IPython).

Is it possible to set IPython as the default REPL? I tried setting /usr/local/bin/ipython3 as my default Python environment, but that doesn't work (it still executes the plain Python interpreter). FWIW, I'm on macOS.

答:
Adding the following setting (Preference: Open Settings JSON; or Preference -> Settings -> Search launchArgs -> edit in json) works without any extension. It also fixes the issue that multiple lines cannot be sent to Python.

```<code>"python.terminal.launchArgs": [
    "-c",
    "\"import subprocess; subprocess.call(['ipython', '--no-autoindent'])\""
],
</code>```

Update (2020-12-27): the following setting seems to work better because it supports Ctrl+C keyboard interrupt without existing IPython:

```<code>"python.terminal.launchArgs": [
    "-m",
    "IPython",
    "--no-autoindent",
],
</code>```

Title: Use IPython REPL in VS Code

Body:
Adding the following setting (Preference: Open Settings JSON; or Preference -> Settings -> Search launchArgs -> edit in json) works without any extension. It also fixes the issue that multiple lines cannot be sent to Python.

"python.terminal.launchArgs": [
    "-c",
    "\"import subprocess; subprocess.call(['ipython', '--no-autoindent'])\""
],

Update (2020-12-27): the following setting seems to work better because it supports Ctrl+C keyboard interrupt without existing IPython:

"python.terminal.launchArgs": [
    "-m",
    "IPython",
    "--no-autoindent",
],


Title: How to Implement `Year + 1` in Dataframe

Body:
You can use a ternary to increase the year by one if it is Q4: int(yr) + (1 if qtr == 'Q4' else 0)

import datetime as dt

# Sample data.
df = pd.DataFrame({
    'Date': ['2013 Q2', '2013 Q3', '2013 Q4', '2014 Q4', '2015 Q1', '2015 Q2', '2015 Q3', '2016 Q4', '2019 Q4'],
    'Filing Date': ['8/17/2013', '11/19/2013', '2/2/2014', '2/13/2015', '5/12/2015', '8/7/2015', '11/20/2015', '2/19/2017', '2/4/2020'],
    'Name': ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III']
})

# Solution.
quarter_to_month_mapping = {'Q1': 5, 'Q2': 8, 'Q3': 11, 'Q4': 2}
year, quarter = zip(*df['Date'].str.split(' ', 1))
df['Filing Date'] = pd.to_datetime([
    dt.date(
        year=int(yr) + (1 if qtr == 'Q4' else 0),
        month=quarter_to_month_mapping[qtr],
        day=15
    )
    for yr, qtr in zip(year, quarter)]
)
>>> df
      Date Filing Date Name
0  2013 Q2  2013-08-15  AAA
1  2013 Q3  2013-11-15  BBB
2  2013 Q4  2014-02-15  CCC
3  2014 Q4  2015-02-15  DDD
4  2015 Q1  2015-05-15  EEE
5  2015 Q2  2015-08-15  FFF
6  2015 Q3  2015-11-15  GGG
7  2016 Q4  2017-02-15  HHH
8  2019 Q4  2020-02-15  III


问:
Having a bit of trouble with self-learning from Cormen et al's algo book
I started reading Intro to Algorithms by Cormen et al like 3 weeks ago on my free time. I  finished the second chapter and have been trying out the exercises for quite a while. I find them a bit difficult.

Is this normal? Should I finish all the exercises before moving on? Or is it alright if I solve the ones I can and move on to the next chapters, possibly coming back to the exercises I can't figure out right now?

If anyone out there has had experience with this book, can you tell me how it was for you? I'm a bit discouraged on not being able to solve quite a few of the exercises here.

答:
I am learning Algorithms on my own from the CLRS book in 2020. Regardless of what people tell you about solutions manuals in general, it is advisable to get "good" solutions manuals if you are self studying with the book.

The two sets of solutions I recommend are (1) The official instructor manual and (2) solutions by Rutger's university students Michelle Bodnar and Andrew Lohr. When one of those solutions is unclear, I simply refer to the other one. If you get stuck at a problem, then give yourself a few minutes to solve it. If you don't get the answer, then use the solutions manuals. You can always test yourself on the problems from other text books or leetcode to see how much you can do on your own vs just following a solutions manual.

I won't post the solutions manuals here. I suggest that you search for them online. The Rutgers one is easily available and is legal. The official one is restricted to instructors only and is hard to get. You might be able to pay obscure online sellers/hackers to get the official one for you. Use a preloaded visa or master card gift card to make that purchase. Make sure that the card is accepted in the sellers country.

Chapter 2 was doable because I used Youtube to understand algorithms and time complexity when it was not clearly explained in the CLRS book, which is quite often. The solutions manuals also helped a little bit.

Chapter 3 is hard and I don't know if I will be able to get past this one. I might have to switch to another book, perhaps the one by Tamassia. I had studied elementary algebra, set theory, functions, probability, mathematical series and calculus a few years ago. But, I remember only a few of those things. So, it is difficult to understand Chapter 3 and move ahead.

ContentLicense: CC BY-SA 2.5


问:
Can a default user's password be set in SQL using PHP's password_hash?
My old PHP app has a default admin user and md5 encrypted password created by the SQL that creates the database: insert into users values ( 1, 'admin', MD5('changeMe'), 2 );

Is there a simple way to include a default user and encrypted password using PHP's passowrd_hash function on creating the tables? I ask because I understand that password_hash is a native PHP function and I assume it won't be understood in SQL.

答:
The solution to my problem came in three parts. My OP sought a simple way to create a hashed password for the admin user for insertion in the MySQL database on the installation of the application, using the native PHP password_hash() function.

(1) Based on a suggestion by @Nick and @Tadman, I decided to incorporate setting the hash in an installer script that would set not only the hash but other defined site/application variables.

Rather than inserting user values when the database table is created, it was deferred until immediately after, with the admin user entering their credentials in the form that inserts the hash and writes other definitions to a file:

```<code>$userpass = $_POST['userpass'];
echo password_hash($userpass, PASSWORD_BCRYPT);
</code>```

(2) The second part of my problem was replacing all instances of md5()`` withpassword_hash()` and I achieved that by using a neat PHP script I found online to recursively search and replace the occurrences on the server.

Having replaced the md5() occurrences, I needed to change the hash comparison method and again by searching the relevant files I was able to replace instances of:

```<code>if ($p != $theUser->pwd ) {
    return( false );     }
</code>```

with:

```<code>if(password_verify($p, $theUser->pwd)) {
    // Success!
    }
else {
    // Invalid credentials
echo "Uh oh!";
    }
</code>```

(3) The third step in resolving the problem was discovering that adding $1$ to the opening of the md5 hash could make it readable by password_hash(); so I just needed to make a couple of adjustments in the installed database to the admin user's old password.

Thanks to those who helped shine the light so I could find my way. I'm off now to invent the wheel and sliced bread.

Body:
The solution to my problem came in three parts. My OP sought a simple way to create a hashed password for the admin user for insertion in the MySQL database on the installation of the application, using the native PHP password_hash() function.

(1) Based on a suggestion by @Nick and @Tadman, I decided to incorporate setting the hash in an installer script that would set not only the hash but other defined site/application variables.

Rather than inserting user values when the database table is created, it was deferred until immediately after, with the admin user entering their credentials in the form that inserts the hash and writes other definitions to a file:

$userpass = $_POST['userpass'];
echo password_hash($userpass, PASSWORD_BCRYPT);

(2) The second part of my problem was replacing all instances of md5()`` withpassword_hash()` and I achieved that by using a neat PHP script I found online to recursively search and replace the occurrences on the server.

Having replaced the md5() occurrences, I needed to change the hash comparison method and again by searching the relevant files I was able to replace instances of:

if ($p != $theUser->pwd ) {
    return( false );     }

with:

if(password_verify($p, $theUser->pwd)) {
    // Success!
    }
else {
    // Invalid credentials
echo "Uh oh!";
    }

(3) The third step in resolving the problem was discovering that adding $1$ to the opening of the md5 hash could make it readable by password_hash(); so I just needed to make a couple of adjustments in the installed database to the admin user's old password.

Thanks to those who helped shine the light so I could find my way. I'm off now to invent the wheel and sliced bread.


问:
GPOs for User Configuration are not overrided
I've a two GPOs on my domain -> "Default Domain Policy" and "GPO - Diretoria". Default Domain Policy is configured to set proxy settings on all IE browser of the clients (User Config > Policies > Windows Settings > Internet Explorer Maintenance > Connection > Proxy Settings). Here are the detailed config used:

```<code>Internet Explorer Connection
----------------------------
    HTTP Proxy Server:   192.168.100.1:3128
    Secure Proxy Server: 192.168.100.1:3128
    FTP Proxy Server:    192.168.100.1:3128
    Gopher Proxy Server: 192.168.100.1:3128
    Socks Proxy Server:  192.168.100.1:3128
    Auto Config Enable:  No
    Enable Proxy:        Yes
    Use same Proxy:      Yes
</code>```

In the other GPO (GPO - Diretoria) the proxy settings are not configured. The "Enable proxy settings" check box are disabled in Proxy Settings window. This GPO are linked to an OU called Diretoria. Inside this OU, there are 3 computers. When I exec a gpupdate (even gpupdate /force) in any of the 3 computers, the proxy settings still setted as configured in Default Domain Policy!

Then, I´ve performed various tests only with User Configuration Settings and, I´ve noticed (by running gpresult /z) that any User Configuration Setting setted on Default Domain Policy GPO cannot be replaced by the "GPO - Diretoria" User Configuration Settings! BUT, the Computer Configuration Settings are replaced perfectly!

```<code>COMPUTER SETTINGS
------------------
    CN=MARCOS-SUPVM,OU=Diretoria,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:36 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        internal
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        GPO - Diretoria
        Default Domain Policy

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
.
.
.
.

USER SETTINGS
--------------
    CN=Administrador,CN=Users,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:39 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        INTERNAL
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        Default Domain Policy  <-- SEE HERE??? "GPO - Diretoria" ARE NOT PROCESSED!

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
</code>```

Why?

答:
The user configuration from GPO - Diretoria won't be applied because your user object CN=Administrador,CN=Users,DC=internal,DC=domain,DC=com,DC=br is not under "Diretoria" OU.

The computer configuration from GPO - Diretora is applied because your computer object
CN=MARCOS-SUPVM,OU=Diretoria,DC=internal,DC=domain,DC=com,DC=br is inside "Directoria" OU

Try moving your administrator user object to OU=Diretoria.  Then, you will see user configuration being applied as well.

Body:
I've a two GPOs on my domain -> "Default Domain Policy" and "GPO - Diretoria". Default Domain Policy is configured to set proxy settings on all IE browser of the clients (User Config > Policies > Windows Settings > Internet Explorer Maintenance > Connection > Proxy Settings). Here are the detailed config used:

Internet Explorer Connection
----------------------------
    HTTP Proxy Server:   192.168.100.1:3128
    Secure Proxy Server: 192.168.100.1:3128
    FTP Proxy Server:    192.168.100.1:3128
    Gopher Proxy Server: 192.168.100.1:3128
    Socks Proxy Server:  192.168.100.1:3128
    Auto Config Enable:  No
    Enable Proxy:        Yes
    Use same Proxy:      Yes

In the other GPO (GPO - Diretoria) the proxy settings are not configured. The "Enable proxy settings" check box are disabled in Proxy Settings window. This GPO are linked to an OU called Diretoria. Inside this OU, there are 3 computers. When I exec a gpupdate (even gpupdate /force) in any of the 3 computers, the proxy settings still setted as configured in Default Domain Policy!

Then, I´ve performed various tests only with User Configuration Settings and, I´ve noticed (by running gpresult /z) that any User Configuration Setting setted on Default Domain Policy GPO cannot be replaced by the "GPO - Diretoria" User Configuration Settings! BUT, the Computer Configuration Settings are replaced perfectly!

COMPUTER SETTINGS
------------------
    CN=MARCOS-SUPVM,OU=Diretoria,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:36 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        internal
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        GPO - Diretoria
        Default Domain Policy

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
.
.
.
.

USER SETTINGS
--------------
    CN=Administrador,CN=Users,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:39 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        INTERNAL
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        Default Domain Policy  <-- SEE HERE??? "GPO - Diretoria" ARE NOT PROCESSED!

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)

Why?


问:
Wish to hover over a container and have both elements (an Image) and p react and change at the same time
I have a <button> that is css formatted with a png as background-image and that has the width and height limited. Also a
 with text. This is actually changing as expected On :hover but the button image is not. On :hover I have the css set to change the background-position to a different part of the larger image.

I  have picked up some code from other answers here on stack overflow and tried to make them fit what I need. I have actually tried for days to make this work and deleted a lot of code in the process. I created a jsfiddle to show what is working and what isn't. Sorry for probably asking the same thing as others.
jsfiddle  Hope I did that right.

  /*Testing buton and id add to basket  without the anchor . so far not working*/
  /*  */
  .frame {
    float: left;
    width: 300px;
    min-height: 50px;
    background-color: ##00F;
    margin: 0px 10px;
    border: 1px solid black;
  }

.frame:hover > .info > p{
    font-size: 14px;
    color:green;
}

.frame:hover > .button > img#add-to-basket1 {
    background-position: 42px 0px;
}
/* also tried
.frame:hover > img#add-to-basket1 { background-position: 42px 0px;}  and
.frame:hover > #add-to-basket1 { background-position: 42px 0px;}
*/

.info {
    float: left;
    max-width: 220px;
    height: auto;
    background-color: none;
    margin-left: 20px;
    vertical-align: middle;
    line-height: 42px;
}

.info p {
    font-family: 'Open Sans', Arial, sans-serif;
    font-size: 14px;
    font-weight: 400;
    font-style: italic;
    color: #8F8F8F;
    margin-top: 5px;
}

img.button {
    border-radius: 100%;
    display: inline-block;
    background-image: url('https://ggeddes.com/_media/_media/Button1_6Square.png');

    height: 42px; width: 42px;
    background-size: 85px 250px;
    text-indent: -9999px;
    line-height:42px;
    float: left;
}

#add-to-basket1 { background-position: 0px 0px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <div class="frame">
      <img class="button" id="add-to-basket1"/>
      <div class="info">
        <p>Preparing Your Home For Showing</p>
      </div>
    </div></code>```

答:
Something Like This?

Here is the problem:

.frame:hover > .button > img#add-to-basket1 { }

This means that you are referencing img#add-to-basket1 which is inside of .button based on your code. But .button and img#add-to-basket1 refers to the same element. so you can remove either of them. in my case I just removed .button.

/*Testing buton and id add to basket  without the anchor . so far not working*/
/*  */
.frame {
    float: left;
    width: 300px;
    min-height: 50px;
    background-color: ##00F;
    margin: 0px 10px;
    border: 1px solid black;
}

.frame:hover > .info > p{
    font-size: 14px;
    color:green;
}

.frame:hover > img#add-to-basket1 {
    background-position: 42px 0px;
}
/* also tried
.frame:hover > img#add-to-basket1 { background-position: 42px 0px;}  and
.frame:hover > #add-to-basket1 { background-position: 42px 0px;}
*/

.info {
    float: left;
    max-width: 220px;
    height: auto;
    background-color: none;
    margin-left: 20px;
    vertical-align: middle;
    line-height: 42px;
}

.info p {
    font-family: 'Open Sans', Arial, sans-serif;
    font-size: 14px;
    font-weight: 400;
    font-style: italic;
    color: #8F8F8F;
    margin-top: 5px;
}

img.button {
    border-radius: 100%;
    display: inline-block;
    background-image: url('https://ggeddes.com/_media/_media/Button1_6Square.png');

    height: 42px; width: 42px;
    background-size: 85px 250px;
    text-indent: -9999px;
    line-height:42px;
    float: left;
}

#add-to-basket1 { background-position: 0px 0px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="frame">
  <img class="button" id="add-to-basket1"/>
  <div class="info">
    <p>Preparing Your Home For Showing</p>
  </div>
</div></code>```

Body:
I have a <button> that is css formatted with a png as background-image and that has the width and height limited. Also a
 with text. This is actually changing as expected On :hover but the button image is not. On :hover I have the css set to change the background-position to a different part of the larger image.

I  have picked up some code from other answers here on stack overflow and tried to make them fit what I need. I have actually tried for days to make this work and deleted a lot of code in the process. I created a jsfiddle to show what is working and what isn't. Sorry for probably asking the same thing as others.
jsfiddle  Hope I did that right.

  /*Testing buton and id add to basket  without the anchor . so far not working*/
  /*  */
  .frame {
    float: left;
    width: 300px;
    min-height: 50px;
    background-color: ##00F;
    margin: 0px 10px;
    border: 1px solid black;
  }

.frame:hover > .info > p{
    font-size: 14px;
    color:green;
}

.frame:hover > .button > img#add-to-basket1 {
    background-position: 42px 0px;
}
/* also tried
.frame:hover > img#add-to-basket1 { background-position: 42px 0px;}  and
.frame:hover > #add-to-basket1 { background-position: 42px 0px;}
*/

.info {
    float: left;
    max-width: 220px;
    height: auto;
    background-color: none;
    margin-left: 20px;
    vertical-align: middle;
    line-height: 42px;
}

.info p {
    font-family: 'Open Sans', Arial, sans-serif;
    font-size: 14px;
    font-weight: 400;
    font-style: italic;
    color: #8F8F8F;
    margin-top: 5px;
}

img.button {
    border-radius: 100%;
    display: inline-block;
    background-image: url('https://ggeddes.com/_media/_media/Button1_6Square.png');

    height: 42px; width: 42px;
    background-size: 85px 250px;
    text-indent: -9999px;
    line-height:42px;
    float: left;
}

#add-to-basket1 { background-position: 0px 0px;}

Preparing Your Home For Showing

Body:
Something Like This?

Here is the problem:

.frame:hover > .button > img#add-to-basket1 { }

This means that you are referencing img#add-to-basket1 which is inside of .button based on your code. But .button and img#add-to-basket1 refers to the same element. so you can remove either of them. in my case I just removed .button.

/*Testing buton and id add to basket  without the anchor . so far not working*/
/* <!-- test of https://codepen.io/anon/pen/bENBGW --> */
.frame {
    float: left;
    width: 300px;
    min-height: 50px;
    background-color: ##00F;
    margin: 0px 10px;
    border: 1px solid black;
}

.frame:hover > .info > p{
    font-size: 14px;
    color:green;
}

.frame:hover > img#add-to-basket1 {
    background-position: 42px 0px;
}
/* also tried
.frame:hover > img#add-to-basket1 { background-position: 42px 0px;}  and
.frame:hover > #add-to-basket1 { background-position: 42px 0px;}
*/

.info {
    float: left;
    max-width: 220px;
    height: auto;
    background-color: none;
    margin-left: 20px;
    vertical-align: middle;
    line-height: 42px;
}

.info p {
    font-family: 'Open Sans', Arial, sans-serif;
    font-size: 14px;
    font-weight: 400;
    font-style: italic;
    color: #8F8F8F;
    margin-top: 5px;
}

img.button {
    border-radius: 100%;
    display: inline-block;
    background-image: url('https://ggeddes.com/_media/_media/Button1_6Square.png');

    height: 42px; width: 42px;
    background-size: 85px 250px;
    text-indent: -9999px;
    line-height:42px;
    float: left;
}

#add-to-basket1 { background-position: 0px 0px;}

<div class="frame">
  <img class="button" id="add-to-basket1"/>
  <div class="info">
    <p>Preparing Your Home For Showing</p>
  </div>
</div>


问:
Type mismatch: cannot convert from double [] to int []
I am trying to have the method return the new array that was made by the for loop. </p>

```<code>import java.util.Arrays;
public class stocks {

public static void main(String[] args) {

    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    double isOverprices [] = overpriced(stockV);

}
    public int [] overpriced(double[] rsiValues)
    {
        for (int i = 0; i < rsiValues.length; i++)
        {
            if (rsiValues[i] > 70)
            {
                rsiValues[i] = 1;
            }
            else if (rsiValues[i] <= 70)
            {
                rsiValues[i] = 0;
            }
            return rsiValues;
        }
    }
 }
</code>```

答:
Add 'static' to the overpriced method signature.

The overpriced method should return an array of ints but you're returning an array of doubles.

Put your return statement outside of the for loop.

In the main method, change isOverprices to an int array

```<code>  public static void main(String[] args) {
    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    int isOverprices [] = overpriced(stockV);
    for(int i: isOverprices) {
      System.out.println(i);
    }
  }
  public static int [] overpriced(double[] rsiValues){
    int result [] = new int[rsiValues.length];
    for (int i = 0; i < rsiValues.length; i++)
    {
      if (rsiValues[i] > 70)
      {
          result[i] = 1;
      }
      else if (rsiValues[i] <= 70)
      {
          result[i] = 0;
      }
    }
    return result;
  }
</code>```

Body:
I am trying to have the method return the new array that was made by the for loop.

import java.util.Arrays;
public class stocks {

public static void main(String[] args) {

    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    double isOverprices [] = overpriced(stockV);

}
    public int [] overpriced(double[] rsiValues)
    {
        for (int i = 0; i < rsiValues.length; i++)
        {
            if (rsiValues[i] > 70)
            {
                rsiValues[i] = 1;
            }
            else if (rsiValues[i] <= 70)
            {
                rsiValues[i] = 0;
            }
            return rsiValues;
        }
    }
 }

Body:
Add 'static' to the overpriced method signature.

The overpriced method should return an array of ints but you're returning an array of doubles.

Put your return statement outside of the for loop.

In the main method, change isOverprices to an int array

  public static void main(String[] args) {
    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    int isOverprices [] = overpriced(stockV);
    for(int i: isOverprices) {
      System.out.println(i);
    }
  }
  public static int [] overpriced(double[] rsiValues){
    int result [] = new int[rsiValues.length];
    for (int i = 0; i < rsiValues.length; i++)
    {
      if (rsiValues[i] > 70)
      {
          result[i] = 1;
      }
      else if (rsiValues[i] <= 70)
      {
          result[i] = 0;
      }
    }
    return result;
  }


问:
finding list with most elements
Here are 3 lists:

```<code>test1 = ['a','a','a','a','a']
test2 = ['b','b,'b']
test3 = ['c','c','c','c','c','c','c','c']
</code>```

How can I output the list with most elements? This solution below is from @Rifat Alptekin Çetin:Python: How do I find the list with the most elements in it but this outputs a 'string' defined by dictionary. How do I output the list with most elements?

```<code>lists=[test1, test2, test3]
listnames=["list1", "list2", "list3"]

most = listnames[np.argmax([len(l) for l in lists])]
</code>```

Current output

```<code>most = 'list3'
</code>```

Desired output

```<code>most = test3
</code>```

答:
```<code>>>> test1 = ['a','a','a','a','a']
>>> test2 = ['b', 'b', 'b']
>>> test3 = ['c','c','c','c','c','c','c','c']
>>> lists = [test1, test2, test3]
>>> max(lists, key=len)
['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
</code>```

This gives you the actual list and not the string name you were talking about

```<code>>>> assert max(lists, key=len) == test3
>>>
</code>```

Title: finding list with most elements

Body:
Here are 3 lists:

test1 = ['a','a','a','a','a']
test2 = ['b','b,'b']
test3 = ['c','c','c','c','c','c','c','c']

How can I output the list with most elements? This solution below is from @Rifat Alptekin Çetin:Python: How do I find the list with the most elements in it but this outputs a 'string' defined by dictionary. How do I output the list with most elements?

lists=[test1, test2, test3]
listnames=["list1", "list2", "list3"]

most = listnames[np.argmax([len(l) for l in lists])]

Current output

most = 'list3'

Desired output

most = test3

Body:
>>> test1 = ['a','a','a','a','a']
>>> test2 = ['b', 'b', 'b']
>>> test3 = ['c','c','c','c','c','c','c','c']
>>> lists = [test1, test2, test3]
>>> max(lists, key=len)
['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']

This gives you the actual list and not the string name you were talking about

>>> assert max(lists, key=len) == test3
>>>


答:
This will get you the longest list using list-comprehension:

```<code>most = [x for x in [test1,test2,test3] if len(x) == max([len(y) for y in [test1,test2,test3]])][0]
</code>```

Basically, it makes a list of the lists's lengths, picks the biggest, then chooses the first of the lists with that length.

Title: finding list with most elements

Body:
This will get you the longest list using list-comprehension:

most = [x for x in [test1,test2,test3] if len(x) == max([len(y) for y in [test1,test2,test3]])][0]

Basically, it makes a list of the lists's lengths, picks the biggest, then chooses the first of the lists with that length.


问:
SQL query with conditional join based on a table variable
I need to write a SQL query and want to check if this is the optimized approach. If not, what would be a better query for this scenario?

All the joining tables are pretty big(approx 150million records).

Below is the sample code.

```<code>DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT * FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1 OR @inputVar IS NULL
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2 OR @inputVar IS NULL
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID OR @inputVar IS NULL
WHERE tbl1.Key = 'blah'
</code>```

Here, my expected output is as follows:-

If @inputVar is NULL, return all records from TABLE1.

If @inputVar is NOT NULL, join with 2 other tables and return only the filtered records. Join with 2 other tables is required because the passed-in variable is a comma-separated id list which is present in TABLE3.

Any help would be appreciated.

答:
The easiest way to do this is going to be to create two queries and UNION ALL them together. Each "half" of the UNION ALL will handle the possible values of @inputVar. One query for when the variable is NULL, and one for when it isn't.

```<code>DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT
    tbl1.JoinIndex1
    ,JoinIndex2 = NULL
    ,JoinIndex3 = NULL
FROM TABLE1 tbl1
WHERE @inputVar IS NULL
    AND tbl1.Key = 'blah'

UNION ALL

SELECT
    tbl1.JoinIndex1
    ,tbl2.JoinIndex2
    ,tbl3.JoinIndex3
FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID
WHERE @inputVar IS NOT NULL
    AND tbl1.Key = 'blah'
</code>```

You should only ever get records from the first half or the second half of the UNION ALL. You'll also want to make sure your column list is the same in both halves. If you need any column names in the first half of the query that are only present in TABLE2, you can just stick a NULL with the correct alias. Notice the JoinIndex2 = NULL in the first half.

Body:
I need to write a SQL query and want to check if this is the optimized approach. If not, what would be a better query for this scenario?

All the joining tables are pretty big(approx 150million records).

Below is the sample code.

DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT * FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1 OR @inputVar IS NULL
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2 OR @inputVar IS NULL
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID OR @inputVar IS NULL
WHERE tbl1.Key = 'blah'

Here, my expected output is as follows:-

If @inputVar is NULL, return all records from TABLE1.

If @inputVar is NOT NULL, join with 2 other tables and return only the filtered records. Join with 2 other tables is required because the passed-in variable is a comma-separated id list which is present in TABLE3.

Any help would be appreciated.

Body:
The easiest way to do this is going to be to create two queries and UNION ALL them together. Each "half" of the UNION ALL will handle the possible values of @inputVar. One query for when the variable is NULL, and one for when it isn't.

DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT
    tbl1.JoinIndex1
    ,JoinIndex2 = NULL
    ,JoinIndex3 = NULL
FROM TABLE1 tbl1
WHERE @inputVar IS NULL
    AND tbl1.Key = 'blah'

UNION ALL

SELECT
    tbl1.JoinIndex1
    ,tbl2.JoinIndex2
    ,tbl3.JoinIndex3
FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID
WHERE @inputVar IS NOT NULL
    AND tbl1.Key = 'blah'

You should only ever get records from the first half or the second half of the UNION ALL. You'll also want to make sure your column list is the same in both halves. If you need any column names in the first half of the query that are only present in TABLE2, you can just stick a NULL with the correct alias. Notice the JoinIndex2 = NULL in the first half.


问:
Elastic search XContent Provider
Help required on the below exception.
Intermittent error with elastic search restHighlevel client.

we were not able to reproduce this in local.

`

```<code>Caused by: java.util.ServiceConfigurationError: org.elasticsearch.plugins.spi.NamedXContentProvider: Provider org.elasticsearch.client.indexlifecycle.IndexLifecycleNamedXContentProvider not a subtype
    at java.util.ServiceLoader.fail(ServiceLoader.java:239)
    at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:376)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at org.elasticsearch.client.RestHighLevelClient.getProvidedNamedXContents(RestHighLevelClient.java:1887)
</code>```

`

答:
I recently experienced this same issue when trying to use the high level client as part of a more complex application. Using the client in a standalone project worked fine however. I'm still tracking down the cause of the issue, but how I fixed it was by modifying the high level client source code to explicitly set the class loader to be used by ServiceLoader.load. Specifically, the change I made was to the getProvidedNamedXContents() method in the RestHighLevelClient class:

Original:

```<code>static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
    List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
    for (NamedXContentProvider service : ServiceLoader.load(NamedXContentProvider.class)) {
        entries.addAll(service.getNamedXContentParsers());
    }
    return entries;
}
</code>```

Modified:

```<code>static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
    List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
    Class<NamedXContentProvider> namedXContentProviderClass = NamedXContentProvider.class;
    for (NamedXContentProvider service : ServiceLoader.load(namedXContentProviderClass, namedXContentProviderClass.getClassLoader())) {
        entries.addAll(service.getNamedXContentParsers());
    }
    return entries;
}
</code>```

After rebuilding the client with these changes the issue no longer occurred for me. I hope this helps

Title: Elastic search XContent Provider

Body:
Help required on the below exception.
Intermittent error with elastic search restHighlevel client.

we were not able to reproduce this in local.

`

Caused by: java.util.ServiceConfigurationError: org.elasticsearch.plugins.spi.NamedXContentProvider: Provider org.elasticsearch.client.indexlifecycle.IndexLifecycleNamedXContentProvider not a subtype
    at java.util.ServiceLoader.fail(ServiceLoader.java:239)
    at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:376)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at org.elasticsearch.client.RestHighLevelClient.getProvidedNamedXContents(RestHighLevelClient.java:1887)

`

Body:
I recently experienced this same issue when trying to use the high level client as part of a more complex application. Using the client in a standalone project worked fine however. I'm still tracking down the cause of the issue, but how I fixed it was by modifying the high level client source code to explicitly set the class loader to be used by ServiceLoader.load. Specifically, the change I made was to the getProvidedNamedXContents() method in the RestHighLevelClient class:

Original:

static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
    List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
    for (NamedXContentProvider service : ServiceLoader.load(NamedXContentProvider.class)) {
        entries.addAll(service.getNamedXContentParsers());
    }
    return entries;
}

Modified:

static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
    List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
    Class<NamedXContentProvider> namedXContentProviderClass = NamedXContentProvider.class;
    for (NamedXContentProvider service : ServiceLoader.load(namedXContentProviderClass, namedXContentProviderClass.getClassLoader())) {
        entries.addAll(service.getNamedXContentParsers());
    }
    return entries;
}

After rebuilding the client with these changes the issue no longer occurred for me. I hope this helps


问:
Data Table Solution In R To Find Group Min/Max
Data

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))
</code>```

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

答:
Using data.table

```<code>library(data.table)

setDT(data)
data[, c("min", "max"):= list(min(score, na.rm = TRUE),
                              max(score,  na.rm = TRUE)), student]
data
#   student score min max
#1:       1    NA   6   7
#2:       1     7   6   7
#3:       1     6   6   7
#4:       2     6   1   6
#5:       2     1   1   6
#6:       2     4   1   6
#7:       3     8   3   8
#8:       3    NA   3   8
#9:       3     3   3   8
</code>```

Or with dplyr

```<code>library(dplyr)
data %>%
  group_by(student) %>%
  mutate(min =  min(score, na.rm = TRUE), max = max(score, na.rm = TRUE))
</code>```

Body:
Data

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

Body:
Using data.table

library(data.table)

setDT(data)
data[, c("min", "max"):= list(min(score, na.rm = TRUE),
                              max(score,  na.rm = TRUE)), student]
data
#   student score min max
#1:       1    NA   6   7
#2:       1     7   6   7
#3:       1     6   6   7
#4:       2     6   1   6
#5:       2     1   1   6
#6:       2     4   1   6
#7:       3     8   3   8
#8:       3    NA   3   8
#9:       3     3   3   8

Or with dplyr

library(dplyr)
data %>%
  group_by(student) %>%
  mutate(min =  min(score, na.rm = TRUE), max = max(score, na.rm = TRUE))


问:
Turning ethernet on and off on android
Is there a way to turn ethernet on and off programatically, similarly to how WiFi can be turned on and off through the WiFiManager class? I believe ifconfig down/up will not work as it would require root. I treid doing ifconfig wlan0 down in a terminal emulator, which gave me permission denied.

I'm on a non-rooted device.

答:
firstly, you should know, since android Q, WifiManager class is not worked.

This method was deprecated in API level 29.
  Starting with Build.VERSION_CODES#Q, applications are not allowed to enable/disable Wi-Fi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false and will have no effect. If apps are targeting an older SDK ( Build.VERSION_CODES.P or below), they can continue to use this API.

Both for the network and wifi, I suggest you show a permission dialog, let the user open it, it matches the android permission manager.

you can use the following code to  open the setting

```<code>Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("com.android.settings",
                "com.android.settings.Settings$DataUsageSummaryActivity"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

</code>```

if the target SDK below Q, you can try to use the reflect way.

```<code>private void setMobileDataEnabled(Context context, boolean enabled) throws Exception{
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Class conmanClass = null;
    try {
        conmanClass = Class.forName(conman.getClass().getName());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);
    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
</code>```

Title: Turning ethernet on and off on android

Body:
firstly, you should know, since android Q, WifiManager class is not worked.

This method was deprecated in API level 29.
  Starting with Build.VERSION_CODES#Q, applications are not allowed to enable/disable Wi-Fi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false and will have no effect. If apps are targeting an older SDK ( Build.VERSION_CODES.P or below), they can continue to use this API.

Both for the network and wifi, I suggest you show a permission dialog, let the user open it, it matches the android permission manager.

you can use the following code to  open the setting

Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("com.android.settings",
                "com.android.settings.Settings$DataUsageSummaryActivity"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

if the target SDK below Q, you can try to use the reflect way.

private void setMobileDataEnabled(Context context, boolean enabled) throws Exception{
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Class conmanClass = null;
    try {
        conmanClass = Class.forName(conman.getClass().getName());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);
    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}


问:
Align Legend Title in tmap
Is it possible to center the legend title in tmap? Utilizing the first example from the tmap getting started vignette:

```<code>library(tmap)
data("World")

tm_shape(World) +
  tm_polygons("HPI")
</code>```

yields

but I want:

I have scoured the documentation for tm_layout but can't figure out how to align the text of the legend title. It seems that the only options for legend.title in tm_layout are (1) legend.title.color, (2) legend.title.size, (3) legend.title.fontface, and (4) legend.title.fontfamily, none of which control the alignment. Am I missing something obvious?

答:
Well... aparently there is not an argument to control the location of the legend title, have you considered report this as an issue?

A workaround though could be:

```<code>library(tmap)
data("World")

tm_shape(World) +
  tm_polygons("HPI",
              title = "     HPI")
</code>```

Yes, I know how ugly this looks, but it gets you the result.

Title: Align Legend Title in tmap

Body:
Is it possible to center the legend title in tmap? Utilizing the first example from the tmap getting started vignette:

library(tmap)
data("World")

tm_shape(World) +
  tm_polygons("HPI")

yields

but I want:

I have scoured the documentation for tm_layout but can't figure out how to align the text of the legend title. It seems that the only options for legend.title in tm_layout are (1) legend.title.color, (2) legend.title.size, (3) legend.title.fontface, and (4) legend.title.fontfamily, none of which control the alignment. Am I missing something obvious?

Body:
Well... aparently there is not an argument to control the location of the legend title, have you considered report this as an issue?

A workaround though could be:

library(tmap)
data("World")

tm_shape(World) +
  tm_polygons("HPI",
              title = "     HPI")

Yes, I know how ugly this looks, but it gets you the result.