问:
Dynamically create a class which derived from an ABC class
I am using PyMongo custom bson encoder. Because the encoder cannot be inherited, it needs to be created for every class, so I want to dynamically create an encoder for it.

The problem is that the base encoder (TypeEncoder) is created from ABC class. When I was trying to create the class using this code:

```<code>from bson.codec_options import TypeEncoder

cls_encoder = type(f"Flag{cls.__name__}Encoder",
                   (TypeEncoder,),
                   {"transform_python": lambda self, value: value.code,
                    "python_type": property(lambda self: cls)})
</code>```

The result will be

```<code>>> isinstance(cls_encoder, TypeEncoder)
False
>> type(cls_encoder)
<class 'abc.FlagAutoReplyContentTypeEncoder'>
>> super(cls_encoder)
<super: <class 'FlagAutoReplyContentTypeEncoder'>, NULL>
</code>```

The expected result should be

```<code>>> isinstance(cls_encoder, TypeEncoder)
True
</code>```

Note: the cls variable will be an Enum
Note: python_type is an abstractproperty; transform_python is a function which accepts the value in the type of python_type and returns something which type is valid for bson serialization.

I have tried this:

```<code>class FlagBsonEncoder(TypeEncoder):
    def transform_python(self, value):
        return value.code

cls_encoder = type(f"Flag{cls.__name__}Encoder",
                   (FlagBsonEncoder,),
                   {"python_type": property(lambda self: cls)})
</code>```

But still the same result:

```<code>>> isinstance(cls_encoder, TypeEncoder)
False
</code>```

Here is the official example of how to use custom type encoding:
http://api.mongodb.com/python/current/api/bson/codec_options.html
http://api.mongodb.com/python/current/examples/custom_type.html#custom-type-type-codec

答:
You misunderstand what isinstance does, I think.

isinstance(cls_encoder, TypeEncoder) asks if the class object cls_encoder is an instance of TypeEncoder. Of course it is not - it is a type!

What you want is isinstance(cls_encoder(), TypeEncoder), which asks if an instance of cls_encoder is also an instance of TypeEncoder, which of course must be true.

If you want to check if the class cls_encoder is a subclass of TypeEncoder, you can use issubclass(cls_encoder, TypeEncoder).

Body:
I am using PyMongo custom bson encoder. Because the encoder cannot be inherited, it needs to be created for every class, so I want to dynamically create an encoder for it.

The problem is that the base encoder (TypeEncoder) is created from ABC class. When I was trying to create the class using this code:

from bson.codec_options import TypeEncoder

cls_encoder = type(f"Flag{cls.__name__}Encoder",
                   (TypeEncoder,),
                   {"transform_python": lambda self, value: value.code,
                    "python_type": property(lambda self: cls)})

The result will be

>> isinstance(cls_encoder, TypeEncoder)
False
>> type(cls_encoder)
<class 'abc.FlagAutoReplyContentTypeEncoder'>
>> super(cls_encoder)
<super: <class 'FlagAutoReplyContentTypeEncoder'>, NULL>

The expected result should be

>> isinstance(cls_encoder, TypeEncoder)
True

Note: the cls variable will be an Enum
Note: python_type is an abstractproperty; transform_python is a function which accepts the value in the type of python_type and returns something which type is valid for bson serialization.

I have tried this:

class FlagBsonEncoder(TypeEncoder):
    def transform_python(self, value):
        return value.code

cls_encoder = type(f"Flag{cls.__name__}Encoder",
                   (FlagBsonEncoder,),
                   {"python_type": property(lambda self: cls)})

But still the same result:

>> isinstance(cls_encoder, TypeEncoder)
False

Here is the official example of how to use custom type encoding:
http://api.mongodb.com/python/current/api/bson/codec_options.html
http://api.mongodb.com/python/current/examples/custom_type.html#custom-type-type-codec


来源: stackexchange

问:
Create unique ID's in VFP
I need to create unique record id's in VFP based on mailing information: zip5, address, lastname, firstname.  Once created, relational tables will be loaded in SQL server 7 with the unique ID's. Any suggestinos?</p>

答:
VFP does have support for unique IDs - in that it has Primary Indexes (which can be based on multiple fields - but make sure the key length is fixed, so if your VFP table uses varchars you will need to pad the fields) and a table can also have Candidate Indexes (where the indexed field(s) must be unique, just like a primary key, but you can have multiple candidate indexes per table).

Either of these will enforce uniqueness in your fields, but generating a primary key based on zip5, address, lastname and firstname will be inefficient. The suggestion of GUIDs will work nicely, or if you have VFP8 or later you can use an Autoinc column, which is analogous to an Identity column in SQL Server.

Incidentally, unique indexes are only used for backward compatibility..

ContentLicense: CC BY-SA 2.5

Title: Create unique ID's in VFP

OwnerDisplayName: Stuart Dunkeld


问:
openGL texture mapping
Hey,
 I am creating a game using openGL in c++
when I try and map a texture to an object it changes the colour of everything else I have drawn
eg everything goes a transparent red or green..

```<code>glEnable (GL_TEXTURE_2D);
    Bitmap image;
    image.loadBMP ("Texture.bmp");

    glGenTextures(1, &m_TextureID);
    glBindTexture ( GL_TEXTURE_2D, m_TextureID);

    glTexEnvf ( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gluBuild2DMipmaps ( GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB,    GL_UNSIGNED_BYTE, image.data);
    glEnd();
</code>```

this is my texture code and here is how i am mapping the texture

```<code>glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);
//glColor3d(1, 0, 0);
glTexCoord2f (0.0f,0.0f);
glVertex3f(0, 0, 0); // bottom left
glTexCoord2f (1.0f,0.0f);
glVertex3f(10, 0, 0); // bottom right
glTexCoord2f (1.0f,1.0f);
glVertex3f(10, 0.6, 0);// top right
glTexCoord2f (0.0f,1.0f);
glVertex3f(0, 0.6, 0); // top left
glEnd();
</code>```

etc...

all my non textured objects are drawn like this

```<code>glBegin(GL_QUADS);//BACK
glColor3d(1,0,0);
glVertex3f(10, 0, 0);
glVertex3f(10, 0, -5.6);
glVertex3f(10, 0.6, -5.6);
glVertex3f(10, 0.6, 0);
glEnd();
</code>```

etc...
am i missing something really obvious ?
thanks

答:
You need to disable texture mapping for your other objects if you don't want them to be textured.</p>

```<code>glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
...
</code>```

ContentLicense: CC BY-SA 3.0

Title: openGL texture mapping

Body:
Hey,
 I am creating a game using openGL in c++
when I try and map a texture to an object it changes the colour of everything else I have drawn
eg everything goes a transparent red or green..

glEnable (GL_TEXTURE_2D);
    Bitmap image;
    image.loadBMP ("Texture.bmp");

    glGenTextures(1, &m_TextureID);
    glBindTexture ( GL_TEXTURE_2D, m_TextureID);

    glTexEnvf ( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gluBuild2DMipmaps ( GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB,    GL_UNSIGNED_BYTE, image.data);
    glEnd();

this is my texture code and here is how i am mapping the texture

glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);
//glColor3d(1, 0, 0);
glTexCoord2f (0.0f,0.0f);
glVertex3f(0, 0, 0); // bottom left
glTexCoord2f (1.0f,0.0f);
glVertex3f(10, 0, 0); // bottom right
glTexCoord2f (1.0f,1.0f);
glVertex3f(10, 0.6, 0);// top right
glTexCoord2f (0.0f,1.0f);
glVertex3f(0, 0.6, 0); // top left
glEnd();

etc...

all my non textured objects are drawn like this

glBegin(GL_QUADS);//BACK
glColor3d(1,0,0);
glVertex3f(10, 0, 0);
glVertex3f(10, 0, -5.6);
glVertex3f(10, 0.6, -5.6);
glVertex3f(10, 0.6, 0);
glEnd();

etc...
am i missing something really obvious ?
thanks

Body:
You need to disable texture mapping for your other objects if you don't want them to be textured.

glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
...


问:
How to know which params is missing in a query?
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

