问:
Partition data around a match query during aggregation
What I have been trying to get my head around is to perform some kind of partitioning(split by predicate) in a mongo query. My current query looks like:

```<code>db.posts.aggregate([
 {"$match": { $and:[ {$or:[{"toggled":false},{"toggled":true, "status":"INACTIVE"}]}  ,  {"updatedAt":{$gte:1549786260000}} ] }},
 {"$unwind" :"$interests"},
 {"$group" : {"_id": {"iid": "$interests", "pid":"$publisher"}, "count": {"$sum" : 1}}},
 {"$project":{ _id: 0, "iid": "$_id.iid", "pid": "$_id.pid", "count": 1 }}
])
</code>```

This results in the following output:

```<code>{
    "count" : 3.0,
    "iid" : "INT456",
    "pid" : "P789"
}
{
    "count" : 2.0,
    "iid" : "INT789",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P123"
}
</code>```

All good so far, but then I had realized that for the documents that match the specific filter {"toggled":true, "status":"INACTIVE"}, I would rather decrement the count (-1). (considering the eventual value can be negative as well.)

Is there a way to somehow partition the data after match to make sure different grouping operations are performed for both the collection of documents?

Something that sounds similar to what I am looking for is
$mergeObjects, or maybe $reduce, but not much that I can relate from the documentation examples.

Note: I can sense, one straightforward way to deal with this would be to perform two queries, but I am looking for a single query to perform the operation.

Sample documents for the above output would be:

```<code>/* 1 */
{
    "_id" : ObjectId("5d1f7******"),
    "id" : "CON123",
    "title" : "Game",
    "content" : {},
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P789",
    "interests" : [
        "INT456"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 2 */
{
    "_id" : ObjectId("5d1f8******"),
    "id" : "CON456",
    "title" : "Home",
    "content" : {},
    "status" : "INACTIVE",
    "toggle":true,
    "publisher" : "P789",
    "interests" : [
        "INT456",
        "INT789"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 3 */
{
    "_id" : ObjectId("5d0e9******"),
    "id" : "CON654",
    "title" : "School",
    "content" : {},
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P789",
    "interests" : [
        "INT123",
        "INT456",
        "INT789"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 4 */
{
    "_id" : ObjectId("5d207*******"),
    "id" : "CON789",
    "title":"Stack",
    "content" : { },
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P123",
    "interests" : [
        "INT123"
    ],
    "updatedAt" : NumberLong(1582078628264)
}
</code>```

What I am looking forward to as a result though is

```<code>{
    "count" : 1.0, (2-1)
    "iid" : "INT456",
    "pid" : "P789"
}
{
    "count" : 0.0, (1-1)
    "iid" : "INT789",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P123"
}
</code>```

答:
This aggregation gives the desired result.

```<code>db.posts.aggregate( [
{ $match:  { updatedAt: { $gte: 1549786260000 } } },
{ $facet: {
        FALSE: [
            { $match: { toggle: false } },
            { $unwind : "$interests" },
            { $group : { _id : { iid: "$interests", pid: "$publisher" }, count: { $sum : 1 } } },
        ],
        TRUE: [
            { $match: { toggle: true, status: "INACTIVE" } },
            { $unwind : "$interests" },
            { $group : { _id : { iid: "$interests", pid: "$publisher" }, count: { $sum : -1 } } },
        ]
} },
{ $project: { result: { $concatArrays: [ "$FALSE", "$TRUE" ] } } },
{ $unwind: "$result" },
{ $replaceRoot: { newRoot: "$result" } },
{ $group : { _id : "$_id", count: { $sum : "$count" } } },
{ $project:{ _id: 0, iid: "$_id.iid", pid: "$_id.pid", count: 1 } }
] )
</code>```

[ EDIT ADD ]

The output from the query using the input data from the question post:

```<code>{ "count" : 1, "iid" : "INT123", "pid" : "P789" }
{ "count" : 1, "iid" : "INT123", "pid" : "P123" }
{ "count" : 0, "iid" : "INT789", "pid" : "P789" }
{ "count" : 1, "iid" : "INT456", "pid" : "P789" }
</code>```

[ EDIT ADD 2 ]

This query gets the same result with different approach (code):

```<code>db.posts.aggregate( [
  {
      $match:  { updatedAt: { $gte: 1549786260000 } }
  },
  {
      $unwind : "$interests"
  },
  {
      $group : {
          _id : {
              iid: "$interests",
              pid: "$publisher"
          },
          count: {
              $sum: {
                  $switch: {
                      branches: [
                        { case: { $eq: [ "$toggle", false ] },
                           then: 1 },
                        { case: { $and: [ { $eq: [ "$toggle", true] },  { $eq: [ "$status", "INACTIVE" ] } ] },
                           then: -1 }
                      ]
                  }
              }
          }
      }
  },
  {
      $project:{
           _id: 0,
           iid: "$_id.iid",
           pid: "$_id.pid",
           count: 1
      }
  }
] )
</code>```

[ EDIT ADD 3 ]

NOTE:

The facet query runs the two facets (TRUE and FALSE) on the same set of documents; it is like two queries running in parallel. But, there is some duplication of code as well as additional stages for shaping the documents down the pipeline to get the desired output.

The second query avoids the code duplication, and there are much lesser stages in the aggregation pipeline. This will make difference when the input dataset has a large number of documents to process - in terms of performance.  In general, lesser stages means lesser iterations of the documents (as a stage has to scan the documents which are output from the previous stage).

Body:
What I have been trying to get my head around is to perform some kind of partitioning(split by predicate) in a mongo query. My current query looks like:

db.posts.aggregate([
 {"$match": { $and:[ {$or:[{"toggled":false},{"toggled":true, "status":"INACTIVE"}]}  ,  {"updatedAt":{$gte:1549786260000}} ] }},
 {"$unwind" :"$interests"},
 {"$group" : {"_id": {"iid": "$interests", "pid":"$publisher"}, "count": {"$sum" : 1}}},
 {"$project":{ _id: 0, "iid": "$_id.iid", "pid": "$_id.pid", "count": 1 }}
])

This results in the following output:

{
    "count" : 3.0,
    "iid" : "INT456",
    "pid" : "P789"
}
{
    "count" : 2.0,
    "iid" : "INT789",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P123"
}

All good so far, but then I had realized that for the documents that match the specific filter {"toggled":true, "status":"INACTIVE"}, I would rather decrement the count (-1). (considering the eventual value can be negative as well.)

Is there a way to somehow partition the data after match to make sure different grouping operations are performed for both the collection of documents?

Something that sounds similar to what I am looking for is
$mergeObjects, or maybe $reduce, but not much that I can relate from the documentation examples.

Note: I can sense, one straightforward way to deal with this would be to perform two queries, but I am looking for a single query to perform the operation.

Sample documents for the above output would be:

/* 1 */
{
    "_id" : ObjectId("5d1f7******"),
    "id" : "CON123",
    "title" : "Game",
    "content" : {},
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P789",
    "interests" : [
        "INT456"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 2 */
{
    "_id" : ObjectId("5d1f8******"),
    "id" : "CON456",
    "title" : "Home",
    "content" : {},
    "status" : "INACTIVE",
    "toggle":true,
    "publisher" : "P789",
    "interests" : [
        "INT456",
        "INT789"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 3 */
{
    "_id" : ObjectId("5d0e9******"),
    "id" : "CON654",
    "title" : "School",
    "content" : {},
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P789",
    "interests" : [
        "INT123",
        "INT456",
        "INT789"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

/* 4 */
{
    "_id" : ObjectId("5d207*******"),
    "id" : "CON789",
    "title":"Stack",
    "content" : { },
    "status" : "ACTIVE",
    "toggle":false,
    "publisher" : "P123",
    "interests" : [
        "INT123"
    ],
    "updatedAt" : NumberLong(1582078628264)
}

What I am looking forward to as a result though is

{
    "count" : 1.0, (2-1)
    "iid" : "INT456",
    "pid" : "P789"
}
{
    "count" : 0.0, (1-1)
    "iid" : "INT789",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P789"
}
{
    "count" : 1.0,
    "iid" : "INT123",
    "pid" : "P123"
}

Body:
This aggregation gives the desired result.

db.posts.aggregate( [
{ $match:  { updatedAt: { $gte: 1549786260000 } } },
{ $facet: {
        FALSE: [
            { $match: { toggle: false } },
            { $unwind : "$interests" },
            { $group : { _id : { iid: "$interests", pid: "$publisher" }, count: { $sum : 1 } } },
        ],
        TRUE: [
            { $match: { toggle: true, status: "INACTIVE" } },
            { $unwind : "$interests" },
            { $group : { _id : { iid: "$interests", pid: "$publisher" }, count: { $sum : -1 } } },
        ]
} },
{ $project: { result: { $concatArrays: [ "$FALSE", "$TRUE" ] } } },
{ $unwind: "$result" },
{ $replaceRoot: { newRoot: "$result" } },
{ $group : { _id : "$_id", count: { $sum : "$count" } } },
{ $project:{ _id: 0, iid: "$_id.iid", pid: "$_id.pid", count: 1 } }
] )

[ EDIT ADD ]

The output from the query using the input data from the question post:

{ "count" : 1, "iid" : "INT123", "pid" : "P789" }
{ "count" : 1, "iid" : "INT123", "pid" : "P123" }
{ "count" : 0, "iid" : "INT789", "pid" : "P789" }
{ "count" : 1, "iid" : "INT456", "pid" : "P789" }

[ EDIT ADD 2 ]

This query gets the same result with different approach (code):

db.posts.aggregate( [
  {
      $match:  { updatedAt: { $gte: 1549786260000 } }
  },
  {
      $unwind : "$interests"
  },
  {
      $group : {
          _id : {
              iid: "$interests",
              pid: "$publisher"
          },
          count: {
              $sum: {
                  $switch: {
                      branches: [
                        { case: { $eq: [ "$toggle", false ] },
                           then: 1 },
                        { case: { $and: [ { $eq: [ "$toggle", true] },  { $eq: [ "$status", "INACTIVE" ] } ] },
                           then: -1 }
                      ]
                  }
              }
          }
      }
  },
  {
      $project:{
           _id: 0,
           iid: "$_id.iid",
           pid: "$_id.pid",
           count: 1
      }
  }
] )

[ EDIT ADD 3 ]

NOTE:

The facet query runs the two facets (TRUE and FALSE) on the same set of documents; it is like two queries running in parallel. But, there is some duplication of code as well as additional stages for shaping the documents down the pipeline to get the desired output.

The second query avoids the code duplication, and there are much lesser stages in the aggregation pipeline. This will make difference when the input dataset has a large number of documents to process - in terms of performance.  In general, lesser stages means lesser iterations of the documents (as a stage has to scan the documents which are output from the previous stage).


来源: stackexchange

问:
How to setRequiredLevel specific control or attribute?
My mission is to check if a control is visible and if it is then to set it as required.
On my form I have the same field twice (in different sections) so to check my control visibility I use this code:

```<code>if(Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").getVisible()) //works
{
              Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").setRequiredLevel("required"); //doesn't work - error
              Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").getAttribute("attrname").setRequiredLevel("required");  //doesn't work - error
}
</code>```

How do I set the required level in this case?

答:
Don't take dependencies in your code on the tab/section names. Use the shortcut method for getting the attribute

```<code>Xrm.Page.getAttribute("new_attributename");
</code>```

And if you need to call a method on a control of the attribute use the controls array to loop through the all of the controls:

```<code>Xrm.Page.getAttribute("new_attributename").controls
</code>```

Then your code will always work, as long as the attribute is somewhere on the form, and the control will work even if there is one control in the header, one in the Business Process Flow, and multiple controls in each section.

ContentLicense: CC BY-SA 4.0

Body:
My mission is to check if a control is visible and if it is then to set it as required.
On my form I have the same field twice (in different sections) so to check my control visibility I use this code:

if(Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").getVisible()) //works
{
              Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").setRequiredLevel("required"); //doesn't work - error
              Xrm.Page.ui.tabs.get("tab1").sections.get("section").controls.get("attrname").getAttribute("attrname").setRequiredLevel("required");  //doesn't work - error
}

How do I set the required level in this case?

Body:
Don't take dependencies in your code on the tab/section names. Use the shortcut method for getting the attribute

Xrm.Page.getAttribute("new_attributename");

And if you need to call a method on a control of the attribute use the controls array to loop through the all of the controls:

Xrm.Page.getAttribute("new_attributename").controls

Then your code will always work, as long as the attribute is somewhere on the form, and the control will work even if there is one control in the header, one in the Business Process Flow, and multiple controls in each section.


问:
Jasper iReport 3.0.0 font missing after reinstall the font
It used to work perfectly fine until I reinstalled a font.
It doesn't show up anymore and I can't find any solution in their community.

I'm using win10 with jre1.8.0_171.

Can anybody help?
Thank you in advance.

It's the one in the red box :

答:
Closed.
You need to put the fonts into your java runtime's fonts folder.</p>


问:
Remove product from Store in Array with Reducer removing wrong item
So I am using a Store to persist the state of props in my react front end.
However, in the cart I would like to allow the user to remove an item if they would like and next give them the ability to update QTY, etc. All from the cart and not from the initial page used to "Add to cart".

I have tried a couple methods and they seemed to work but once more items are in the Array it doesnt seem to be working as intended but once the user logs out and back in of course the DB is persisting it correctly.

My "Remove_Product" reducer looks like this:

```<code> case REMOVE_PRODUCT:
        // eslint-disable-next-line no-case-declarations
        const rmindex = action.payload.product_index
        // eslint-disable-next-line no-case-declarations
        let newProduct = [...state.product]
        newProduct.splice(rmindex, 1)
        return {
            ...state,
           product: newProduct,
           loading: true
        }
</code>```

This works until there are more items and I would like to find the best practice method for handling this so I can continue to use best practices in the application as much as possible.

答:
Not sure what you mean "This works until there are more items" but,

I personally prefer filter when removing an item from array state, which can directly return a new array with less code (no mutation of state :D)

```<code>case REMOVE_PRODUCT:
  const { product_index } = action.payload;
  return {
    ...state,
    product: state.product.filter((item, index) => product_index !== index),
    loading: true
  }
</code>```

Body:
So I am using a Store to persist the state of props in my react front end.
However, in the cart I would like to allow the user to remove an item if they would like and next give them the ability to update QTY, etc. All from the cart and not from the initial page used to "Add to cart".

I have tried a couple methods and they seemed to work but once more items are in the Array it doesnt seem to be working as intended but once the user logs out and back in of course the DB is persisting it correctly.

My "Remove_Product" reducer looks like this:

 case REMOVE_PRODUCT:
        // eslint-disable-next-line no-case-declarations
        const rmindex = action.payload.product_index
        // eslint-disable-next-line no-case-declarations
        let newProduct = [...state.product]
        newProduct.splice(rmindex, 1)
        return {
            ...state,
           product: newProduct,
           loading: true
        }

This works until there are more items and I would like to find the best practice method for handling this so I can continue to use best practices in the application as much as possible.

Body:
Not sure what you mean "This works until there are more items" but,

I personally prefer filter when removing an item from array state, which can directly return a new array with less code (no mutation of state :D)

case REMOVE_PRODUCT:
  const { product_index } = action.payload;
  return {
    ...state,
    product: state.product.filter((item, index) => product_index !== index),
    loading: true
  }


问:
How to check if a remote server supports PHP?
I often have clients who do not know if their server supports PHP (their website is HTML web site). At the moment, I send them hello.php file, they upload it and then I check it remotely if their server supports PHP. As you see this takes day or two and it's just a waste of time.

Can I myself any how check if their server supports PHP (via web browser or console tool)? If the domain is for example www.my-client.com, what would be the syntax?

Thanks

PS. I have an access to Linux console so I could use it as well

答: In addition to Darin Dimitrov's answer I can say that you could read WHOIS information about the domain and detect where it is being hosted. Then, if you identify the hoster, simply check what features he offers.</p>

ContentLicense: CC BY-SA 3.0


问:
Difference between $('.huyen') and $('.huyen')[0]
What are different between $(".huyen")[0].style.opacity and $(".huyen").style.opacity?

When I use console.log to print out value return of two statements:

$(".huyen")[0] ----> [object HTMLDivElement]

$(".huyen") -----> [object HTMLCollection]

I don't understand about having [0] and have not [0].

Can you explain for me about this problem?

答: $(".huyen") returns a reference to a jQuery object. $(".huyen")[0] references the first DOM node that the jQuery object holds in its collection of HTML elements (if any).


问:
Python RegEx - Single vs multiple line test
re.finditer() will pick the (.com) is the below text is in multiline string. The same function does not work if the text is in a single string (var ss). Can anyone please help me to understand?</p>

```<code>s = """  example (.com)
  w3resource github (.com)
    stackoverflow (.com) """

# ss = """  example (.com) w3resource github (.com) stackoverflow (.com) """
match = re.finditer(r'\(.+\)',s)
print(match)
for i in match:
    print(i)
</code>```

答:
The dot ( . ) will match any character except a newline, so in first case your greedy + stops when it finds the newline, on the later case, the greedy + works till the last parenthesis and hence perform only a single match.So it means your regex should be modified, try replacing it with below, so what I wrote it is this:
Inside a parenthesis , match a literal dot (escaped here) with a word (one or more characters) followed by a closing parenthesis. The output matches as expected</p>

```<code>import re
s = """  example (.com)
  w3resource github (.com)
    stackoverflow (.com) """

ss = """  example (.com) w3resource github (.com) stackoverflow (.com) """
match = re.finditer(r'\(\.\w+\)',ss) ## changes are done here
print(match)
for i in match:
    print(i)
</code>```

Body:
re.finditer() will pick the (.com) is the below text is in multiline string. The same function does not work if the text is in a single string (var ss). Can anyone please help me to understand?

s = """  example (.com)
  w3resource github (.com)
    stackoverflow (.com) """

# ss = """  example (.com) w3resource github (.com) stackoverflow (.com) """
match = re.finditer(r'\(.+\)',s)
print(match)
for i in match:
    print(i)

Body:
The dot ( . ) will match any character except a newline, so in first case your greedy + stops when it finds the newline, on the later case, the greedy + works till the last parenthesis and hence perform only a single match.So it means your regex should be modified, try replacing it with below, so what I wrote it is this:
Inside a parenthesis , match a literal dot (escaped here) with a word (one or more characters) followed by a closing parenthesis. The output matches as expected

import re
s = """  example (.com)
  w3resource github (.com)
    stackoverflow (.com) """

ss = """  example (.com) w3resource github (.com) stackoverflow (.com) """
match = re.finditer(r'\(\.\w+\)',ss) ## changes are done here
print(match)
for i in match:
    print(i)


问:
How to generate uniformly distributed random numbers between 0 and 1 in a C code using OpenMP?
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}
</code>```

答:
You're using xor of time (integer, in seconds) and thread ID to seed the generator. Clearly not necessarily unique across all threads and all time, so not a good idea. You'd be much better off calling srand with the output of std::random_device which on most machines (i.e. anything but a tiny embedded CPU) will seed your pseudorandom generator with real entropy.

Sample code from https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> dis(1.0, 2.0);
    for (int n = 0; n < 10; ++n) {
        // Use dis to transform the random unsigned int generated by gen into a
        // double in [1, 2). Each call to dis(gen) generates a new random double
        std::cout << dis(gen) << ' ';
    }
    std::cout << '\n';
}
```

Body:
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}


问:
How to convert time format in dolphindb?
I have a timestamp type, like x = 2020.01.24, how to covert it to format in "24-01-2020" in DolphinDB? Currently I have to use string manipulation.

答:
Please use format function to format the date.

```<code>x= 2020.01.24
format(x, "dd-MM-yyyy")
</code>```

Body:
Please use format function to format the date.

x= 2020.01.24
format(x, "dd-MM-yyyy")


问:
How to update in one to one relation in laravel?
In my user model, I have the following code

```<code>public function profile()
{
    return $this->hasOne(UserProfile::class);
}
</code>```

In profile model,

```<code>public function user()
{
   return $this->belongsTo(User::class);
}
</code>```

The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.

```<code>$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';

$user = User::find($userId);
$res = $user->profile()->save($profile);
</code>```

What is the correct method to update in One to One Relationship ?

答:
I fixed it using push method. Here is the code.

```<code>$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();
</code>```

Body:
In my user model, I have the following code

public function profile()
{
    return $this->hasOne(UserProfile::class);
}

In profile model,

public function user()
{
   return $this->belongsTo(User::class);
}

The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.

$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';

$user = User::find($userId);
$res = $user->profile()->save($profile);

What is the correct method to update in One to One Relationship ?

Body:
I fixed it using push method. Here is the code.

$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();


问:
GeoPandas loses .crs info across notebooks
I've run into an odd problem: when using GeoPandas (in Jupyter Notebooks) the .crs data works fine in my first notebook, then gets lost in my second one.

Just looking at the one world map that comes with the library, running this cell...

```<code>world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world.crs
</code>```

... in my first notebook returns...

```<code>{'init': 'epsg:4326'}
</code>```

..., while in my second notebook I get...

```<code>{}
</code>```

On top of (or because of) that, matching crs works in the first notebook but not the second. In notebook 1...

```<code>mal0 = gpd.read_file('./bird-species/E00039600_mallard.gdb', layer=0)
mal0 = mal0.to_crs(world.crs)
mal0.crs
</code>```

returns...

```<code>{'init': 'epsg:4326'}
</code>```

... as expected, but in notebook 2 it throws an error:

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-10-fd67623093a6> in <module>
      1 mal0 = gpd.read_file('./bird-species/E00039600_mallard.gdb', layer=0)
----> 2 mal0 = mal0.to_crs(world.crs)
      3 mal0.crs

~/anaconda3/lib/python3.6/site-packages/geopandas/geodataframe.py in to_crs(self, crs, epsg, inplace)
    441         else:
    442             df = self.copy()
--> 443         geom = df.geometry.to_crs(crs=crs, epsg=epsg)
    444         df.geometry = geom
    445         df.crs = geom.crs

~/anaconda3/lib/python3.6/site-packages/geopandas/geoseries.py in to_crs(self, crs, epsg)
    303                 raise TypeError('Must set either crs or epsg for output.')
    304         proj_in = pyproj.Proj(self.crs, preserve_units=True)
--> 305         proj_out = pyproj.Proj(crs, preserve_units=True)
    306         project = partial(pyproj.transform, proj_in, proj_out)
    307         result = self.apply(lambda geom: transform(project, geom))

~/anaconda3/lib/python3.6/site-packages/pyproj/__init__.py in __new__(self, projparams, preserve_units, **kwargs)
    360         # on case-insensitive filesystems).
    361         projstring = projstring.replace('EPSG','epsg')
--> 362         return _proj.Proj.__new__(self, projstring)
    363
    364     def __call__(self, *args, **kw):

_proj.pyx in _proj.Proj.__cinit__()

RuntimeError: b'no arguments in initialization list'
</code>```

Does anyone know what's going with this?

答:
I had exactly the same problem. I can reproduce this without jupyter with geopandas 0.6.1.

This is a case of unhelpful error messages. The actual error is that your crs is not supported by geopandas.

Body:
I've run into an odd problem: when using GeoPandas (in Jupyter Notebooks) the .crs data works fine in my first notebook, then gets lost in my second one.

Just looking at the one world map that comes with the library, running this cell...

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world.crs

... in my first notebook returns...

{'init': 'epsg:4326'}

..., while in my second notebook I get...

{}

On top of (or because of) that, matching crs works in the first notebook but not the second. In notebook 1...

mal0 = gpd.read_file('./bird-species/E00039600_mallard.gdb', layer=0)
mal0 = mal0.to_crs(world.crs)
mal0.crs

returns...

{'init': 'epsg:4326'}

... as expected, but in notebook 2 it throws an error:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-10-fd67623093a6> in <module>
      1 mal0 = gpd.read_file('./bird-species/E00039600_mallard.gdb', layer=0)
----> 2 mal0 = mal0.to_crs(world.crs)
      3 mal0.crs

~/anaconda3/lib/python3.6/site-packages/geopandas/geodataframe.py in to_crs(self, crs, epsg, inplace)
    441         else:
    442             df = self.copy()
--> 443         geom = df.geometry.to_crs(crs=crs, epsg=epsg)
    444         df.geometry = geom
    445         df.crs = geom.crs

~/anaconda3/lib/python3.6/site-packages/geopandas/geoseries.py in to_crs(self, crs, epsg)
    303                 raise TypeError('Must set either crs or epsg for output.')
    304         proj_in = pyproj.Proj(self.crs, preserve_units=True)
--> 305         proj_out = pyproj.Proj(crs, preserve_units=True)
    306         project = partial(pyproj.transform, proj_in, proj_out)
    307         result = self.apply(lambda geom: transform(project, geom))

~/anaconda3/lib/python3.6/site-packages/pyproj/__init__.py in __new__(self, projparams, preserve_units, **kwargs)
    360         # on case-insensitive filesystems).
    361         projstring = projstring.replace('EPSG','epsg')
--> 362         return _proj.Proj.__new__(self, projstring)
    363
    364     def __call__(self, *args, **kw):

_proj.pyx in _proj.Proj.__cinit__()

RuntimeError: b'no arguments in initialization list'

Does anyone know what's going with this?


答:
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that.

See More: https://learn.jquery.com/using-jquery-core/jquery-object/

So when you call:

```<code>$(".huyen")
</code>```

This represents a jQuery Object. That object has a number of elements within it. You can call the first element by the the 0 index:

```<code>$(".huyen")[0]
</code>```

For example, when you use:

```<code>$(".huyen")[0].style.opacity = 0.95;
</code>```

This allows you to access the DOM Elements and change the style. To do this in jQuery you can do:

```<code>$(".huyen").css("opacity", 0.95);
</code>```

.css() is a specific function in the collection of that jQuery Object.

Title: Difference between $('.huyen') and $('.huyen')[0]

Body:
What are different between $(".huyen")[0].style.opacity and $(".huyen").style.opacity?

When I use console.log to print out value return of two statements:

$(".huyen")[0] ----> [object HTMLDivElement]

$(".huyen") -----> [object HTMLCollection]

I don't understand about having [0] and have not [0].

Can you explain for me about this problem?

Body:
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that.

See More: https://learn.jquery.com/using-jquery-core/jquery-object/

So when you call:

$(".huyen")

This represents a jQuery Object. That object has a number of elements within it. You can call the first element by the the 0 index:

$(".huyen")[0]

For example, when you use:

$(".huyen")[0].style.opacity = 0.95;

This allows you to access the DOM Elements and change the style. To do this in jQuery you can do:

$(".huyen").css("opacity", 0.95);

.css() is a specific function in the collection of that jQuery Object.


问:
Mongodb database after a few day, suddenly it deleted automatically?
after I deployed my application and used it for a few days, suddenly it deleted automatically, I have no idea what happened to my mongoDB. Can anyone give me the suggestions or ideas of what happened to my application regarding the mongoDB? Thank you.

Cloud server: Digitalocean
Technology: MERN Stack Application

答:
is the directory there that it was in?....does it contain files?
sounds like you need to talk to the hosting company</p>


问:
Why am I getting the error in post? Laravel
So I'm trying to create a simple REST API using Laravel.
While testing out the API with creating new items to the database I'm receiving an error:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (world.cities, CONSTRAINT cities_ibfk_1 FOREIGN KEY (CountryCode) REFERENCES country (Code)) (SQL: insert into cities (Name, CountryCode, District, Population, updated_at, created_at) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669

here's the Controller:

```<code>
      public function createCity(Request $request) {
        $city = new City;
        $city->Name = $request->Name;
        $city->CountryCode = $request->CountryCode;
        $city->District = $request->District;
        $city->Population = $request->Population;
        $city->save();
</code>```

Model:

```<code>class City extends Model
{
    protected $table = 'cities';

    protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}
</code>```

Help would be appreciated as I can't figure out why I'm getting the error after POST.
Thanks in advance.

答:
You try to add vlh as contry_code value into your model .but this field refrence to another model that have country name and in that table there is not any record with this condition and vlh value is unknown or it.

You can romve relation between these models (if it is possible) or first find the id of country that has that code and then insert it into your model.

Body:
So I'm trying to create a simple REST API using Laravel.
While testing out the API with creating new items to the database I'm receiving an error:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (world.cities, CONSTRAINT cities_ibfk_1 FOREIGN KEY (CountryCode) REFERENCES country (Code)) (SQL: insert into cities (Name, CountryCode, District, Population, updated_at, created_at) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669

here's the Controller:

      public function createCity(Request $request) {
        $city = new City;
        $city->Name = $request->Name;
        $city->CountryCode = $request->CountryCode;
        $city->District = $request->District;
        $city->Population = $request->Population;
        $city->save();

Model:

class City extends Model
{
    protected $table = 'cities';

    protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}

Help would be appreciated as I can't figure out why I'm getting the error after POST.
Thanks in advance.


问:
How to sort values and index with a pivot table using Pandas
Giving this data:

```<code> data = [{'Group1': 'A', 'Group2 date':'01/20/20', 'value1':0, 'value2':1},
         {'Group1': 'A', 'Group2 date':'01/25/20', 'value1':0, 'value2':3},
         {'Group1': 'A', 'Group2 date':'02/28/20', 'value1':0, 'value2':2},
         {'Group1': 'B', 'Group2 date':'01/25/20', 'value1':0, 'value2':1},
         {'Group1': 'B', 'Group2 date':'01/27/20', 'value1':2, 'value2':2},
         {'Group1': 'C', 'Group2 date':'01/29/20', 'value1':0, 'value2':5},
         {'Group1': 'C', 'Group2 date':'01/30/20', 'value1':2, 'value2':6}]
</code>```

I have a pivot table created with pandas using:

```<code>pivot = pd.pivot_table(
  df,
  index=["Group1", "Group2 date"],
  values=["value1", "value2"],
  aggfunc={"value1":np.sum, "value2":np.sum},
)
</code>```

and I'm getting a table like this:

```<code>                     value1  value2
Group1  Group2 date
A       01/20/20          0       1
        01/25/20          0       3
        01/28/20          0       2
B       01/25/20          0       1
        01/27/20          2       2
C       01/29/20          0       5
        01/30/20          2       6
</code>```

But I need first the table sorted by "value2" with the highest values and then "Group2 date" be always descending to get something like:

```<code>                     value1  value2
Group1  Group2 date
C       01/30/20          2       6
        01/29/20          0       5
A       01/28/20          0       2
        01/25/20          0       3
        01/20/20          0       1
B       01/27/20          2       2
        01/25/20          0       1
</code>```

Is possible?, how?

答:
This is what I could pull out: lemme know if it works for you. I used your data, just in a flattened form, as I was unsuccessful in reading in the multiindex.</p>

```<code>data = '''

Group1  Group2_date value1  value2
A       01/20/20          0       1
A        01/25/20          0       3
A        01/28/20          0       2
B       01/25/20          0       1
B        01/27/20          2       2
C       01/29/20          0       5
C        01/30/20          2       6
   '''

df = pd.read_csv(StringIO(data), sep='\s+',engine='python')

#create a temp column, getting the max dates from each group

df['filler'] = df.groupby('Group1').Group2_date.transform('max')

#sort dataframe on filler and group1, so that the latest dates are at the top

df = df.sort_values(['filler','Group1'],ascending=False)

#list comprehension on a second groupby, this time using the filler and Group1
#note  the use of loc to flip the rows

M = [group.loc[::-1,]
     for name, group in
     df.groupby(['filler','Group1'],sort=False)]

#concat and print result

outcome = pd.concat(M).drop('filler',axis=1)

    Group1  Group2_date value1  value2
6       C   01/30/20        2   6
5       C   01/29/20        0   5
2       A   01/28/20        0   2
1       A   01/25/20        0   3
0       A   01/20/20        0   1
4       B   01/27/20        2   2
3       B   01/25/20        0   1
</code>```

Body:
Giving this data:

 data = [{'Group1': 'A', 'Group2 date':'01/20/20', 'value1':0, 'value2':1},
         {'Group1': 'A', 'Group2 date':'01/25/20', 'value1':0, 'value2':3},
         {'Group1': 'A', 'Group2 date':'02/28/20', 'value1':0, 'value2':2},
         {'Group1': 'B', 'Group2 date':'01/25/20', 'value1':0, 'value2':1},
         {'Group1': 'B', 'Group2 date':'01/27/20', 'value1':2, 'value2':2},
         {'Group1': 'C', 'Group2 date':'01/29/20', 'value1':0, 'value2':5},
         {'Group1': 'C', 'Group2 date':'01/30/20', 'value1':2, 'value2':6}]

I have a pivot table created with pandas using:

pivot = pd.pivot_table(
  df,
  index=["Group1", "Group2 date"],
  values=["value1", "value2"],
  aggfunc={"value1":np.sum, "value2":np.sum},
)

and I'm getting a table like this:

                     value1  value2
Group1  Group2 date
A       01/20/20          0       1
        01/25/20          0       3
        01/28/20          0       2
B       01/25/20          0       1
        01/27/20          2       2
C       01/29/20          0       5
        01/30/20          2       6

But I need first the table sorted by "value2" with the highest values and then "Group2 date" be always descending to get something like:

                     value1  value2
Group1  Group2 date
C       01/30/20          2       6
        01/29/20          0       5
A       01/28/20          0       2
        01/25/20          0       3
        01/20/20          0       1
B       01/27/20          2       2
        01/25/20          0       1

Is possible?, how?

Body:
This is what I could pull out: lemme know if it works for you. I used your data, just in a flattened form, as I was unsuccessful in reading in the multiindex.

data = '''

Group1  Group2_date value1  value2
A       01/20/20          0       1
A        01/25/20          0       3
A        01/28/20          0       2
B       01/25/20          0       1
B        01/27/20          2       2
C       01/29/20          0       5
C        01/30/20          2       6
   '''

df = pd.read_csv(StringIO(data), sep='\s+',engine='python')

#create a temp column, getting the max dates from each group

df['filler'] = df.groupby('Group1').Group2_date.transform('max')

#sort dataframe on filler and group1, so that the latest dates are at the top

df = df.sort_values(['filler','Group1'],ascending=False)

#list comprehension on a second groupby, this time using the filler and Group1
#note  the use of loc to flip the rows

M = [group.loc[::-1,]
     for name, group in
     df.groupby(['filler','Group1'],sort=False)]

#concat and print result

outcome = pd.concat(M).drop('filler',axis=1)

    Group1  Group2_date value1  value2
6       C   01/30/20        2   6
5       C   01/29/20        0   5
2       A   01/28/20        0   2
1       A   01/25/20        0   3
0       A   01/20/20        0   1
4       B   01/27/20        2   2
3       B   01/25/20        0   1


问:
Allow guest user ownership over an app registration in order to manage certificates and secrets
On our AD tenant I am testing guest user ownership over an app registration + service principal. I want to allow an external daemon service to call my .NET Core REST API. In order to do so securely I need an identity provider trusted by both parties, and one that limits the administrative overhead of managing credential stores.

Instead of deploying IdentityServer or doing something stupid like hardcoding basic-auth passwords in my API, I am considering using our Azure AD tenant, and have the external client registered as an app in our tenant. They can then easily authenticate that daemon app against AD and call my API, and I skip the need of managing said credential store. Also, the client gets password refresh etc, they can manage their own credentials. Yay!

It is my understanding based on this page, that a guest can be made owner over the app registration and the service principal. Done so succesfully, on both the AzureAD App, and on the AzureAD ServicePrincipal objects.
After which the guest user should be able to manage certain aspects of that app registration. Specifically, I want the guest user to be able to manage the credentials for that app registration. The documentation page states that the guest is allowed to:

Guest user permissions

Read properties of registered and enterprise applications

Manage application properties, assignments, and credentials for owned
applications

Delete owned applications

Restore owned applications

However, even after signing out and back in to refresh my tokens, the Azure Portal still blocks my testing guest user from managing the app I made him owner of. (The error actually has a hyperlink to the page showing owners, and lo and behold, the guest account is shown as the owner)

The question is whether I am missing a key configuration entry somewhere to allow this to happen, or, is the documentation wrong and are guests simply not allowed to manage the credentials contained within the service principal object?

答:
I can reproduce your issue, according to the doc, the guest should be able to manage the credentials for owned applications, not sure why it happens, just two solutions for you here.

1.Per my test, you could navigate to the Azure AD in the portal -> User settings -> click Manage external collaboration settings -> set the Guest users permissions are limited to No, then the guest user can manage the credentials for the owned  application successfully.

Note: If the Guest users permissions are limited is No, the Guest user will have some other permissions as the Member user, e.g. create a new app registration, view other applications which he is not an Owner of.

2.This option is that I recommend you to use, create a custom admin role in AAD, assign the role to the Guest user at the scope of the specific application, the Guest users permissions are limited could be Yes. After doing that, the Guest user just has permissions in the specific application, other permissions are like a normal Guest user.

Just create the role in the portal, and assign the role to the user at the scope of the owned application.

You could also do this with Powershell or Graph API, reference - Create and assign a custom role in Azure Active Directory.

For the permissions in the custom role, they all depend on your requirement, this is my role.

After assigning the role, it works.


问:
C++ program that catches SIGKILL under Linux
I want to make a core when my process receive the SIGKILL in linux.
I try to caught this signal, but it seems that SIGKILL can't be catch.</p>

答:
That is correct, As per the man page for sigaction:

signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP.

This has pretty much been the case forever, you really don't want to give a process the ability to handle all signals since that would allow you to get to a point where it can only be killed by a power cycle :-)


问:
Sending values from one form to another without returning to form 1
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

```<code>// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}
</code>```

And...

```<code>// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}
</code>```

答:
You can try something like this

In Form2

```<code>public void SetText(string text)
    {
        this.label1.Text = text;
    }
</code>```

And In Form1

```<code>private void Form1Button1_Click(object sender, EventArgs e)
    {
        using (Form2 form2 = new Form2())
        {
            form2.SetText(this.textBox1.Text);
            form2.ShowDialog();
        }
    }
</code>```

If you don't want a modal dialog then change the Form1 code like below

```<code>Form2 form2 = new Form2();
    public Form1()
    {
        InitializeComponent();
    }
private void Form1Button1_Click(object sender, EventArgs e)
    {
        form2.SetText(this.textBox1.Text);
        form2.Show();
    }
</code>```

Body:
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}

Body:
You can try something like this

In Form2

public void SetText(string text)
    {
        this.label1.Text = text;
    }

And In Form1

private void Form1Button1_Click(object sender, EventArgs e)
    {
        using (Form2 form2 = new Form2())
        {
            form2.SetText(this.textBox1.Text);
            form2.ShowDialog();
        }
    }

If you don't want a modal dialog then change the Form1 code like below

Form2 form2 = new Form2();
    public Form1()
    {
        InitializeComponent();
    }
private void Form1Button1_Click(object sender, EventArgs e)
    {
        form2.SetText(this.textBox1.Text);
        form2.Show();
    }


问:
C - How to read input separated by commans and whitespaces
I have a question on how to read input and assigning it to an array (or even two arrays).

I have a project where I have to:

```<code>Create a C console application to compile the following statistics on a list of real number pairs:
•   minimum value;
•   maximum value;
•   median value;
•   arithmetic mean;
•   mean absolute deviation – (mean, median, mode)
•   variance (of a discrete random variable);
•   standard deviation (of a finite population);
•   mode (including multi-modal lists).
•   least squares regression line
•   outliers
</code>```

Your program must handle any length of list.  The list will be input (or piped) from the console, or read from a file.  The list is terminated with end-of-stream (^Z) or non-numeric input.

So basically, the program has to read:

```<code>1,2
2,23
3,45
5,34
</code>```

or: 1,2 3,4 5,6 7,8
and be able to calculate their statistic properties.

I know how to do the calculations and create the functions etc. My question is, how to implement the parts: "any length of the list" and "list of real number pairs". See sample below.

sample output

What I tried so far:

```<code>#include <stdio.h>

int main()
{
    int a[100];
    int b[100];
    int n = 100;

    for (int i = 0; i < n; i++) {
        scanf_s("%d,", &a[i]);
    }

    for (int i = 0; i < n; i++) {
        printf(" %d", a[i]);
    }

    return 0;
}
</code>```

which returns a the result, but only to a fixed array length and gives me a bunch of -858993460 -858993460.

For now, I just want to know how to read the input properly and assign them to one Array, so I can read the odd and even index and calculate their mean and whatever respectively...

or assign them to two different arrays (x[], y[]), x for the digit on the left of the comma, y on the right.

答:
Hi you can get the entire input in a single line in a character array and then loop on the array to correctly split the char array to convert it into integer array.
Below is the code you can try : </p>

```<code>#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;
  while ( sscanf ( src, "%d%n", &arr[index], &n ) == 1 ) {
  //while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {  ////Use this for values separated by commas
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}
</code>```

Body:
I have a question on how to read input and assigning it to an array (or even two arrays).

I have a project where I have to:

Create a C console application to compile the following statistics on a list of real number pairs:
•   minimum value;
•   maximum value;
•   median value;
•   arithmetic mean;
•   mean absolute deviation – (mean, median, mode)
•   variance (of a discrete random variable);
•   standard deviation (of a finite population);
•   mode (including multi-modal lists).
•   least squares regression line
•   outliers

Your program must handle any length of list.  The list will be input (or piped) from the console, or read from a file.  The list is terminated with end-of-stream (^Z) or non-numeric input.

So basically, the program has to read:

1,2
2,23
3,45
5,34

or: 1,2 3,4 5,6 7,8
and be able to calculate their statistic properties.

I know how to do the calculations and create the functions etc. My question is, how to implement the parts: "any length of the list" and "list of real number pairs". See sample below.

sample output

What I tried so far:

#include <stdio.h>

int main()
{
    int a[100];
    int b[100];
    int n = 100;

    for (int i = 0; i < n; i++) {
        scanf_s("%d,", &a[i]);
    }

    for (int i = 0; i < n; i++) {
        printf(" %d", a[i]);
    }

    return 0;
}

which returns a the result, but only to a fixed array length and gives me a bunch of -858993460 -858993460.

For now, I just want to know how to read the input properly and assign them to one Array, so I can read the odd and even index and calculate their mean and whatever respectively...

or assign them to two different arrays (x[], y[]), x for the digit on the left of the comma, y on the right.

Body:
Hi you can get the entire input in a single line in a character array and then loop on the array to correctly split the char array to convert it into integer array.
Below is the code you can try :

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;
  while ( sscanf ( src, "%d%n", &arr[index], &n ) == 1 ) {
  //while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {  ////Use this for values separated by commas
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}


问:
How Do You Use WebMessagePort As An Alternative to addJavascriptInterface()?
Google's security guidelines for Android app developers has the following:

WebViews do not use addJavaScriptInterface() with untrusted content.

On Android M and above, HTML message channels can be used instead.

Near as I can tell, "HTML message channels" refers to things like createWebMessageChannel(), WebMessagePort, WebMessage, and kin.

However, they do not provide any examples. All they do is link to a WhatWG specification, which is rather unclear. And, based on a Google search for createWebMessageChannel, it appears that this has not been used much yet — my blog post describing changes in the Android 6.0 SDK makes the top 10 search results, and I just mention it in passing.

addJavascriptInterface() is used to allow JavaScript in a WebView to call into Java code supplied by the app using the WebView. How would we use "HTML message channels" as a replacement for that?

答:
Here's a solution using the compat lib:
Download Full Solution in Android Studio format

This example uses an index.html and an index.js file stored in the assets folder.

Here is the JS:

```<code>const channel = new MessageChannel();
var nativeJsPortOne = channel.port1;
var nativeJsPortTwo = channel.port2;
window.addEventListener('message', function(event) {
    if (event.data != 'capturePort') {
        nativeJsPortOne.postMessage(event.data)
    } else if (event.data == 'capturePort') {
        /* The following three lines form Android class 'WebViewCallBackDemo' capture the port and assign it to nativeJsPortTwo
        var destPort = arrayOf(nativeToJsPorts[1])
        nativeToJsPorts[0].setWebMessageCallback(nativeToJs!!)
        WebViewCompat.postWebMessage(webView, WebMessageCompat("capturePort", destPort), Uri.EMPTY) */
        if (event.ports[0] != null) {
            nativeJsPortTwo = event.ports[0]
        }
    }
}, false);

nativeJsPortOne.addEventListener('message', function(event) {
    alert(event.data);
}, false);

nativeJsPortTwo.addEventListener('message', function(event) {
    alert(event.data);
}, false);
nativeJsPortOne.start();
nativeJsPortTwo.start();
</code>```

And here is the HTML:

```<code><!DOCTYPE html>
<html lang="en-gb">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebView Callback Demo</title>
    <script src="js/index.js"></script>
</head>
<body>
    <div style="font-size: 24pt; text-align: center;">
        <input type="button" value="Test" onclick="nativeJsPortTwo.postMessage(msgFromJS.value);" style="font-size: inherit;" /><br />
        <input id="msgFromJS" type="text" value="JavaScript To Native" style="font-size: 16pt; text-align: inherit; width: 80%;" />
    </div>
</body>
</html>
</code>```

And finally Here is the native Android code:

```<code>class PostMessageHandler(webView: WebView) {
    private val nativeToJsPorts = WebViewCompat.createWebMessageChannel(webView)
    private var nativeToJs: WebMessagePortCompat.WebMessageCallbackCompat? = null
    init {
        if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_CALLBACK_ON_MESSAGE)) {
            nativeToJs = object : WebMessagePortCompat.WebMessageCallbackCompat() {
                override fun onMessage(port: WebMessagePortCompat, message: WebMessageCompat?) {
                    super.onMessage(port, message)
                    Toast.makeText(webView.context, message!!.data, Toast.LENGTH_SHORT).show()
                }
            }
        }
        var destPort = arrayOf(nativeToJsPorts[1])
        nativeToJsPorts[0].setWebMessageCallback(nativeToJs!!)
        WebViewCompat.postWebMessage(webView, WebMessageCompat("capturePort", destPort), Uri.EMPTY)
    }
}
</code>```

It is important the the native code be executed from the 'WebViewClient.onPageFinished(webView: WebView, url: String)' callback.
See download link above for full details. This project shows postMessage working both ways (Native to JS and JS to Native)
Hope this helps.

Body:
Here's a solution using the compat lib:
Download Full Solution in Android Studio format

This example uses an index.html and an index.js file stored in the assets folder.

Here is the JS:

const channel = new MessageChannel();
var nativeJsPortOne = channel.port1;
var nativeJsPortTwo = channel.port2;
window.addEventListener('message', function(event) {
    if (event.data != 'capturePort') {
        nativeJsPortOne.postMessage(event.data)
    } else if (event.data == 'capturePort') {
        /* The following three lines form Android class 'WebViewCallBackDemo' capture the port and assign it to nativeJsPortTwo
        var destPort = arrayOf(nativeToJsPorts[1])
        nativeToJsPorts[0].setWebMessageCallback(nativeToJs!!)
        WebViewCompat.postWebMessage(webView, WebMessageCompat("capturePort", destPort), Uri.EMPTY) */
        if (event.ports[0] != null) {
            nativeJsPortTwo = event.ports[0]
        }
    }
}, false);

nativeJsPortOne.addEventListener('message', function(event) {
    alert(event.data);
}, false);

nativeJsPortTwo.addEventListener('message', function(event) {
    alert(event.data);
}, false);
nativeJsPortOne.start();
nativeJsPortTwo.start();

And here is the HTML:

<!DOCTYPE html>
<html lang="en-gb">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebView Callback Demo</title>
    <script src="js/index.js"></script>
</head>
<body>
    <div style="font-size: 24pt; text-align: center;">
        <input type="button" value="Test" onclick="nativeJsPortTwo.postMessage(msgFromJS.value);" style="font-size: inherit;" /><br />
        <input id="msgFromJS" type="text" value="JavaScript To Native" style="font-size: 16pt; text-align: inherit; width: 80%;" />
    </div>
</body>
</html>

And finally Here is the native Android code:

class PostMessageHandler(webView: WebView) {
    private val nativeToJsPorts = WebViewCompat.createWebMessageChannel(webView)
    private var nativeToJs: WebMessagePortCompat.WebMessageCallbackCompat? = null
    init {
        if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_CALLBACK_ON_MESSAGE)) {
            nativeToJs = object : WebMessagePortCompat.WebMessageCallbackCompat() {
                override fun onMessage(port: WebMessagePortCompat, message: WebMessageCompat?) {
                    super.onMessage(port, message)
                    Toast.makeText(webView.context, message!!.data, Toast.LENGTH_SHORT).show()
                }
            }
        }
        var destPort = arrayOf(nativeToJsPorts[1])
        nativeToJsPorts[0].setWebMessageCallback(nativeToJs!!)
        WebViewCompat.postWebMessage(webView, WebMessageCompat("capturePort", destPort), Uri.EMPTY)
    }
}

It is important the the native code be executed from the 'WebViewClient.onPageFinished(webView: WebView, url: String)' callback.
See download link above for full details. This project shows postMessage working both ways (Native to JS and JS to Native)
Hope this helps.


问:
Compile Error CS0433 on pre-compiled ASP.NET 2.0 site
I keep getting this error ever so often when I launch the debugger to debug my site.  I'm using the Telerik controls, and usually the error is in my tab strip.  Here is an example of the error I'm looking at right now:

```<code>Compiler Error Message: CS0433: The type 'ASP.controls_motorvehiclegeneral_ascx' exists in both 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll' and 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll'

Source Error:

Line 48:     </telerik:RadTabStrip>
Line 49:     <telerik:RadMultiPage ID="RadMultiPageControls" Runat="server" SelectedIndex="0">
Line 50:     <telerik:RadPageView ID="PageGeneral" runat="server"><uc1:General ID="GeneralControl" runat="server" /></telerik:RadPageView>
Line 51:     <telerik:RadPageView ID="PageVehicle" runat="server"><uc1:VehicleList ID="VehicleList" runat="server" /></telerik:RadPageView>
Line 52:     <telerik:RadPageView ID="PagePerson" runat="server"><uc1:PersonList ID="PersonList" runat="server" /></telerik:RadPageView>
</code>```

The thing that bothers me most, is if I just keep hitting F5, the page WILL refresh and work as it should.  Sometimes it takes several refreshes to do this, others it happens pretty quick.  I have not been able to find a solution on the net, as most of the people with this error are upgrading from VS2005 to Web Application, and thus the fix seems to be "Remove your app_code directory, and change the CodeFile= to CodeBehind=.  But, the CodeBehind is old, and not used anymore.

In this instance, I'm getting the error on my General tab, but it can happen of ANY of my user controls when it DOES happen.

Has anyone else seen this with pre-compiled pages?  I'm using VS2008 SP1.

The other effect I've seen related to this is when I have a GridView setup with a datasource, and the datasource changes, but the page does not update until several other operations, then all at once all the data is filled in...  This makes me think there is some sort of cache issue, or compile-time, time-out or something...

I am using a site.master page, and have checked the @Page and @Master directives...  Just for the sake of argument, here are the compiler options it's using...

```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE> "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /t:library /utf8output /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6614ff9a\005164fc_423cc801\PetersDatePackage.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.IdentityModel\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.Common\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.Common.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_0-em44qa.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Utilities\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Utilities.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6fe979bb\0056bc44_4b94c701\Microsoft.Practices.EnterpriseLibrary.Common.DLL" /R:"C:\WINDOWS\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\ad70f8ed\0010f920_4b94c701\Microsoft.Practices.EnterpriseLibrary.Data.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel.Web\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\d61e8194\009ae0bd_854ec901\Telerik.Web.UI.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\98ba2ae7\211fb135_e674c901\CoreAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\1.0.61025.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Management\2.0.0.0__b03f5f7f11d50a3a\System.Management.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\62fa267e\9888875e_bb5cc901\AjaxControlToolkit.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Framework\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Framework.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Code.nufffrfb.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\52f6447d\f90fd1c8_b475c901\StatisticsAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\955f38e7\982cdc0f_bc5cc901\Validators.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.WebForms\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.WebForms.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_nv7t8gs_.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Design\2.0.0.0__b03f5f7f11d50a3a\System.Design.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\a5daf5e0\0071b5e7_909cc701\Microsoft.Practices.ObjectBuilder.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.ProcessingObjectModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_atcckswk.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll" /out:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.dll" /D:DEBUG /debug+ /optimize- /win32res:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\zva2jsmk.res" /nowarn:1659;1699;1701 /d:DBCONVERTPUBLIC;CRYSTALSUPPORT  "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.0.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.1.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.2.cs"
```

Anyone have any ideas where I can even start to look?

答: in IIS you need to restart it by opening the command prompt and typing iisreset then hit enter, however if your using the build in Visual Studio web server (Cassini) then this wont solve your problem. You can terminate all running Cassini instances by typing (exactly like this because its Case Sensitive): taskkill /f /im "WebDev.WebServer.exe" and hitting enter. You will then see the following message: SUCCESS: The Process "WebDev.WebServer.EXE" with PID <some #> has been terminated.

OwnerDisplayName: LarryF

ContentLicense: CC BY-SA 2.5

Body:
I keep getting this error ever so often when I launch the debugger to debug my site.  I'm using the Telerik controls, and usually the error is in my tab strip.  Here is an example of the error I'm looking at right now:

Compiler Error Message: CS0433: The type 'ASP.controls_motorvehiclegeneral_ascx' exists in both 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll' and 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll'

Source Error:

Line 48:     </telerik:RadTabStrip>
Line 49:     <telerik:RadMultiPage ID="RadMultiPageControls" Runat="server" SelectedIndex="0">
Line 50:     <telerik:RadPageView ID="PageGeneral" runat="server"><uc1:General ID="GeneralControl" runat="server" /></telerik:RadPageView>
Line 51:     <telerik:RadPageView ID="PageVehicle" runat="server"><uc1:VehicleList ID="VehicleList" runat="server" /></telerik:RadPageView>
Line 52:     <telerik:RadPageView ID="PagePerson" runat="server"><uc1:PersonList ID="PersonList" runat="server" /></telerik:RadPageView>

The thing that bothers me most, is if I just keep hitting F5, the page WILL refresh and work as it should.  Sometimes it takes several refreshes to do this, others it happens pretty quick.  I have not been able to find a solution on the net, as most of the people with this error are upgrading from VS2005 to Web Application, and thus the fix seems to be "Remove your app_code directory, and change the CodeFile= to CodeBehind=.  But, the CodeBehind is old, and not used anymore.

In this instance, I'm getting the error on my General tab, but it can happen of ANY of my user controls when it DOES happen.

Has anyone else seen this with pre-compiled pages?  I'm using VS2008 SP1.

The other effect I've seen related to this is when I have a GridView setup with a datasource, and the datasource changes, but the page does not update until several other operations, then all at once all the data is filled in...  This makes me think there is some sort of cache issue, or compile-time, time-out or something...

I am using a site.master page, and have checked the @Page and @Master directives...  Just for the sake of argument, here are the compiler options it's using...

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE> "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /t:library /utf8output /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6614ff9a\005164fc_423cc801\PetersDatePackage.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.IdentityModel\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.Common\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.Common.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_0-em44qa.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Utilities\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Utilities.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6fe979bb\0056bc44_4b94c701\Microsoft.Practices.EnterpriseLibrary.Common.DLL" /R:"C:\WINDOWS\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\ad70f8ed\0010f920_4b94c701\Microsoft.Practices.EnterpriseLibrary.Data.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel.Web\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\d61e8194\009ae0bd_854ec901\Telerik.Web.UI.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\98ba2ae7\211fb135_e674c901\CoreAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\1.0.61025.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Management\2.0.0.0__b03f5f7f11d50a3a\System.Management.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\62fa267e\9888875e_bb5cc901\AjaxControlToolkit.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Framework\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Framework.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Code.nufffrfb.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\52f6447d\f90fd1c8_b475c901\StatisticsAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\955f38e7\982cdc0f_bc5cc901\Validators.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.WebForms\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.WebForms.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_nv7t8gs_.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Design\2.0.0.0__b03f5f7f11d50a3a\System.Design.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\a5daf5e0\0071b5e7_909cc701\Microsoft.Practices.ObjectBuilder.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.ProcessingObjectModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_atcckswk.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll" /out:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.dll" /D:DEBUG /debug+ /optimize- /win32res:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\zva2jsmk.res" /nowarn:1659;1699;1701 /d:DBCONVERTPUBLIC;CRYSTALSUPPORT  "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.0.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.1.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.2.cs"

Anyone have any ideas where I can even start to look?

LastEditorDisplayName: Rich B

OwnerDisplayName: mknopf


问:
How to scroll to middle (50%) of page
Without using the popular scrollTo plugin, how can I scroll to the vertical middle (50%) of the page/div?</p>

答:
This scrolls the internal scroll of a div to it's vertical middle</p>

```<code>var myDiv = $("#yourdiv");
var scrollto = myDiv.offset().top + (myDiv.height() / 2);
myDiv.animate({ scrollTop:  scrollto});
</code>```

Title: How to scroll to middle (50%) of page

Body:
This scrolls the internal scroll of a div to it's vertical middle

var myDiv = $("#yourdiv");
var scrollto = myDiv.offset().top + (myDiv.height() / 2);
myDiv.animate({ scrollTop:  scrollto});


问:
oracle: deferring Foreign Key checks not working
oracle: deferring Foreign Key checks not working. e.g.,

```<code>create table Foo (id number(20,0), name varchar(20),
    primary key(id));
create table Bar (id number(20,0), name varchar(20),
    primary key(id),
    constraint FK1 foreign key (id) references Foo (id));

insert into Foo(id,name) values(1, 'foo');
insert into Bar(id,name) values(1, 'bar');
</code>```

delete data:

```<code>SET CONSTRAINTS ALL DEFERRED;

delete from Foo;
delete from Bar;

SET CONSTRAINTS ALL IMMEDIATE;
</code>```

ERROR:

```<code>ORA-02292: integrity constraint violated - child record found
</code>```

答:
You can't defer a constraint if it is NOT DEFERRABLE. A constraint can be either deferrable or not, but the default (if you don't explicitly specify either way) is NOT DEFERRABLE.

In your sample code, add the keyword deferrable right after the foreign key constraint definition, and then run everything again. It will work as expected.

That is: Edit the following line of code

```<code>constraint FK1 foreign key (id) references Foo (id));
</code>```

to

```<code>constraint FK1 foreign key (id) references Foo (id) deferrable);
</code>```

Body:
oracle: deferring Foreign Key checks not working. e.g.,

create table Foo (id number(20,0), name varchar(20),
    primary key(id));
create table Bar (id number(20,0), name varchar(20),
    primary key(id),
    constraint FK1 foreign key (id) references Foo (id));

insert into Foo(id,name) values(1, 'foo');
insert into Bar(id,name) values(1, 'bar');

delete data:

SET CONSTRAINTS ALL DEFERRED;

delete from Foo;
delete from Bar;

SET CONSTRAINTS ALL IMMEDIATE;

ERROR:

ORA-02292: integrity constraint violated - child record found

Body:
You can't defer a constraint if it is NOT DEFERRABLE. A constraint can be either deferrable or not, but the default (if you don't explicitly specify either way) is NOT DEFERRABLE.

In your sample code, add the keyword deferrable right after the foreign key constraint definition, and then run everything again. It will work as expected.

That is: Edit the following line of code

constraint FK1 foreign key (id) references Foo (id));

to

constraint FK1 foreign key (id) references Foo (id) deferrable);


问:
Struggling to scrape multiple pages - Cheerio.js
I am trying to create a web scraper using Javascript and Cheerio and I'm running into some difficulty when I try to scrape data from url's within scraped pages. For example, I scrape a first page for a few details (including a URL of a linked page) and then when I try to scrape the linked page using a callback function I am unable to assign the return value to the object. Both of the scrapers work individually however I am having issues getting them to run asynchronously and the variable detailsPage always returns as undefined.

Any help would be greatly appreciated!

```<code>const cheerio = require("cheerio");
const axios = require("axios");

const scrapeAllData = () => {
  return scrapeListingPage(scrapeFullDetailsPage, "www.fakeURL.com");
};

function scrapeListingPage(callbackFn, url) {
  axios.get(url)
    .then(response => {
      const $ = cheerio.load(response.data);
      let products = [];
      let singleProduct = {};

      $(".page-content-thumbs-two .row .col-sm-8").each((i, e) => {
        singleProduct = {
          price: $(e).find($("h3")),
          shortDescription: $(e).find($("p")),
          fullProductDetailsURL: $(e).find($("a")).attr("href"),
          detailsPageData: {}
        };
        singleProduct.detailsPage = scrapeFullDetailsPage(singleProduct.fullDescriptionURL);
        products.push(singleProduct);
      });
      console.log("Product DATA --> ", products);
    });
}

function scrapeFullDetailsPage(url) {
  axios.get(url).then(res => {
    const $ = cheerio.load(res.data);
    let detailsPageData = {};
    $("#container").each((i, e) => {
      detailsPageData.fullDescription = $(e)
        .find($("p span"))
        .text();
    });
    console.log("detailsPageData", detailsPageData);
    return detailsPageData;
  });
}

scrapeAllData();
</code>```

答:
The reason why your singleProduct.detailsPage is always empty is that scrapeFullDetailsPage() function is asynchronous by nature, because axios library is Promise-based.

Please look into How to make axios synchronous as one potential solution, and I hope it helps.

Body:
I am trying to create a web scraper using Javascript and Cheerio and I'm running into some difficulty when I try to scrape data from url's within scraped pages. For example, I scrape a first page for a few details (including a URL of a linked page) and then when I try to scrape the linked page using a callback function I am unable to assign the return value to the object. Both of the scrapers work individually however I am having issues getting them to run asynchronously and the variable detailsPage always returns as undefined.

Any help would be greatly appreciated!

const cheerio = require("cheerio");
const axios = require("axios");

const scrapeAllData = () => {
  return scrapeListingPage(scrapeFullDetailsPage, "www.fakeURL.com");
};

function scrapeListingPage(callbackFn, url) {
  axios.get(url)
    .then(response => {
      const $ = cheerio.load(response.data);
      let products = [];
      let singleProduct = {};

      $(".page-content-thumbs-two .row .col-sm-8").each((i, e) => {
        singleProduct = {
          price: $(e).find($("h3")),
          shortDescription: $(e).find($("p")),
          fullProductDetailsURL: $(e).find($("a")).attr("href"),
          detailsPageData: {}
        };
        singleProduct.detailsPage = scrapeFullDetailsPage(singleProduct.fullDescriptionURL);
        products.push(singleProduct);
      });
      console.log("Product DATA --> ", products);
    });
}

function scrapeFullDetailsPage(url) {
  axios.get(url).then(res => {
    const $ = cheerio.load(res.data);
    let detailsPageData = {};
    $("#container").each((i, e) => {
      detailsPageData.fullDescription = $(e)
        .find($("p span"))
        .text();
    });
    console.log("detailsPageData", detailsPageData);
    return detailsPageData;
  });
}

scrapeAllData();


问:
Docker Ubuntu 18.04 unable to install msodbcsql17 SQL Server ODBC Driver 17
I have the below ubuntu docker file to which I want to add SQL Server ODBC Driver 17 for installation. When I build the docker file, I am getting an error:
'/bin/sh -c apt-get install msodbcsql17' returned a non-zero code: 1

Could you please help?

I am referring to the article - https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15

I followed the steps in the article in my Ubuntu VM and it works fine and I am able to run my python programs. However, when I use the docker file I get the error

```<code>FROM ubuntu:18.04

RUN apt update -y  &&  apt upgrade -y && apt-get update
RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-dev

RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN exit
#RUN ACCEPT_EULA=Y apt-get install msodbcsql17
RUN apt-get update
RUN ACCEPT_EULA=Y
RUN apt-get install msodbcsql17
#RUN ACCEPT_EULA=Y apt install msodbcsql17
RUN ACCEPT_EULA=Y apt install mssql-tools
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

COPY startup.sh /
RUN chmod +x /startup.sh
ENTRYPOINT ["sh","/startup.sh"]
</code>```

答:
I could get it working. Below is the updated Docker file snippet </p>

```<code>FROM ubuntu:18.04

RUN apt update -y  &&  apt upgrade -y && apt-get update
RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-dev

# Add SQL Server ODBC Driver 17 for Ubuntu 18.04
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated msodbcsql17
RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated mssql-tools
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

COPY startup.sh /
RUN chmod +x /startup.sh
ENTRYPOINT ["sh","/startup.sh"]
</code>```

Body:
I have the below ubuntu docker file to which I want to add SQL Server ODBC Driver 17 for installation. When I build the docker file, I am getting an error:
'/bin/sh -c apt-get install msodbcsql17' returned a non-zero code: 1

Could you please help?

I am referring to the article - https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15

I followed the steps in the article in my Ubuntu VM and it works fine and I am able to run my python programs. However, when I use the docker file I get the error

FROM ubuntu:18.04

RUN apt update -y  &&  apt upgrade -y && apt-get update
RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-dev

RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN exit
#RUN ACCEPT_EULA=Y apt-get install msodbcsql17
RUN apt-get update
RUN ACCEPT_EULA=Y
RUN apt-get install msodbcsql17
#RUN ACCEPT_EULA=Y apt install msodbcsql17
RUN ACCEPT_EULA=Y apt install mssql-tools
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

COPY startup.sh /
RUN chmod +x /startup.sh
ENTRYPOINT ["sh","/startup.sh"]

Body:
I could get it working. Below is the updated Docker file snippet

FROM ubuntu:18.04

RUN apt update -y  &&  apt upgrade -y && apt-get update
RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-dev

# Add SQL Server ODBC Driver 17 for Ubuntu 18.04
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated msodbcsql17
RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated mssql-tools
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

COPY startup.sh /
RUN chmod +x /startup.sh
ENTRYPOINT ["sh","/startup.sh"]


问:
fatal: unable to access ".....": gnutls_handshake() failed: Handshake failed
I've been using Git for the past few months. Recently when I try to clone or to push, I keep on getting this error. I've researched on the internet but so far no solution has worked for me. Does anyone have an idea?

External note : Now I moved to different country, it was working perfectly where I was before.
Git Version : 2.11.0   , OS : Debian GNU/Linux 9.11 (stretch)

Error :

```<code>git push
fatal: unable to access 'https://**************/': gnutls_handshake() failed: Handshake failed
</code>```

答:
This error means that Git cannot establish a secure connection to the server you're trying to use.  Your version of Git uses the GnuTLS library to set up TLS (encrypted) connections, and for some reason that setup process is failing.

This could be for a couple of reasons.  One is that your server (which one you haven't mentioned) is using an incompatible set of cipher suites or TLS versions, and there's no encryption algorithms in common that can be chosen.  It's also possible that you have someone tampering with the connection via a MITM device.

The version of Git and GnuTLS you're using should work just fine with most standard servers.  Re-installing it won't help.  You can try upgrading to a newer version of Debian, or you can try building Git yourself against a version of libcurl using OpenSSL.  You can also just switch to SSH-based remotes, which will avoid this incompatibility altogether.

Body:
I've been using Git for the past few months. Recently when I try to clone or to push, I keep on getting this error. I've researched on the internet but so far no solution has worked for me. Does anyone have an idea?

External note : Now I moved to different country, it was working perfectly where I was before.
Git Version : 2.11.0   , OS : Debian GNU/Linux 9.11 (stretch)

Error :

git push
fatal: unable to access 'https://**************/': gnutls_handshake() failed: Handshake failed


问:
How to check if a remote server supports PHP?
I often have clients who do not know if their server supports PHP (their website is HTML web site). At the moment, I send them hello.php file, they upload it and then I check it remotely if their server supports PHP. As you see this takes day or two and it's just a waste of time.

Can I myself any how check if their server supports PHP (via web browser or console tool)? If the domain is for example www.my-client.com, what would be the syntax?

Thanks

PS. I have an access to Linux console so I could use it as well

答:
As Darin Dimitrov says some Servers promote the versions of the uses software.  You can use curl to view the HTTP Header of a response.</p>

```<code>> curl -I http://example.com

HTTP/1.1 200 OK
Date: Tue, 17 May 2011 10:04:01 GMT
Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.10 with Suhosin-Patch
X-Powered-By: PHP/5.2.4-2ubuntu5.10
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
</code>```

Body:
As Darin Dimitrov says some Servers promote the versions of the uses software.  You can use curl to view the HTTP Header of a response.

> curl -I http://example.com

HTTP/1.1 200 OK
Date: Tue, 17 May 2011 10:04:01 GMT
Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.10 with Suhosin-Patch
X-Powered-By: PHP/5.2.4-2ubuntu5.10
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8


问:
How to disable dragging from a Rich Edit Control
I use a subclass of CRichEditCtrl to provide a CEdit+ type control. One thing I want is to disable drag-drop functionality, which the base class provided by default.

Disabling dropping is easy: ::RevokeDragDrop(m_hWnd);

But I can't see a simple way to disable the control being a drag-source. Is there an easy way?

答:
To Override Starting Drag-and-Drop in the RichEdit Control:

Implement IRichEditOleCallback interface.

implement GetDragDropEffect() method of the interface like this:

```<code>HRESULT CRichEditOleCallback::GetDragDropEffect( BOOL fDrag, DWORD grfKeyState,
            LPDWORD pdwEffect)
{
    CComPtr<IDataObject> pdata_obj;
    CComQIPtr<IDropSource> psource;
    DWORD dwEffect;

    // You put here your own data-object code....

    DoDragDrop( pdata_obj, psource, DROPEFFECT_COPY|DROPEFFECT_MOVE, &dwEffect);
    // This executes your own drag and drop function.

    return E_ABORT; // !!!! THIS IS ESSENTIALLY IMPORTANT !!!! NOT WRITTEN IN MANUAL !!!!
}
</code>```

Most important here is return E_ABORT; this causes quitting default drag and drop operation and starting the customized one.

To Override Receiving Drag and Drop Operation in the RichEdit Control:

Implement your own IDropTarget Interface.

Register IDropTarget interface like this:

After Creating RichEdit control in RichEdit derived subclass function:

```<code>CComPtr<IDropTarget> pDropTarget; // this is your own customized drop target.

RevokeDragDrop(m_hWnd); // unregister default IDropTarget interface of Rich Edit.
RegisterDragDrop(m_hWnd, pDropTarget);
</code>```

This example overrides the default drop target function of RichEdit.

Body:
To Override Starting Drag-and-Drop in the RichEdit Control:

Implement IRichEditOleCallback interface.

implement GetDragDropEffect() method of the interface like this:

HRESULT CRichEditOleCallback::GetDragDropEffect( BOOL fDrag, DWORD grfKeyState,
            LPDWORD pdwEffect)
{
    CComPtr<IDataObject> pdata_obj;
    CComQIPtr<IDropSource> psource;
    DWORD dwEffect;

    // You put here your own data-object code....

    DoDragDrop( pdata_obj, psource, DROPEFFECT_COPY|DROPEFFECT_MOVE, &dwEffect);
    // This executes your own drag and drop function.

    return E_ABORT; // !!!! THIS IS ESSENTIALLY IMPORTANT !!!! NOT WRITTEN IN MANUAL !!!!
}

Most important here is return E_ABORT; this causes quitting default drag and drop operation and starting the customized one.

To Override Receiving Drag and Drop Operation in the RichEdit Control:

Implement your own IDropTarget Interface.

Register IDropTarget interface like this:

After Creating RichEdit control in RichEdit derived subclass function:

CComPtr<IDropTarget> pDropTarget; // this is your own customized drop target.

RevokeDragDrop(m_hWnd); // unregister default IDropTarget interface of Rich Edit.
RegisterDragDrop(m_hWnd, pDropTarget);

This example overrides the default drop target function of RichEdit.