```<code>let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }
</code>```

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })
```

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information

答:
Read the documentation or the source code.

Seriously. If the API response doesn't tell you in the error message, then there is no way to know what parameters it expects programmatically.

ContentLicense: CC BY-SA 4.0

Body:
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information


问:
Dropbox integration using oAuth2 Url in React Native Android is not working with handleOpenUrl
I have successfully integrated dropbox oAuth2 and Writing files to dropbox in react native for iOS. Same code is not working for Android.

I am using  oAuth Url and handleOpenUrl in react native  to read the incoming links in Android.

It opens the Dropbox website with the OAuthUrl and authorizes the user. In  Dropbox website when it asks permission to access files and folders, when we tap on "Allow" it doesn't open my app.

So the control is not passed back and it doesn't call handleOpenUrl method. Not sure what I am missing.

I also tried with below method:

```<code>Linking.getInitialURL().then((url) => {
        if (url) {
          console.log('Initial url is: ' + url);
          this.navigate(url);
      }
</code>```

But this gives url  comes as undefined.

In AndroidManifest.XML file I added the intent filter and permissions :

```<code><uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https"
          android:host="www.dropbox.com" />

        <data android:scheme="https"
          android:host="www.dropbox.com/oauth2/authorize" />
<!-- Oauth2 redirect url set when dropbox app is created -->
        <data android:scheme="com.companyname.appname.oauth"
          android:host="oauthredirect" />
      </intent-filter>
</code>```

In Activity tag added  android:launchMode="singleTask".

Below is the code snippet of React Native code :

```<code>export class DropboxAuthorize implements Authorize {
constructor() {

    this._handleOpenURL = this._handleOpenURL.bind(this);
  }

  // Authorize with Dropbox. Uses the device's browser to work through the Dropbox
  // OAuth 2 process, eventually recording a token and account ID if successful.
  public authorize(): Promise<void> {
    console.log("Authorization starting...");
    // Generate a random string for Dropbox's state param.
    // This helps us be sure a deep link into the app is indeed related to the request
    // we made to Dropbox.
    const stateValue = Math.random().toString();
     console.log("authorize stateValue",stateValue);
    // Open the Dropbox authorization page in the device browser
    return Linking.openURL(
      [
        'https://www.dropbox.com/oauth2/authorize',
        "?response_type=token",
        `&client_id=${DROPBOX.OAUTH_CLIENT_ID}`,
        `&redirect_uri=${DROPBOX.OAUTH_REDIRECT_URI}`,
        `&state=${stateValue}`
      ].join("")
    )
      .catch(err =>
        console.error(
          "An error occurred trying to open the browser to authorize with Dropbox:",
          err
        )
      )
      .then(() => {
        return new Promise((resolve, reject) => {
          const handleOpenURL = (event: { url: string }) => {
            console.log("event", event);
            this._handleOpenURL(event, stateValue)
              .then(() => {
                resolve();
              })
              .catch(reason => {
                reject(reason);
              })
              .then(() => {
                // "Finally" block
                // Remove deep link event listener
                Linking.removeEventListener("url", handleOpenURL);
                return;
              });

          };
           console.log("Hi there");
          // Add deep link event listener to catch when Dropbox sends the user back to the app.
          Linking.addEventListener("url", handleOpenURL);
        });
      });
  }

  private _handleOpenURL(
    event: { url: string },
    stateValue: string
  ): Promise<void> {
    console.log("Deep link event!", event);
    console.log("State Value",stateValue);
    const queryStringResult = event.url.match(/\#(.*)/);
    if (queryStringResult === null || queryStringResult.length < 2) {
      return Promise.reject(
        "Did not receive a query string as part of this deep link!"
      );
    }

    const [, queryString] = queryStringResult;
    const parsedQueryString = shittyQs(queryString);
    console.log ("parsedQueryString",parsedQueryString);
    if (parsedQueryString.error) {
      // There was an error!
      const errorCode = parsedQueryString.error;
      const errorDescription = parsedQueryString.error_description;

      console.error("Dropbox OAuth error! code:", errorCode);
      console.error("Error description:", errorDescription);

      return Promise.reject(
        `Could not authorize with Dropbox. Code: ${errorCode}`
      );
    }

      if (parsedQueryString.state){
        if (stateValue !== parsedQueryString.state) {
          // This value must match! This is a security feature of Dropbox's OAuth impl
          return Promise.reject("State parameter DID NOT MATCH!");
        }
      }
    // Otherwise: not an error!
    const accessToken = parsedQueryString.access_token;
    const accountId = parsedQueryString.account_id;

    // Persist accessToken and accountId
    return AsyncStorage.setItem(DROPBOX.ACCESS_TOKEN_STORAGE_KEY, accessToken)
      .then(() => {
     /*    return AsyncStorage.setItem(DROPBOX.ACCOUNT_ID_STORAGE_KEY, accountId);
      })
      .then(() => { */
        console.log(
          "Dropbox OAuth authorization success! Access Token:",
          accessToken
        );
       /*  console.log(
          "Dropbox OAuth authorization success! Account ID:",
          accountId
        ); */
        return;
      });
  }
</code>```

Let me know if any alternative method is available to read the incoming links.

答:
I solved this issue by creating a redirect Url in my dropbox apps : company_name://open
Then in AndroidManifest.xml file i  added the scheme and host as below :
 </p>

Body:
I have successfully integrated dropbox oAuth2 and Writing files to dropbox in react native for iOS. Same code is not working for Android.

I am using  oAuth Url and handleOpenUrl in react native  to read the incoming links in Android.

It opens the Dropbox website with the OAuthUrl and authorizes the user. In  Dropbox website when it asks permission to access files and folders, when we tap on "Allow" it doesn't open my app.

So the control is not passed back and it doesn't call handleOpenUrl method. Not sure what I am missing.

I also tried with below method:

Linking.getInitialURL().then((url) => {
        if (url) {
          console.log('Initial url is: ' + url);
          this.navigate(url);
      }

But this gives url  comes as undefined.

In AndroidManifest.XML file I added the intent filter and permissions :

<uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https"
          android:host="www.dropbox.com" />

        <data android:scheme="https"
          android:host="www.dropbox.com/oauth2/authorize" />

        <data android:scheme="com.companyname.appname.oauth"
          android:host="oauthredirect" />
      </intent-filter>

In Activity tag added  android:launchMode="singleTask".

Below is the code snippet of React Native code :

export class DropboxAuthorize implements Authorize {
constructor() {

    this._handleOpenURL = this._handleOpenURL.bind(this);
  }

  // Authorize with Dropbox. Uses the device's browser to work through the Dropbox
  // OAuth 2 process, eventually recording a token and account ID if successful.
  public authorize(): Promise<void> {
    console.log("Authorization starting...");
    // Generate a random string for Dropbox's state param.
    // This helps us be sure a deep link into the app is indeed related to the request
    // we made to Dropbox.
    const stateValue = Math.random().toString();
     console.log("authorize stateValue",stateValue);
    // Open the Dropbox authorization page in the device browser
    return Linking.openURL(
      [
        'https://www.dropbox.com/oauth2/authorize',
        "?response_type=token",
        `&client_id=${DROPBOX.OAUTH_CLIENT_ID}`,
        `&redirect_uri=${DROPBOX.OAUTH_REDIRECT_URI}`,
        `&state=${stateValue}`
      ].join("")
    )
      .catch(err =>
        console.error(
          "An error occurred trying to open the browser to authorize with Dropbox:",
          err
        )
      )
      .then(() => {
        return new Promise((resolve, reject) => {
          const handleOpenURL = (event: { url: string }) => {
            console.log("event", event);
            this._handleOpenURL(event, stateValue)
              .then(() => {
                resolve();
              })
              .catch(reason => {
                reject(reason);
              })
              .then(() => {
                // "Finally" block
                // Remove deep link event listener
                Linking.removeEventListener("url", handleOpenURL);
                return;
              });

          };
           console.log("Hi there");
          // Add deep link event listener to catch when Dropbox sends the user back to the app.
          Linking.addEventListener("url", handleOpenURL);
        });
      });
  }

  private _handleOpenURL(
    event: { url: string },
    stateValue: string
  ): Promise<void> {
    console.log("Deep link event!", event);
    console.log("State Value",stateValue);
    const queryStringResult = event.url.match(/\#(.*)/);
    if (queryStringResult === null || queryStringResult.length < 2) {
      return Promise.reject(
        "Did not receive a query string as part of this deep link!"
      );
    }

    const [, queryString] = queryStringResult;
    const parsedQueryString = shittyQs(queryString);
    console.log ("parsedQueryString",parsedQueryString);
    if (parsedQueryString.error) {
      // There was an error!
      const errorCode = parsedQueryString.error;
      const errorDescription = parsedQueryString.error_description;

      console.error("Dropbox OAuth error! code:", errorCode);
      console.error("Error description:", errorDescription);

      return Promise.reject(
        `Could not authorize with Dropbox. Code: ${errorCode}`
      );
    }

      if (parsedQueryString.state){
        if (stateValue !== parsedQueryString.state) {
          // This value must match! This is a security feature of Dropbox's OAuth impl
          return Promise.reject("State parameter DID NOT MATCH!");
        }
      }
    // Otherwise: not an error!
    const accessToken = parsedQueryString.access_token;
    const accountId = parsedQueryString.account_id;

    // Persist accessToken and accountId
    return AsyncStorage.setItem(DROPBOX.ACCESS_TOKEN_STORAGE_KEY, accessToken)
      .then(() => {
     /*    return AsyncStorage.setItem(DROPBOX.ACCOUNT_ID_STORAGE_KEY, accountId);
      })
      .then(() => { */
        console.log(
          "Dropbox OAuth authorization success! Access Token:",
          accessToken
        );
       /*  console.log(
          "Dropbox OAuth authorization success! Account ID:",
          accountId
        ); */
        return;
      });
  }

Let me know if any alternative method is available to read the incoming links.


问:
QListWidgetItem when button clicked do actions
I have a QListWidget with some items. I did this to select an item from QListWidget:

```<code>connect(ui->mylist,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(onMyListItem(QListWidgetItem*)));
</code>```

Now in onMyListItem function I did this to check the index of the item:

```<code>int index=ui->mylist->currentRow();
    qDebug()<<"index item: "<<index;
</code>```

How can I do some actions when I select an item and click a showBtn button?

答: If you are adding a button to your QListWidget , create an slot and connect your button signal to slot. by clicking the button , you can check witch item is selected and you can do what you want</p>

Body:
I have a QListWidget with some items. I did this to select an item from QListWidget:

connect(ui->mylist,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(onMyListItem(QListWidgetItem*)));

Now in onMyListItem function I did this to check the index of the item:

int index=ui->mylist->currentRow();
    qDebug()<<"index item: "<<index;

How can I do some actions when I select an item and click a showBtn button?


问:
Creating a a range within a databodyrange
I have a sub that updates a graph with the series based within a table. However, the first row of the table is blank and I want to omit that from my series collection. I thought of creating a range within my databody range and use that. This is my code:

```<code>Sub UpdateGraph()

Dim rng_pf As Variant, rng_bm As Variant, rng_date As Variant,
Dim lr as integer

' Defining ranges
With ThisWorkbook.Sheets("Time series")
         lr = .ListObjects(1).ListColumns(1).Range.Rows.Count + 6 ' This corresponds to the last row in my table
         rng_pf = .ListObjects(1).ListColumns("PF").DataBodyRange(2, lr) ' <-- This doesnt work
         rng_bm = .ListObjects(1).ListColumns("BM").DataBodyRange(2, lr)
         rng_date = .ListObjects(1).ListColumns("Date").DataBodyRange(2, lr)
End With

' Updating chart
With Sheets(1).ChartObjects("Chart 1").Chart
    .FullSeriesCollection(1).Values = rng_pf
    .FullSeriesCollection(2).Values = rng_bm
    .FullSeriesCollection(1).XValues = rng_date
    .FullSeriesCollection(2).XValues = rng_date
End With

End sub
</code>```

I thought of creating an array that is based on the databodyrange and then removing the first element of the array, but that seems to be overkill.
When running my code I get that rng_pf is Empty.
My table:

答:
You should define ranges a bit better, but meanwhile give this a try?

Sub UpdateGraph()

Dim rng_pf As Range, rng_bm As Range, rng_date As Range

' Defining ranges
With ThisWorkbook.Sheets("Time series")
        With .ListObjects(1)
            With .ListColumns("PF")
                Set rng_pf = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
            End With
            With .ListColumns("BM")
                Set rng_bm = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
            End With
            With .ListColumns("Date")
                Set rng_date = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
            End With
        End With
End With

' Updating chart
With Sheets(1).ChartObjects("Chart 1").Chart
    .FullSeriesCollection(1).Values = rng_pf
    .FullSeriesCollection(2).Values = rng_bm
    .FullSeriesCollection(1).XValues = rng_date
    .FullSeriesCollection(2).XValues = rng_date
End With

End Sub
```vba

**EDIT:** minor code cleanup as per OP suggestion.
</code>```

Body:
I have a sub that updates a graph with the series based within a table. However, the first row of the table is blank and I want to omit that from my series collection. I thought of creating a range within my databody range and use that. This is my code:

Sub UpdateGraph()

Dim rng_pf As Variant, rng_bm As Variant, rng_date As Variant,
Dim lr as integer

' Defining ranges
With ThisWorkbook.Sheets("Time series")
         lr = .ListObjects(1).ListColumns(1).Range.Rows.Count + 6 ' This corresponds to the last row in my table
         rng_pf = .ListObjects(1).ListColumns("PF").DataBodyRange(2, lr) ' <-- This doesnt work
         rng_bm = .ListObjects(1).ListColumns("BM").DataBodyRange(2, lr)
         rng_date = .ListObjects(1).ListColumns("Date").DataBodyRange(2, lr)
End With

' Updating chart
With Sheets(1).ChartObjects("Chart 1").Chart
    .FullSeriesCollection(1).Values = rng_pf
    .FullSeriesCollection(2).Values = rng_bm
    .FullSeriesCollection(1).XValues = rng_date
    .FullSeriesCollection(2).XValues = rng_date
End With

End sub

I thought of creating an array that is based on the databodyrange and then removing the first element of the array, but that seems to be overkill.
When running my code I get that rng_pf is Empty.
My table:


问:
jquery+jstree in .net - webservice responseformat?
I have been playing with jstree (1.0rc2)+jquery (1.4.2) for the first time with c#.net and although I have gotten it working, there are a couple things that I don't understand about how data is provided to the tree by the webservice I use to populate the tree (using ajax and the json_data plug-in). I was hoping someone with more experience using jstree could provide some insight.

The jstree config looks like this:

```<code> "json_data": {
                "ajax": {
                    "url": "GetTree.asmx/GetChildren",
                    "type": "POST",
                    "contentType": "application/json; charset=utf-8",
                    "dataType": "json",
                    "data": function(n) {
                        var result = "{'id':'" + (n.attr ? n.attr("id").replace("node_", "") : "0") + "'}";
                        return (result);
                    }
                }
            }
</code>```

GetTree.asmx GetChildren method:

```<code>   [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml )]
    public string GetChildren(string id)
    {
        List<jsTreeNode> jsTree = new List<jsTreeNode>();
        //... (build the tree as needed)

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return(serializer.Serialize(jsTree));
    }
</code>```

Question 1: So everything works great, so what's the problem? The problem is "ResponseFormat = ResponseFormat.Xml". I struggled for a while to get this working because it did not work when it was set to ResponseFormat.Json, which is what I would expect it to be. In that situation, no errors would be reported by the web service or by jQuery when parsing the json response, but the tree would render empty.

In looking at the HTML output of the web service, I could see no difference between what was rendered either way. I was hoping someone could explain why this works (counterintuitively) and why it does not work with ResponseFormat.Json, and if this is indicative of something else I might be doing wrong.

Question 2: Generally, web service or web handler?

Would using a generic web handler (ashx) be a more efficient way to do this anyway? Is there a substantial difference in the overhead required of a standard web service versus a generic web handler? Since my goal is basically to control exactly what is output (and using the json data format in the web service doesn't seem to be working the way I want it to anyway) I am not sure what benefit, if any, there is to using a web service here instead of just stripping it down completely. On the other hand this works now so maybe I should leave well enough alone.

答:
Seeing as this question has almost 600 views and no answers I thought I would answer it myself (since I've long since figured it out).

Using a ScriptMethod is really not the right way to communicate with jQuery ajax. While it can be done, you will notice what I was doing above is returning a string with data that I encoded myself to JSON using JavascriptSerializer.

However, using a ScriptMethod  automatically incorporates serialization/deserialization designed to communicate with Microsoft's AJAX framework. Since serializing a pure string with no object wrapper will genererally result in the same string (whether I be returning XML or JSON format), it basically worked, but what was really happening internally is it was being serialized twice.

So what I should have done, at a minimum, was:

public List<jsTreeNode> GetChildren(string id)

that is, the return type should be the actual data type, not a string of serialized data.

However, this still wouldn't be exactly right, because Microsoft's methods wrap the return value in an object d. I could still extract that in Javascript to get the inner data. But if something like jsTree is expecting data in a predefined format this may not be workable.

The best solution is do not use WebServices, use generic handlers (ashx) instead. This gives you complete control over the format and handling of your input and output. It may take a little bit of doing to set yourself up a nice framework, but the frustration of being unable to skip parts of the WebService handling that you don't need makes it well worth it.

Body:
I have been playing with jstree (1.0rc2)+jquery (1.4.2) for the first time with c#.net and although I have gotten it working, there are a couple things that I don't understand about how data is provided to the tree by the webservice I use to populate the tree (using ajax and the json_data plug-in). I was hoping someone with more experience using jstree could provide some insight.

The jstree config looks like this:

 "json_data": {
                "ajax": {
                    "url": "GetTree.asmx/GetChildren",
                    "type": "POST",
                    "contentType": "application/json; charset=utf-8",
                    "dataType": "json",
                    "data": function(n) {
                        var result = "{'id':'" + (n.attr ? n.attr("id").replace("node_", "") : "0") + "'}";
                        return (result);
                    }
                }
            }

GetTree.asmx GetChildren method:

   [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml )]
    public string GetChildren(string id)
    {
        List<jsTreeNode> jsTree = new List<jsTreeNode>();
        //... (build the tree as needed)

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return(serializer.Serialize(jsTree));
    }

Question 1: So everything works great, so what's the problem? The problem is "ResponseFormat = ResponseFormat.Xml". I struggled for a while to get this working because it did not work when it was set to ResponseFormat.Json, which is what I would expect it to be. In that situation, no errors would be reported by the web service or by jQuery when parsing the json response, but the tree would render empty.

In looking at the HTML output of the web service, I could see no difference between what was rendered either way. I was hoping someone could explain why this works (counterintuitively) and why it does not work with ResponseFormat.Json, and if this is indicative of something else I might be doing wrong.

Question 2: Generally, web service or web handler?

Would using a generic web handler (ashx) be a more efficient way to do this anyway? Is there a substantial difference in the overhead required of a standard web service versus a generic web handler? Since my goal is basically to control exactly what is output (and using the json data format in the web service doesn't seem to be working the way I want it to anyway) I am not sure what benefit, if any, there is to using a web service here instead of just stripping it down completely. On the other hand this works now so maybe I should leave well enough alone.


问:
reuse a calculated field in the same query
I have this query.

```<code>SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

```<code>SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

答:
Mysql doesnt support using variables unless it is inside of HAVING statement, so for this to work you should rewrite it as</p>

```<code>SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

Body:
I have this query.

SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

Body:
Mysql doesnt support using variables unless it is inside of HAVING statement, so for this to work you should rewrite it as

SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca


问:
Is there an INDArray's method to perform an addition of two INDArray (with different size)?
Imagine two INDArray:

a1.shape() = [2, 3] and a1 is full of 1;

a2.shape() = [1, 2] and a2 is full of 2.

I would like to perform an addition between them such as:

```<code>?> result = a1.add(0, a2)
?> print(result)
[[3, 3, 1], [1, 1, 1]]
?> result = a1.add(1, a2)
?> print(result)
[[1, 1, 1], [3, 3, 1]]
?> result = a1.add(1, 1, a2)
?> print(result)
[[1, 1, 1], [1, 3, 3]]
</code>```

I have tried to first select a sub-array:

```<code>?> subarray = a1.get(NDArrayIndex.interval(0, 1), NDArrayIndex.interval(0, 2))
?> print(subarray)
[1, 1]
</code>```

Perform the addition:

```<code>?> subarray = subarray.add(a2)
?> print(subarray)
[3, 3]
</code>```

But I can't figure out how to insert 'subarray' into 'a1' at the good position...

Note: I simplified the problem for the sake of the explanation. The arrays being processed are 4D-arrays.

答:
I just found the following function in the documentation:

```<code>INDArray put(INDArrayIndex[] indices, INDArray element)
</code>```

This can be used as follow to solve this question:

```<code>a1.put(
  new INDArrayIndex[] {NDArrayIndex.interval(0, 1), NDArrayIndex.interval(0, 2)},
  subarray
);
</code>```

Indeed NDArrayIndex implement the INDArrayIndex interface.

Body:
Imagine two INDArray:

a1.shape() = [2, 3] and a1 is full of 1;

a2.shape() = [1, 2] and a2 is full of 2.

I would like to perform an addition between them such as:

?> result = a1.add(0, a2)
?> print(result)
[[3, 3, 1], [1, 1, 1]]
?> result = a1.add(1, a2)
?> print(result)
[[1, 1, 1], [3, 3, 1]]
?> result = a1.add(1, 1, a2)
?> print(result)
[[1, 1, 1], [1, 3, 3]]

I have tried to first select a sub-array:

?> subarray = a1.get(NDArrayIndex.interval(0, 1), NDArrayIndex.interval(0, 2))
?> print(subarray)
[1, 1]

Perform the addition:

?> subarray = subarray.add(a2)
?> print(subarray)
[3, 3]

But I can't figure out how to insert 'subarray' into 'a1' at the good position...

Note: I simplified the problem for the sake of the explanation. The arrays being processed are 4D-arrays.

Body:
I just found the following function in the documentation:

INDArray put(INDArrayIndex[] indices, INDArray element)

This can be used as follow to solve this question:

a1.put(
  new INDArrayIndex[] {NDArrayIndex.interval(0, 1), NDArrayIndex.interval(0, 2)},
  subarray
);

Indeed NDArrayIndex implement the INDArrayIndex interface.


问:
How to Delete set of XML node in C#?
Below is my XML file

```<code><MultiCentreDeals>
  <DealItem>
    <ID>24</ID>
      <Days>
        <Day>
           <DayID>24-1</DayID>
           <DayTitle>Day 13</DayTitle>
           <Title>Meeting Point</Title>
           <HotelName>15</HotelName>
        </Day>
        <Day>
           <DayID>24-2</DayID>
           <DayTitle>Day 2</DayTitle>
           <Title>Departure to Test</Title>
           <HotelName>54</HotelName>
        </Day>
       </Days>
  </DealItem>
</MultiCentreDeals>
</code>```

I want to delete the XML node set belong to ID 24 and DayID 24-2. Can anyone explain how to do this.

答:
XDocument is your friend.</p>

```<code>// Parse your XML string
var doc = XDocument.Parse(xml);

// Find the first child of type "Day", whose child of type "DayID" has the value "24-2"
var toRemove = doc.Root
    .Descendants("Day")
    .FirstOrDefault(x => x.Element("DayID").Value == "24-2");

// Remove it
toRemove?.Remove();

string result = doc.ToString();
</code>```

Title: How to Delete set of XML node in C#?

Body:
Below is my XML file

<MultiCentreDeals>
  <DealItem>
    <ID>24</ID>
      <Days>
        <Day>
           <DayID>24-1</DayID>
           <DayTitle>Day 13</DayTitle>
           <Title>Meeting Point</Title>
           <HotelName>15</HotelName>
        </Day>
        <Day>
           <DayID>24-2</DayID>
           <DayTitle>Day 2</DayTitle>
           <Title>Departure to Test</Title>
           <HotelName>54</HotelName>
        </Day>
       </Days>
  </DealItem>
</MultiCentreDeals>

I want to delete the XML node set belong to ID 24 and DayID 24-2. Can anyone explain how to do this.

Body:
XDocument is your friend.

// Parse your XML string
var doc = XDocument.Parse(xml);

// Find the first child of type "Day", whose child of type "DayID" has the value "24-2"
var toRemove = doc.Root
    .Descendants("Day")
    .FirstOrDefault(x => x.Element("DayID").Value == "24-2");

// Remove it
toRemove?.Remove();

string result = doc.ToString();


问:
back button browser causes go to home page
I would like to understand more about how to capture if a user click on the back button of the browser, and what are the basic tecniques to handle it.

As an example of this do you know how to redirect (for instance) to the user to the home page if the back button is pressed?

答: You can't and you shouldn't. Users expect their back button to work in a certain way, changing this breaks this behaviour. Bad, bad.</p>


问:
Jinja2 list is undefined
In Jinja2 I want to print the length of the 'first' value in a dictionary. In Python this would be done with the command len(list(my_dict.values())[0]).

When I try this in Jinja2 I get the error jinja2.exceptions.UndefinedError: 'list' is undefined.

Minimum working example:

```<code>from jinja2 import Template, DebugUndefined
from shutil import copyfile

def main(file_name_template, file_name_log):

    # Copy template file 'file_name_template' to 'file_name_log' so that logging can start.
    copyfile(file_name_template, file_name_log)
    template = Template(open(file_name_log).read(), undefined=DebugUndefined)

    # Define test variable 'my_dict'.
    my_dict = {'key_0': 4641896,
               'key_1': 189478415,
               'key_2': 841653}

    # Start logging.
    template_render_dict = {'my_dict': my_dict}

    # Save log to external file and possibly open upon completion of the 'main' program.
    template_rendered = template.render(template_render_dict)  # Render the template to the filled in log report.

if __name__ == "__main__":
    main("template.html", "template_rendered.html")
</code>```

with in template.html the code

```<code><!DOCTYPE html>
<html lang="en">
    <body>
        {{my_dict}}<br/>
        {{my_dict.keys()}}<br/>
        {{my_dict.values()}}<br/>
        {{len(list(my_dict.values())[0])}}<br/>
    </body>
</html>
</code>```

How do I solve this?

答:
You cannot use Python list in jinja2 template because it's not Python, it is a mark language. However, it provides a length method. Instead of:

```<code>{% if len(dict.values()[0]) > 1 %}
</code>```

You should write:

```<code>{% if dict.values()[0] | length > 1 %}

# or
{% if dict.values() | first | length > 1 %}
</code>```

Please see doc for more examples.

Title: Jinja2 list is undefined

Body:
In Jinja2 I want to print the length of the 'first' value in a dictionary. In Python this would be done with the command len(list(my_dict.values())[0]).

When I try this in Jinja2 I get the error jinja2.exceptions.UndefinedError: 'list' is undefined.

Minimum working example:

from jinja2 import Template, DebugUndefined
from shutil import copyfile

def main(file_name_template, file_name_log):

    # Copy template file 'file_name_template' to 'file_name_log' so that logging can start.
    copyfile(file_name_template, file_name_log)
    template = Template(open(file_name_log).read(), undefined=DebugUndefined)

    # Define test variable 'my_dict'.
    my_dict = {'key_0': 4641896,
               'key_1': 189478415,
               'key_2': 841653}

    # Start logging.
    template_render_dict = {'my_dict': my_dict}

    # Save log to external file and possibly open upon completion of the 'main' program.
    template_rendered = template.render(template_render_dict)  # Render the template to the filled in log report.

if __name__ == "__main__":
    main("template.html", "template_rendered.html")

with in template.html the code

<!DOCTYPE html>

        {{my_dict}}

        {{my_dict.keys()}}

        {{my_dict.values()}}

        {{len(list(my_dict.values())[0])}}

How do I solve this?

Body:
You cannot use Python list in jinja2 template because it's not Python, it is a mark language. However, it provides a length method. Instead of:

{% if len(dict.values()[0]) > 1 %}

You should write:

{% if dict.values()[0] | length > 1 %}

# or
{% if dict.values() | first | length > 1 %}

Please see doc for more examples.


问:
C# Environment variables in integration test
I have built a custom web application Factory to run a in memory test server for integration tests. Instead of using in memory database, we are trying to use a sql database.

My problem is that the connection string is changing for each environment. We have several appsettings{envName}.json files with the connection string. So, I need to find a solution for getting the env variable. These are my tries:

```<code>public class CustomWebApplicationSQLServerFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            var env = serviceProvider.GetService<IHostingEnvironment>();

            Configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            var defaultConnection = Configuration.GetConnectionString("DefaultConnection");
            var connectionString = string.Format(defaultConnection, "TestSampleOrder_" + Guid.NewGuid().ToString());

            services.AddDbContext<SampleOrderContext>(options =>
            {
                options.UseSqlServer(connectionString);
                options.UseInternalServiceProvider(serviceProvider);
            });

            var sp = services.BuildServiceProvider();

            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;

                var context = scopedServices.GetRequiredService<SampleOrderContext>();

                DbInitializer.InitializeDbForTests(context);
            }
        });
    }
</code>```

Also I have added in my test Project a launchSettings.json file. In that file, under my test Project name, I have added "ASPNETCORE_ENVIRONMENT": "AnyValue". So, I can't understand why <s>env = null</s>. After doing more tests, env.EnvironmentName = "Development", and application name and path are the main Project. Why? "Development" Word is NOT set in the hole solution.

I tried also replace the env line for this one:

```<code>var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
</code>```

If I set a Windows variable, I can get the value using that, but I need to understand how can I set the value of the variable in my launchSettings file.

Another thing I have tried is this:

```<code>var serviceProvider = services.BuildServiceProvider();
</code>```

But I really don't understand the difference.

Can anyone please help me to understand how this is working, what is the best way to get the env variable and what is the difference between using services.BuildServiceProvider() and new ServiceCollection()?

Thanks a lot.

答:
Perhaps this question could provide some insight.

That being said, the "simplest" way to go about testing with configuration is to abstract what you need.  Maybe you could build an adapter that gives you the environment name, e.g.:

```<code>public interface IApplicationConfiguration
{
    string GetEnvironmentName();
}

public class ApplicationConfiguration
{
    private IHostingEnvironment _hostingConfiguration;

    public ApplicationConfiguration(IHostingEnvironment hostingConfiguration)
    {
        _hostingConfiguration = hostingConfiguration;
    }

    public string GetEnvironmentName()
    {
        return _hostingConfiguration.EnvironmentName;
    }
}
</code>```

You could solve it using other options but mocking these type of settings can be quite useful.

Body:
I have built a custom web application Factory to run a in memory test server for integration tests. Instead of using in memory database, we are trying to use a sql database.

My problem is that the connection string is changing for each environment. We have several appsettings{envName}.json files with the connection string. So, I need to find a solution for getting the env variable. These are my tries:

public class CustomWebApplicationSQLServerFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            var env = serviceProvider.GetService<IHostingEnvironment>();

            Configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            var defaultConnection = Configuration.GetConnectionString("DefaultConnection");
            var connectionString = string.Format(defaultConnection, "TestSampleOrder_" + Guid.NewGuid().ToString());

            services.AddDbContext<SampleOrderContext>(options =>
            {
                options.UseSqlServer(connectionString);
                options.UseInternalServiceProvider(serviceProvider);
            });

            var sp = services.BuildServiceProvider();

            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;

                var context = scopedServices.GetRequiredService<SampleOrderContext>();

                DbInitializer.InitializeDbForTests(context);
            }
        });
    }

Also I have added in my test Project a launchSettings.json file. In that file, under my test Project name, I have added "ASPNETCORE_ENVIRONMENT": "AnyValue". So, I can't understand why <s>env = null</s>. After doing more tests, env.EnvironmentName = "Development", and application name and path are the main Project. Why? "Development" Word is NOT set in the hole solution.

I tried also replace the env line for this one:

var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

If I set a Windows variable, I can get the value using that, but I need to understand how can I set the value of the variable in my launchSettings file.

Another thing I have tried is this:

var serviceProvider = services.BuildServiceProvider();

But I really don't understand the difference.

Can anyone please help me to understand how this is working, what is the best way to get the env variable and what is the difference between using services.BuildServiceProvider() and new ServiceCollection()?

Thanks a lot.

Body:
Perhaps this question could provide some insight.

That being said, the "simplest" way to go about testing with configuration is to abstract what you need.  Maybe you could build an adapter that gives you the environment name, e.g.:

public interface IApplicationConfiguration
{
    string GetEnvironmentName();
}

public class ApplicationConfiguration
{
    private IHostingEnvironment _hostingConfiguration;

    public ApplicationConfiguration(IHostingEnvironment hostingConfiguration)
    {
        _hostingConfiguration = hostingConfiguration;
    }

    public string GetEnvironmentName()
    {
        return _hostingConfiguration.EnvironmentName;
    }
}

You could solve it using other options but mocking these type of settings can be quite useful.


问:
How to insert variable results into calls in Django Template Language
In Django I'm trying to make a generic "confirm action" call which I can easily pass the final address to, but I'm having difficulty inserting a variable in the link:

```<code><a href="{% url 'view_do_confirm_action' 'url view_delete_object object.object_name' %}"> Delete this object </a><br>
</code>```

In case it's not clear, the argument to view_do_confirm_action is the url to be followed if the user confirms.  The final url I would like to be followed links to this pattern:

```<code>path('objects/object/<str:object_name>/delete', views.view_delete_object, name='view_delete_object'),
</code>```

"url view_delete_object object.object_name" is not being resolved at the right time here - any advice?

Thank you

scan

答:
urls.py

```<code>path('<str:object_name>/delete', ViewBarDrinkDetail, name='view_delete_object'),
path('confirm/<str:url_text>', ViewBarDrinkUpdate, name='view_do_confirm_action'),
</code>```

Your top url view_do_confirm_action is taking a url_text, this url_text will obviously contain /, with these dynamic slashes Django won't be able to resolve your view_do_confirm_action.

Solutions

Try changing your pattern:

```<code>path('/confirm/<str:object_name>/delete', ViewBarDrinkDetail, name='view_do_confirm_action'),
</code>```

Use Custom Template Tag

```<code>@register.simple_tag
def pass_url_to_reverse_name(name, arg_url_name, arg_url_args):

    arg_resolved_url = reverse(arg_url_name, args=[arg_url_args])
    resolved_url = reverse(name, args=[arg_resolved_url])

    return resolved_ur
</code>```

In template Use it like this:

```<code><a href="{% pass_url_to_reverse_name 'view_do_confirm_action' 'view_delete_object' request.user.id %}"> Delete this object </a>
</code>```

Body:
In Django I'm trying to make a generic "confirm action" call which I can easily pass the final address to, but I'm having difficulty inserting a variable in the link:

 Delete this object

In case it's not clear, the argument to view_do_confirm_action is the url to be followed if the user confirms.  The final url I would like to be followed links to this pattern:

path('objects/object/<str:object_name>/delete', views.view_delete_object, name='view_delete_object'),

"url view_delete_object object.object_name" is not being resolved at the right time here - any advice?

Thank you

scan

Body:
urls.py

path('<str:object_name>/delete', ViewBarDrinkDetail, name='view_delete_object'),
path('confirm/<str:url_text>', ViewBarDrinkUpdate, name='view_do_confirm_action'),

Your top url view_do_confirm_action is taking a url_text, this url_text will obviously contain /, with these dynamic slashes Django won't be able to resolve your view_do_confirm_action.

Solutions

Try changing your pattern:

path('/confirm/<str:object_name>/delete', ViewBarDrinkDetail, name='view_do_confirm_action'),

Use Custom Template Tag

@register.simple_tag
def pass_url_to_reverse_name(name, arg_url_name, arg_url_args):

    arg_resolved_url = reverse(arg_url_name, args=[arg_url_args])
    resolved_url = reverse(name, args=[arg_resolved_url])

    return resolved_ur

In template Use it like this:

<a href="{% pass_url_to_reverse_name 'view_do_confirm_action' 'view_delete_object' request.user.id %}"> Delete this object </a>


问:
Change doesn't trigger when selection all checkboxes and records not getting added to the array
I have checkbox in each row of the table if I check any checkbox in the table individually then checkedForDeletion() methond runs and it adds the added record in the array and removes it if unchecked however if i select the checkbox at the top in the table th heading then (change) doesn't get triggerd and records are not added and removed from the array based on checked status.
I want that if user clicks on checkbox in the heading then all records should be push to the array and removed if used unchecks anyone row and so on.

              <input type="checkbox" (change)="selectAll();" [checked]="selectedAll">
              IP
              Domain
              Status
              Sender Email
              Action

              <input type="checkbox" [(ngModel)]="record.selected" (change)="checkedForDeletion(record,$event);">
              {{record.ip}}
              {{record.forDomain}}
              {{record.status}}
              {{record.senderEmail}}

```

<p>ts file</p>

<pre class="lang-js prettyprint-override"><code>    ipRecords: any;
    deletionList: any;
   selectedAll: any;

    checkedForDeletion(record: any, event: any) {
        const checked = event.target.checked;
        if (checked) {
          this.deletionList.push(record);
          console.log(this.deletionList);
        } else {
          const index = this.deletionList.findIndex(list => list.id === record.id );
          this.deletionList.splice(index, 1);
          console.log(this.deletionList);
        }

        selectAll() {
        this.selectedAll = !this.selectedAll;
        for (var i = 0; i < this.ipRecords.length; i++) {
          this.ipRecords[i].selected = this.selectedAll;
      }

      }
</code>```

答:
Make following minor changes:

Add an id to your checkboxes

```<code><tr *ngFor="let record of ipRecords; let i = index;>
      <td><input type="checkbox" id="checkboxId{{ i }}" [(ngModel)]="record.selected" (change)="checkIfAllSelected(record); checkedForDeletion(record,$event);"></td>
      <td>{{record.ip}}</td>
      <td>{{record.forDomain}}</td>
      <td>{{record.status}}</td>
      <td>{{record.senderEmail}}</td>
</tr>
</code>```

Update your ts component, to tick or untick your checkbox as appropriate

```<code>selectAll() {
    this.selectedAll = !this.selectedAll;
    for (var i = 0; i < this.ipRecords.length; i++) {
      let box = document.getElementById('checkboxId' + i) as HTMLInputElement;
      box.checked = this.selectedAll; // toggle checked state here
      this.ipRecords[i].selected = this.selectedAll;

      let check = this.deletionList.findIndex(list => list.id === this.ipRecords[i].id );
      if (check == -1) {
         (this.selectedAll) ?  this.deletionList.push(this.ipRecords[i]) : ''; // only add if true
      } else {
         (!this.selectedAll) ? this.deletionList.splice(check, 1) : ''; // only remove if false
      }

    }
}
</code>```

Body:
I have checkbox in each row of the table if I check any checkbox in the table individually then checkedForDeletion() methond runs and it adds the added record in the array and removes it if unchecked however if i select the checkbox at the top in the table th heading then (change) doesn't get triggerd and records are not added and removed from the array based on checked status.
I want that if user clicks on checkbox in the heading then all records should be push to the array and removed if used unchecks anyone row and so on.

              <input type="checkbox" (change)="selectAll();" [checked]="selectedAll">
              IP
              Domain
              Status
              Sender Email
              Action

              <input type="checkbox" [(ngModel)]="record.selected" (change)="checkedForDeletion(record,$event);">
              {{record.ip}}
              {{record.forDomain}}
              {{record.status}}
              {{record.senderEmail}}

ts file

    ipRecords: any;
    deletionList: any;
   selectedAll: any;

    checkedForDeletion(record: any, event: any) {
        const checked = event.target.checked;
        if (checked) {
          this.deletionList.push(record);
          console.log(this.deletionList);
        } else {
          const index = this.deletionList.findIndex(list => list.id === record.id );
          this.deletionList.splice(index, 1);
          console.log(this.deletionList);
        }

        selectAll() {
        this.selectedAll = !this.selectedAll;
        for (var i = 0; i < this.ipRecords.length; i++) {
          this.ipRecords[i].selected = this.selectedAll;
      }

      }

Body:
Make following minor changes:

Add an id to your checkboxes

<tr *ngFor="let record of ipRecords; let i = index;>
      <td><input type="checkbox" id="checkboxId{{ i }}" [(ngModel)]="record.selected" (change)="checkIfAllSelected(record); checkedForDeletion(record,$event);"></td>
      <td>{{record.ip}}</td>
      <td>{{record.forDomain}}</td>
      <td>{{record.status}}</td>
      <td>{{record.senderEmail}}</td>
</tr>

Update your ts component, to tick or untick your checkbox as appropriate

selectAll() {
    this.selectedAll = !this.selectedAll;
    for (var i = 0; i < this.ipRecords.length; i++) {
      let box = document.getElementById('checkboxId' + i) as HTMLInputElement;
      box.checked = this.selectedAll; // toggle checked state here
      this.ipRecords[i].selected = this.selectedAll;

      let check = this.deletionList.findIndex(list => list.id === this.ipRecords[i].id );
      if (check == -1) {
         (this.selectedAll) ?  this.deletionList.push(this.ipRecords[i]) : ''; // only add if true
      } else {
         (!this.selectedAll) ? this.deletionList.splice(check, 1) : ''; // only remove if false
      }

    }
}


问:
I'm confused with this database, should I create more Foreign Keys or more columns?
I'm creating this database about Movies, Series and Actors. The Movies part is done, but I'm confused with the Series+Actors part. My goal is to have 4 tables, 1 of series in general, 1 with the number of seasons and episodes, 1 with the actors info (already connected by foreign key with the movies table).

I've created this tables:

```<code>SeriesData (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4),
  ActorID int FK);

ActorsData (
  ActorID int PK,
  ActorName varchar(50),
  ActorAge varchar(3),
  MoviesParticipated varchar(50))
</code>```

For now its OK, but now comes my confusion.
I need to create 2 more tables right? A seasons and episodes table, since we can't put that type of data in the first table and I need a MoviesParticipated table. How do I do it so that I can get the data of 'How many episodes does every season have?'

This is my current SeasonsEpisodes table, but this will only tell me how many seasons and how many episodes the series has right?

```<code>SeasonsEpisodes (
  SerieID int PK,
  SerieSeasons int,
  SerieEpisodes int
</code>```

For the MoviesParticipated table would be something like this (My goal is to output each movie/series he participated)?

```<code>MoviesParticipated (
ActorID int PK
MovieID varchar(50) FK,
SerieID varchar(50) FK)
</code>```

Which Foreign Keys should I create? Should I add more columns?

答:
1) Since, Actors to Movies/Series participated is [many to many] combination, its efficient to have a seperate table for the mapping.

2) You donot need a reference of Participation on the Actors Table, since ActorsID is referred in the Participation table

you can refer the below table structures:

```<code>--Series Table
SeriesData (
SeriesID int PK,
SeriesName varchar(50),
SeriesDescription text,
SeriesCategory varchar(50),
SeriesYear varchar(4));

--Actors Table
ActorsData (
ActorID int PK,
ActorName varchar(50),
ActorAge varchar(3))

--SeasonsnEpisodes
SeasonsEpisodes (
SeasonsEpisodesId in PK,
SeriesID int FK,
SerieSeasons int,
SerieEpisodes int)
</code>```

EDITED AS PER @ADyson's Comment

```<code>--MoviesParticipated
MoviesParticipated (
MoviesParticipationId int PK
ActorID int FK
MovieID varchar(50) FK)

--SeriesParticipated
SeriesParticipated (
SeriesParticipationId int PK
ActorID int FK
SeriesID varchar(50) FK)
</code>```

Body:
I'm creating this database about Movies, Series and Actors. The Movies part is done, but I'm confused with the Series+Actors part. My goal is to have 4 tables, 1 of series in general, 1 with the number of seasons and episodes, 1 with the actors info (already connected by foreign key with the movies table).

I've created this tables:

SeriesData (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4),
  ActorID int FK);

ActorsData (
  ActorID int PK,
  ActorName varchar(50),
  ActorAge varchar(3),
  MoviesParticipated varchar(50))

For now its OK, but now comes my confusion.
I need to create 2 more tables right? A seasons and episodes table, since we can't put that type of data in the first table and I need a MoviesParticipated table. How do I do it so that I can get the data of 'How many episodes does every season have?'

This is my current SeasonsEpisodes table, but this will only tell me how many seasons and how many episodes the series has right?

SeasonsEpisodes (
  SerieID int PK,
  SerieSeasons int,
  SerieEpisodes int

For the MoviesParticipated table would be something like this (My goal is to output each movie/series he participated)?

MoviesParticipated (
ActorID int PK
MovieID varchar(50) FK,
SerieID varchar(50) FK)

Which Foreign Keys should I create? Should I add more columns?

Body:
1) Since, Actors to Movies/Series participated is [many to many] combination, its efficient to have a seperate table for the mapping.

2) You donot need a reference of Participation on the Actors Table, since ActorsID is referred in the Participation table

you can refer the below table structures:

--Series Table
SeriesData (
SeriesID int PK,
SeriesName varchar(50),
SeriesDescription text,
SeriesCategory varchar(50),
SeriesYear varchar(4));

--Actors Table
ActorsData (
ActorID int PK,
ActorName varchar(50),
ActorAge varchar(3))

--SeasonsnEpisodes
SeasonsEpisodes (
SeasonsEpisodesId in PK,
SeriesID int FK,
SerieSeasons int,
SerieEpisodes int)

EDITED AS PER @ADyson's Comment

--MoviesParticipated
MoviesParticipated (
MoviesParticipationId int PK
ActorID int FK
MovieID varchar(50) FK)

--SeriesParticipated
SeriesParticipated (
SeriesParticipationId int PK
ActorID int FK
SeriesID varchar(50) FK)


问:
Is there any better way to Launch UWP apps from Console application
I tried to launch the UWP application from c# console application. It tried with below code which uses APPID

Process.Start(@"C:\Program Files (x86)\Windows Kits\10\App Certification Kit\microsoft.windows.softwarelogo.appxlauncher.exe", "1a75- 6f75 - 5ed3 - 8944 - 6b7df2bee095");

Is there any better way to launch UWP application programatically.

答:
I tried to launch the UWP app through Protocol. The below link will help how to create a protocol

Automate launching Windows 10 UWP apps

Now you can launch your application by using

Process.Start("URL:myapplication://");

The process class is available in System.Diagnostics. And also need to add the following method in App.xaml.cs file

```<code> protected override void OnActivated(IActivatedEventArgs args)
    {
        Initialize(args);
        if (args.Kind == ActivationKind.Protocol)
        {
            ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            // Always navigate for a protocol launch
            rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.AbsoluteUri);

            // Ensure the current window is active
            Window.Current.Activate();
        }

    }
</code>```

Body:
I tried to launch the UWP app through Protocol. The below link will help how to create a protocol

Automate launching Windows 10 UWP apps

Now you can launch your application by using

Process.Start("URL:myapplication://");

The process class is available in System.Diagnostics. And also need to add the following method in App.xaml.cs file

 protected override void OnActivated(IActivatedEventArgs args)
    {
        Initialize(args);
        if (args.Kind == ActivationKind.Protocol)
        {
            ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            // Always navigate for a protocol launch
            rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.AbsoluteUri);

            // Ensure the current window is active
            Window.Current.Activate();
        }

    }


问:
How to sort map without using comparable and Comparator Interface? How to write Custom Sorting?
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

```<code>public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}
</code>```

Main class

```<code>public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}
</code>```

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

答:
In the interests of Keeping it simple (i.e. the KISS principle) and explaining my "hint" relating to a compound key, following  is the worked example.

The "key" to the solution is to let the tree sort the data naturally (not, IMHO, to add to the code making it more complex by providing a manual sort). Thus the student class needs to return a key that the tree can naturally sort.

To produce the desired sort result, the key for the Tree is (total Marks, student name).

Here is the revised Student class (minus getters and setters, but I did add a new constructor to make life easy for me):

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter

    public Student() {

    }

    public Student(String name, Integer rollNumber, int m1, int m2, int m3) {
        this.name = name;
        this.rollNumber = rollNumber;
        this.m1 = m1;
        this.m2 = m2;
        this.m3 = m3;
        this.totMarks = m1 + m2 + m3;
    }

    public String getKey() {
//      return String.format("%d-%s", totMarks, name);          // WRONG!
        return String.format("%04d-%s", totMarks, name);        // Right
    }

    public String toString() {
        return String.format("%06d: %s - %d", rollNumber, name, totMarks);
    }

}
```

<p><strong>Note</strong> there is a commented out line of code in the <code>getKey</code> method with the comment <em>WRONG</em>. This relates to my hint of testing with single digit scores. Try swapping out the two lines of code to see the correct and incorrect result.</p>

<p>Here is the main, I removed all of the Scanner stuff - again to make life easy for me. Hopefully you can follow it and add back in your scanner loop.</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class StudentData {
    public static void main(String[] args) {
        // Initialise a list of students (as I don't want to rekey all the details each
        // time I run the program).
        List<Student> studentList = Arrays.asList(
                    new Student("Fred", 1, 2, 2, 2),      /* Score of 6 */
                    new Student("John", 2, 2, 3, 3),      /* Score of 8 */
                    new Student("Jane", 3, 20, 25, 30),      /* Score of 75 */
                    new Student("Julie", 4, 20, 15, 10)      /* Score of 45 */
                    // add as many new students as you like, and reorder them
                    // as much as you like to see if there is any difference in the
                    // result (there shouldn't be).
        );

            // Note the key of the tree is of type String - not Integer.
            // This is the heart of the algorithm, the tree will be "sorted"
            // on the natural key provided. This "natural key" is in fact
            // a compound key that is generated by combining the total score
            // and the student name.
        Map<String,Student> map = new TreeMap<String,Student>();
        for (Student ss : studentList) {
            map.put(ss.getKey(),ss);
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<String,Student> m :map.entrySet()) {
            System.out.println(m);
        }
    }
}
</code>```

I hope you agree that this is a simpler solution. There is also a potential performance benefit as the students are sorted as they are being loaded into the tree (i.e. once). The performance of this sorting is, I think, log(n). Sort on retrieval will likely be n log(n) or worse.

Body:
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}

Main class

public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

Body:
In the interests of Keeping it simple (i.e. the KISS principle) and explaining my "hint" relating to a compound key, following  is the worked example.

The "key" to the solution is to let the tree sort the data naturally (not, IMHO, to add to the code making it more complex by providing a manual sort). Thus the student class needs to return a key that the tree can naturally sort.

To produce the desired sort result, the key for the Tree is (total Marks, student name).

Here is the revised Student class (minus getters and setters, but I did add a new constructor to make life easy for me):

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter

    public Student() {

    }

    public Student(String name, Integer rollNumber, int m1, int m2, int m3) {
        this.name = name;
        this.rollNumber = rollNumber;
        this.m1 = m1;
        this.m2 = m2;
        this.m3 = m3;
        this.totMarks = m1 + m2 + m3;
    }

    public String getKey() {
//      return String.format("%d-%s", totMarks, name);          // WRONG!
        return String.format("%04d-%s", totMarks, name);        // Right
    }

    public String toString() {
        return String.format("%06d: %s - %d", rollNumber, name, totMarks);
    }

}

Note there is a commented out line of code in the getKey method with the comment WRONG. This relates to my hint of testing with single digit scores. Try swapping out the two lines of code to see the correct and incorrect result.

Here is the main, I removed all of the Scanner stuff - again to make life easy for me. Hopefully you can follow it and add back in your scanner loop.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class StudentData {
    public static void main(String[] args) {
        // Initialise a list of students (as I don't want to rekey all the details each
        // time I run the program).
        List<Student> studentList = Arrays.asList(
                    new Student("Fred", 1, 2, 2, 2),      /* Score of 6 */
                    new Student("John", 2, 2, 3, 3),      /* Score of 8 */
                    new Student("Jane", 3, 20, 25, 30),      /* Score of 75 */
                    new Student("Julie", 4, 20, 15, 10)      /* Score of 45 */
                    // add as many new students as you like, and reorder them
                    // as much as you like to see if there is any difference in the
                    // result (there shouldn't be).
        );

            // Note the key of the tree is of type String - not Integer.
            // This is the heart of the algorithm, the tree will be "sorted"
            // on the natural key provided. This "natural key" is in fact
            // a compound key that is generated by combining the total score
            // and the student name.
        Map<String,Student> map = new TreeMap<String,Student>();
        for (Student ss : studentList) {
            map.put(ss.getKey(),ss);
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<String,Student> m :map.entrySet()) {
            System.out.println(m);
        }
    }
}

I hope you agree that this is a simpler solution. There is also a potential performance benefit as the students are sorted as they are being loaded into the tree (i.e. once). The performance of this sorting is, I think, log(n). Sort on retrieval will likely be n log(n) or worse.


问:
Drop triggers for all tables
I have multiple triggers, all being the same trigger, but on different tables e.g.

```<code>  tgname         |          trigger_table
------------------------+----------------------------------
 updated_agg_trigger    | forecasts.forecast_1548180000
 updated_agg_trigger    | forecasts.forecast_1548187200
 updated_agg_trigger    | forecasts.forecast_1548162000
 updated_agg_trigger    | forecasts.forecast_1548190800
 updated_agg_trigger    | forecasts.forecast_1548183600
 updated_agg_trigger    | forecasts.forecast_1548172800
 updated_agg_trigger    | forecasts.forecast_1548111600
 updated_agg_trigger    | forecasts.forecast_1548136800
 updated_agg_trigger    | forecasts.forecast_1548129600
</code>```

How can I delete all updated_agg_trigger-triggers on all tables with a single command?

P.S. I don't want to delete ALL triggers, just the updated_agg_trigger-triggers.

答:
Run  dynamic statement looping through information_schema.triggers.

```<code>DO $$
DECLARE
l_trig_name TEXT := 'updated_agg_trigger';
l_schema    TEXT := 'forecasts';
rec record;
BEGIN

for rec IN
(
  SELECT event_object_table as table_name
      ,trigger_schema as schema_name
      ,trigger_name
   FROM  information_schema.triggers
      WHERE  trigger_name   = l_trig_name
       AND trigger_schema   = l_schema
 )
   LOOP
        EXECUTE format ('DROP TRIGGER %I
                ON %I.%I', rec.trigger_name,rec.schema_name,rec.table_name);
   END LOOP;

END $$;
</code>```

Title: Drop triggers for all tables

Body:
I have multiple triggers, all being the same trigger, but on different tables e.g.

  tgname         |          trigger_table
------------------------+----------------------------------
 updated_agg_trigger    | forecasts.forecast_1548180000
 updated_agg_trigger    | forecasts.forecast_1548187200
 updated_agg_trigger    | forecasts.forecast_1548162000
 updated_agg_trigger    | forecasts.forecast_1548190800
 updated_agg_trigger    | forecasts.forecast_1548183600
 updated_agg_trigger    | forecasts.forecast_1548172800
 updated_agg_trigger    | forecasts.forecast_1548111600
 updated_agg_trigger    | forecasts.forecast_1548136800
 updated_agg_trigger    | forecasts.forecast_1548129600

How can I delete all updated_agg_trigger-triggers on all tables with a single command?

P.S. I don't want to delete ALL triggers, just the updated_agg_trigger-triggers.

Body:
Run  dynamic statement looping through information_schema.triggers.

DO $$
DECLARE
l_trig_name TEXT := 'updated_agg_trigger';
l_schema    TEXT := 'forecasts';
rec record;
BEGIN

for rec IN
(
  SELECT event_object_table as table_name
      ,trigger_schema as schema_name
      ,trigger_name
   FROM  information_schema.triggers
      WHERE  trigger_name   = l_trig_name
       AND trigger_schema   = l_schema
 )
   LOOP
        EXECUTE format ('DROP TRIGGER %I
                ON %I.%I', rec.trigger_name,rec.schema_name,rec.table_name);
   END LOOP;

END $$;


问:
How can I fix FindElement by xpath in chrome driver misbehavior?
FindElement by XPath function is misbehaving. It gives error for some code and works for other code.

When I give object path directly it works. But when I give it through some variable, it throws error.

It works for this

```<code>var usermenu = _chromeDriver.FindElement(By.XPath("/html/body/div/header/nav/div/div[3]/ul/li[4]/a/span"));

usermenu.Click();
</code>```

But doesn't work for this

```<code>String object_id = "/html/body/div/header/nav/div/div[3]/ul/li[4]/a/span";

IWebElement btnsubmit = driver.FindElement(By.XPath(object_id));

btnsubmit.Click();
</code>```

答:
I found the issue. The object was being obstructed by another modal object since my function was being called before the modal gets faded.

So I added a 2 second wait and it started working normally.

Thanks all.

Body:
FindElement by XPath function is misbehaving. It gives error for some code and works for other code.

When I give object path directly it works. But when I give it through some variable, it throws error.

It works for this

var usermenu = _chromeDriver.FindElement(By.XPath("/html/body/div/header/nav/div/div[3]/ul/li[4]/a/span"));

usermenu.Click();

But doesn't work for this

String object_id = "/html/body/div/header/nav/div/div[3]/ul/li[4]/a/span";

IWebElement btnsubmit = driver.FindElement(By.XPath(object_id));

btnsubmit.Click();


问:
Undefined variable: data in laravel
Undefined variable: data error occure when i want to display data from database.

Here is my code

Controller

```<code>public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->where('zipcode');
    }

    return view('search.searchhome',compact('data',$data));
    dd($data);

}
</code>```

Blade

```<code><p>
@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach
</p>
</code>```

答:
You have a few errors in your code.

```<code>if(!empty($ids)){
    $results = DB::table('trial')->whereIn( 'id', $ids)->get();
 }
</code>```

Removed the ->where(), the where clause had no condition.
Added the get(), otherwise the query wont return any results.

```<code>return view('search.searchhome',compact('results'));
</code>```

changed data to results as that contains your data.

```<code>dd($data);
</code>```

remove the dd(), this does nothing as the function returns before it.

(I would also suggest to look into collections, instead of looping over the first result set)

Title: Undefined variable: data in laravel

Body:
Undefined variable: data error occure when i want to display data from database.

Here is my code

Controller

public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->where('zipcode');
    }

    return view('search.searchhome',compact('data',$data));
    dd($data);

}

Blade

@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach

Body:
You have a few errors in your code.

if(!empty($ids)){
    $results = DB::table('trial')->whereIn( 'id', $ids)->get();
 }

Removed the ->where(), the where clause had no condition.
Added the get(), otherwise the query wont return any results.

return view('search.searchhome',compact('results'));

changed data to results as that contains your data.

dd($data);

remove the dd(), this does nothing as the function returns before it.

(I would also suggest to look into collections, instead of looping over the first result set)


问:
How do i resolve this JSONObject issue
I am following an article to use web services in unity3d. I am complete beginner and unfamiliar with webservices and I have basic understanding of how it works.

I have tried using JsonUtiltiy lib but there is no function for JSONObject in it too.

here is the article i am following

list of errors i am getting

答:
JSONObject is not a class implemented in the unity editor.

To use it, you require to download its implementation in your project (Assets Folder).

As stated in the article you reported the JSONObject can be found in Unity Wiki.

I started off bringing down a JSON-reading implementation for their
  Wiki (be sure to add the Nullable class definition, listed further
  down the page)

I see that the link on the article is dead, but you can find the asset he mentioned at the following links.

Download and import it from the Asset Store

Download and import from github repository

You need to import them and use in your project.

Title: How do i resolve this JSONObject issue


问:
Hide filenames for product images
Is there any way that I can hide the image filenames for all products on a website so that, even if someone chooses to view the page source or image properties, they can't?
I need a way to hide the filenames because in some cases they contain information that i dont want to display to the public.</p>

答: You can use different techniques, e.g. use md5 function to generate a hash for image file name and store the images in any directory, push their path info in database and then get from database..</p>

Title: Hide filenames for product images


问:
Errors within standard header files
I'm currently getting the following errors:

c:\program files\microsoft visual studio\vc98\include\iomanip(15) : error C2059: >syntax error : 'namespace'

c:\program files\microsoft visual studio\vc98\include\iomanip(15) : error C2334: >unexpected token(s) preceding '{'; skipping apparent function body

c:\program files\microsoft visual studio\vc98\include\math.h(36) : error C2059: syntax >error : 'string'

c:\program files\microsoft visual studio\vc98\include\math.h(36) : error C2334: unexpected >token(s) preceding '{'; skipping apparent function body

As they are all in the standard library header files, and therefore read only, I don't know how to fix it!

Any help would be great.

答:
Visual Studio:

Open the project's Property Pages dialog box.

Click the C/C++ folder.

Click the Advanced property page.

Show Includes (Yes)

Build the project, in the build output you should see the include tree.
Find the first occurrence of the error, and scan upwards opening each include file (that you wrote) to find which one has the missing curly bracket "}"

Title: Errors within standard header files


问:
Syntax error "Missing keyword" in case statement in WHERE clause
I am having some syntax error in my case statement where I am checking below condition:

```<code>((RAP10B.CLMSRC = '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT)
       OR
(RAP10B.CLMSRC <> '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT - 60 days)
</code>```

Below is the code what I am using.

```<code>CASE
  WHEN RAP10B.CLMSRC = '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t
  WHEN RAP10B.CLMSRC <> '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60)
END
</code>```

The error message is  "ORA-00905: missing keyword". But I am not able to find the missing thing.

答:
Are you looking for something like this?</p>

```<code>CASE
   WHEN RAP10B.CLMSRC = '2'
      AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36)
      AND rap01.teffdt_t THEN <your_column>
   WHEN RAP10B.CLMSRC <> '2'
      AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36)
      AND (rap01.teffdt_t - 60) THEN <your_column>
END
</code>```

Body:
I am having some syntax error in my case statement where I am checking below condition:

((RAP10B.CLMSRC = '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT)
       OR
(RAP10B.CLMSRC <> '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT - 60 days)

Below is the code what I am using.

CASE
  WHEN RAP10B.CLMSRC = '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t
  WHEN RAP10B.CLMSRC <> '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60)
END

The error message is  "ORA-00905: missing keyword". But I am not able to find the missing thing.

Body:
Are you looking for something like this?

CASE
   WHEN RAP10B.CLMSRC = '2'
      AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36)
      AND rap01.teffdt_t THEN <your_column>
   WHEN RAP10B.CLMSRC <> '2'
      AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36)
      AND (rap01.teffdt_t - 60) THEN <your_column>
END


问:
Javascript Stuck in Cache
I have a HTML document which I am developing a .js file for. My problem is, my browser is still using an outdated version of the .js script, which it stored in the cache when it was used. Any modifications to the actual .js script make no difference. Clearing the cache didn't help... How can I fix this?

答:
Did you try with filename.js?v=2, and after another changes filename.js?v=3?

Another possibillity is, that you attached wrong file, not this what you're editing.

Restart the browser? But I dont suspect, its this issue.

If the file is on remote server, try uploading again, and then download the file and check for the changes. It may be caching mechanism on the server too, so try to restart apache if you've got permissions.

Can you add more code?

Title: Javascript Stuck in Cache


问:
How to Deploy a unity working app to the HoloLens 1?
I have followed some guidelines found online on how to build a unity application using MRTk2 and saw which bugs to ignore, nevertheless, after building my solution I am unable to deploy it to the HoloLens 1.

I built the solution using:

II2Cpp backend & have

installed SDK 10.0.18632.30

Set minimum SDK to 10.0.10240.0

Target SDK to Latest Installed

And The build succeeded!

When I open the solution on Visual Studio 2017, and try to deploy(release, x86) I get the errors bellow:

Error   MSB3073 The command ""D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\Il2CppOutputProject\IL2CPP\build\il2cpp.exe" --libil2cpp-static --compile-cpp -architecture=x86 -configuration=Release -platform=winrt -outputpath="D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\build\bin\Win32\Release\GameAssembly.dll" --data-folder="D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\build\bin\Win32\Release\" -cachedirectory="D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\build\obj\il2cppOutputProject\Win32\Release\" -generatedcppdir="D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\Il2CppOutputProject\Source" --additional-defines=WINDOWS_UWP --additional-defines=UNITY_UWP --additional-defines=UNITY_WSA_10_0 --additional-defines=UNITY_WSA --additional-defines=UNITY_WINRT --additional-defines=PLATFORM_WINRT -dotnetprofile=unityaot -verbose --map-file-parser="D:\Project\Virtual%20Guided%20Assembly%20V3\Code_VGA.v3b\Builds\WSAPlayer\Il2CppOutputProject\IL2CPP\MapFileParser\MapFileParser.exe"" exited with code 3.

Error   MSB4018 The "GetOutOfDateItems" task failed unexpectedly.

答:
After many trials, I have decided to move the project to a new location and I was able to build it and deploy to the HoloLens.
Apparently the problem was being caused by the encoded space "%" on the project path, removing that allowed me to build and deploy the application successfully!

You can see the difference on how the solution were being loaded into VS17 in the picture below:


答:
Try below -</p>

```<code>CASE
  WHEN RAP10B.CLMSRC = '2'
  and rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t then yourval
  WHEN RAP10B.CLMSRC <> '2'
  and rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60) yourval1
END
</code>```

Title: Syntax error "Missing keyword" in case statement in WHERE clause

Body:
Try below -

CASE
  WHEN RAP10B.CLMSRC = '2'
  and rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t then yourval
  WHEN RAP10B.CLMSRC <> '2'
  and rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60) yourval1
END


问:
Can somebody explain me how to make my JSON inside of : let parameters: [String: AnyObject]?
I need to send this JSON with HTTP post request, but I Want to convert him to a String, I have problem with the " "
if somebody can do it for me or explain it for me it will help me,
thank you!</p>

```<code>{
  "inputs": [
    {
      "data": {
        "image": {
          "url": "https://someImage.jpg"
        }
      }
    }
  ]
}
</code>```

答:
You can try</p>

```<code>let str :[String:Any] =  [
    "inputs": [
    [
    "data": [
    "image": [
    "url": "https://someImage.jpg"
    ]
    ]
    ]
]]
</code>```

Body:
I need to send this JSON with HTTP post request, but I Want to convert him to a String, I have problem with the " "
if somebody can do it for me or explain it for me it will help me,
thank you!

{
  "inputs": [
    {
      "data": {
        "image": {
          "url": "https://someImage.jpg"
        }
      }
    }
  ]
}

Body:
You can try

let str :[String:Any] =  [
    "inputs": [
    [
    "data": [
    "image": [
    "url": "https://someImage.jpg"
    ]
    ]
    ]
]]