问:
Lambda expression with empty capture
I've encountered an interesting case (at least for me) when using lambdas and was wondering whether it is a compiler bug or something allowed by the standard feature.

Let's cut to the chase. Having sample code:

```<code>const int controlValue = 5;
std::vector<int> vect{ 0, 1, 2, 3 };
const auto result = std::any_of(vect.begin(), vect.end(), [](const int& item)
{
    return item == controlValue;
});
</code>```

Notice that controlValue variable is not captured by the lambda expression.
Additionally, in the cppreference for lambda expressions it is stated that [] - captures nothing

Using VS2015 for compilation of the above code gives an error which is not surprising:

```<code>error C3493: 'controlValue' cannot be implicitly captured because no default capture mode has been specified
</code>```

However, when using MinGW with gcc 4.8.2 same example compiles and works.
Some online compilers including gcc 5.4.0, clang 3.8.0 give similar result.

When controlValue loses its const then all tested compilers give the error all expect (that the variable is not captured which is fine).

Which of the compilers is standard compliant in this case?
Does this mean that some optimizations or other "hacks" are used for const variables here? Maybe something is captured implicitly?
Could anyone explain the situation happening here?

EDIT:

Some pointed out that this question is a duplicate of Lambda capturing constexpr object
. While the answer there may be somewhat related (points to the odr-use case) the question there is about an error occurring while capturing by ref. The topic here is quite different and focuses on not capturing explicitly a variable at all (although using it in the lambda body).

After looking through more lambda related questions, if someone's interested, I'd point to Using lambda captured constexpr value as an array dimension
 which (same as @Barry stated) suggests VS2015 bug and shows that setting the controlValue variable in the example here to static fixes the compilation under VS2015.

答:
This is a VS bug. The code is perfectly well-formed.

The rule in [expr.prim.lambda] is:

If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses (3.2) this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression.

Where a variable is odr-used if, according to [basic.def.odr]:

A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.20) that does not invoke any non-trivial
  functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion (4.1) is applied to e, or e is a discarded-value expression (Clause 5).

And, from [expr.const]:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the
  abstract machine (1.9), would evaluate one of the following expressions:  [...] an lvalue-to-rvalue conversion (4.1) unless it is applied to a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression

In:

```<code>return item == controlValue;
</code>```

controlValue is a glvalue of integral type that refers to a complete non-volatile const object initialized with a constant expression. Hence, when we use controlValue in a context that involves an lvalue-to-rvalue conversion, it is not odr-used. Since it's not odr-used, we don't need to capture it.

When you changed controlValue to be non-const, it's ceases to be a constant expression, and the equality check odr-uses it. Since it's not captured but is odr-used, the lambda is ill-formed.

Note that exactly such an example appears in the standard:

```<code>void f(int, const int (&)[2] = {}) { }   // #1
void f(const int&, const int (&)[1]) { } // #2
void test() {
    const int x = 17;
    auto g = [](auto a) {
        f(x); // OK: calls #1, does not capture x
    };

    // ...
}
</code>```

Title: Lambda expression with empty capture

Body:
I've encountered an interesting case (at least for me) when using lambdas and was wondering whether it is a compiler bug or something allowed by the standard feature.

Let's cut to the chase. Having sample code:

const int controlValue = 5;
std::vector<int> vect{ 0, 1, 2, 3 };
const auto result = std::any_of(vect.begin(), vect.end(), [](const int& item)
{
    return item == controlValue;
});

Notice that controlValue variable is not captured by the lambda expression.
Additionally, in the cppreference for lambda expressions it is stated that [] - captures nothing

Using VS2015 for compilation of the above code gives an error which is not surprising:

error C3493: 'controlValue' cannot be implicitly captured because no default capture mode has been specified

However, when using MinGW with gcc 4.8.2 same example compiles and works.
Some online compilers including gcc 5.4.0, clang 3.8.0 give similar result.

When controlValue loses its const then all tested compilers give the error all expect (that the variable is not captured which is fine).

Which of the compilers is standard compliant in this case?
Does this mean that some optimizations or other "hacks" are used for const variables here? Maybe something is captured implicitly?
Could anyone explain the situation happening here?

EDIT:

Some pointed out that this question is a duplicate of Lambda capturing constexpr object
. While the answer there may be somewhat related (points to the odr-use case) the question there is about an error occurring while capturing by ref. The topic here is quite different and focuses on not capturing explicitly a variable at all (although using it in the lambda body).

After looking through more lambda related questions, if someone's interested, I'd point to Using lambda captured constexpr value as an array dimension
 which (same as @Barry stated) suggests VS2015 bug and shows that setting the controlValue variable in the example here to static fixes the compilation under VS2015.

Body:
This is a VS bug. The code is perfectly well-formed.

The rule in [expr.prim.lambda] is:

If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses (3.2) this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression.

Where a variable is odr-used if, according to [basic.def.odr]:

A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.20) that does not invoke any non-trivial
  functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion (4.1) is applied to e, or e is a discarded-value expression (Clause 5).

And, from [expr.const]:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the
  abstract machine (1.9), would evaluate one of the following expressions:  [...] an lvalue-to-rvalue conversion (4.1) unless it is applied to a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression

In:

return item == controlValue;

controlValue is a glvalue of integral type that refers to a complete non-volatile const object initialized with a constant expression. Hence, when we use controlValue in a context that involves an lvalue-to-rvalue conversion, it is not odr-used. Since it's not odr-used, we don't need to capture it.

When you changed controlValue to be non-const, it's ceases to be a constant expression, and the equality check odr-uses it. Since it's not captured but is odr-used, the lambda is ill-formed.

Note that exactly such an example appears in the standard:

void f(int, const int (&)[2] = {}) { }   // #1
void f(const int&, const int (&)[1]) { } // #2
void test() {
    const int x = 17;
    auto g = [](auto a) {
        f(x); // OK: calls #1, does not capture x
    };

    // ...
}


来源: stackexchange

问:
Complex aggregation query involving nested arrays
I'm moving my first steps into MongoDB but I'm having difficulties into writing complex queries.

I have several items like this in my collection:

```
{
    "_id" : "sku001",
    "deposits" : [
        {
            "deposit_id" : "deposit01",
            "total" : "3",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "2"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "0"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "1"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit02",
            "total" : "5",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "1"
                },
                {
                    "size" : "38",
                    "stock" : "1"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "1"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "1"
                },
                {
                    "size" : "48",
                    "stock" : "1"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit03",
            "total" : "2",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "1"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "1"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "0"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit04",
            "total" : "0",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "0"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "0"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "0"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        }
    ]
}
```

and would like to write a query which will output this resulting document:

```
{
    "_id" : "sku001",
    "total": 10,
    "sizes" [
        {
            "size" : "36",
            "stock" : "4"
        },
        {
            "size" : "38",
            "stock" : "1"
        },
        {
            "size" : "40",
            "stock" : "0"
        },
        {
            "size" : "42",
            "stock" : "2"
        },
        {
            "size" : "44",
            "stock" : "0"
        },
        {
            "size" : "46",
            "stock" : "2"
        },
        {
            "size" : "48",
            "stock" : "1"
        },
        {
            "size" : "50",
            "stock" : "0"
        },
        {
            "size" : "52",
            "stock" : "0"
        }
    ]
}
```

so that:

total is the sum the "total" field in each deposit

sizes is the resulting array given from the sum of the same size in each deposit

I know that I need to use aggregate() with $unwind, $group and maybe $project, but I don't understand how and in which order.

Can you help me? I'm using MongoDB version 3.4.3

答:
You may want to change your schema first before even applying the operators in the aggregation framework to produce your desired report i.e. the string values need to be parsed to numbers and then run the aggregate operation.

Changing the schema

To change the schema, you'd need to iterate the collection and for each document in the collection update the keys which need to have the string values parsed to numbers. You may want to create a temporary collection with the updated schema if it's not possible to change the original collection schema.
For the former, consider running the following update operation (for relatively small collections):

```<code>db.collection.find({}).snapshot()
  .forEach(function(doc) {
        var query = { "_id": doc._id },
            update = { "$set": {} };

        for (var i=0; i<doc.deposits.length; i++) {
            update["$set"]["deposits."+i+".total"] =  parseInt(doc.deposits[i].total);
            for (var j=0; j<doc.deposits[i].sizes.length; j++) {
                update["$set"]["deposits."+i+".sizes."+j+".stock"] = parseInt(doc.deposits[i].sizes[j].stock);
            }
        }

        printjson(query);
        printjson(update);

        db.collection.updateOne( query, update );
  });
</code>```

Aggregate Pipeline

Having the correct schema will allow you to run the pipeline in the following aggregate operation which should give you the desired report:

```<code>db.collection.aggregate([
    { "$unwind": "$deposits" },
    { "$unwind": "$deposits.sizes" },
    {
        "$group": {
            "_id": {
                "id": "$_id",
                "size": "$deposits.sizes.size"
            },
            "total_stock": { "$sum": "$deposits.sizes.stock" },
            "deposits": {
                "$push": {
                    "deposit_id": "$deposits.deposit_id",
                    "total":  "$deposits.total"
                }
            }
        }
    },
    { "$unwind": "$deposits" },
    {
        "$group": {
            "_id": {
                "id": "$_id.id",
                "deposit_id": "$deposits.deposit_id"
            },
            "sizes": {
                "$push": {
                    "size": "$_id.size",
                    "stock": "$total_stock"
                }
            },
            "total": { "$first": "$deposits.total" }
        }
    },
    {
        "$group": {
            "_id": "$_id.id",
            "total": { "$sum": "$total" },
            "sizes": { "$first": "$sizes" }
        }
    }
])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm moving my first steps into MongoDB but I'm having difficulties into writing complex queries.

I have several items like this in my collection:

{
    "_id" : "sku001",
    "deposits" : [
        {
            "deposit_id" : "deposit01",
            "total" : "3",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "2"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "0"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "1"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit02",
            "total" : "5",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "1"
                },
                {
                    "size" : "38",
                    "stock" : "1"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "1"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "1"
                },
                {
                    "size" : "48",
                    "stock" : "1"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit03",
            "total" : "2",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "1"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "1"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "0"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        },
        {
            "deposit_id" : "deposit04",
            "total" : "0",
            "sizes" : [
                {
                    "size" : "36",
                    "stock" : "0"
                },
                {
                    "size" : "38",
                    "stock" : "0"
                },
                {
                    "size" : "40",
                    "stock" : "0"
                },
                {
                    "size" : "42",
                    "stock" : "0"
                },
                {
                    "size" : "44",
                    "stock" : "0"
                },
                {
                    "size" : "46",
                    "stock" : "0"
                },
                {
                    "size" : "48",
                    "stock" : "0"
                },
                {
                    "size" : "50",
                    "stock" : "0"
                },
                {
                    "size" : "52",
                    "stock" : "0"
                }
            ]
        }
    ]
}

and would like to write a query which will output this resulting document:

{
    "_id" : "sku001",
    "total": 10,
    "sizes" [
        {
            "size" : "36",
            "stock" : "4"
        },
        {
            "size" : "38",
            "stock" : "1"
        },
        {
            "size" : "40",
            "stock" : "0"
        },
        {
            "size" : "42",
            "stock" : "2"
        },
        {
            "size" : "44",
            "stock" : "0"
        },
        {
            "size" : "46",
            "stock" : "2"
        },
        {
            "size" : "48",
            "stock" : "1"
        },
        {
            "size" : "50",
            "stock" : "0"
        },
        {
            "size" : "52",
            "stock" : "0"
        }
    ]
}

so that:

total is the sum the "total" field in each deposit

sizes is the resulting array given from the sum of the same size in each deposit

I know that I need to use aggregate() with $unwind, $group and maybe $project, but I don't understand how and in which order.

Can you help me? I'm using MongoDB version 3.4.3

Body:
You may want to change your schema first before even applying the operators in the aggregation framework to produce your desired report i.e. the string values need to be parsed to numbers and then run the aggregate operation.

Changing the schema

To change the schema, you'd need to iterate the collection and for each document in the collection update the keys which need to have the string values parsed to numbers. You may want to create a temporary collection with the updated schema if it's not possible to change the original collection schema.
For the former, consider running the following update operation (for relatively small collections):

db.collection.find({}).snapshot()
  .forEach(function(doc) {
        var query = { "_id": doc._id },
            update = { "$set": {} };

        for (var i=0; i<doc.deposits.length; i++) {
            update["$set"]["deposits."+i+".total"] =  parseInt(doc.deposits[i].total);
            for (var j=0; j<doc.deposits[i].sizes.length; j++) {
                update["$set"]["deposits."+i+".sizes."+j+".stock"] = parseInt(doc.deposits[i].sizes[j].stock);
            }
        }

        printjson(query);
        printjson(update);

        db.collection.updateOne( query, update );
  });

Aggregate Pipeline

Having the correct schema will allow you to run the pipeline in the following aggregate operation which should give you the desired report:

db.collection.aggregate([
    { "$unwind": "$deposits" },
    { "$unwind": "$deposits.sizes" },
    {
        "$group": {
            "_id": {
                "id": "$_id",
                "size": "$deposits.sizes.size"
            },
            "total_stock": { "$sum": "$deposits.sizes.stock" },
            "deposits": {
                "$push": {
                    "deposit_id": "$deposits.deposit_id",
                    "total":  "$deposits.total"
                }
            }
        }
    },
    { "$unwind": "$deposits" },
    {
        "$group": {
            "_id": {
                "id": "$_id.id",
                "deposit_id": "$deposits.deposit_id"
            },
            "sizes": {
                "$push": {
                    "size": "$_id.size",
                    "stock": "$total_stock"
                }
            },
            "total": { "$first": "$deposits.total" }
        }
    },
    {
        "$group": {
            "_id": "$_id.id",
            "total": { "$sum": "$total" },
            "sizes": { "$first": "$sizes" }
        }
    }
])


问:
Moving average calculation for empty points in excel
I am generating trendline for the given data points using excel trendline formula. In normal case (without empty points) moving average is working fine. But i not able to proceed with empty points for moving average trendline. I couldn't find out the moving average formula for empty points. Please refer the below excel moving average chart with period 2

If i changed period value to 3, this empty point value changed

Can anyone suggest a solution?

答:
For your case, moving average is like this:

```<code>     A     B     C     D
----+-----------------------
1   |x     y     MA(2) MA(3)
2   |1     1
3   |2     5     3
4   |3     17    11    7.67
5   |4           17    11
6   |5     4     4     10.5
</code>```

It has nothing to do with an empty point (more precisely, missing data). MA with interval 2 is calculated based on (ie, taking average of) current and a previous value. So C3 is =AVERAGE(B2:B3), C4 is =AVERAGE(B3:B4), and so on.

Likewise MA with interval 3 is calculated based on current and previous two values. D4 is =AVERAGE(B2:B4), D5 is =AVERAGE(B3:B5), and D6 is =AVERAGE(B4:B6). You can see that those MA values are exact the same in the plot.

This is called simple moving average. You'd better read this article for more gentle explanation.

Body:
For your case, moving average is like this:

     A     B     C     D
----+-----------------------
1   |x     y     MA(2) MA(3)
2   |1     1
3   |2     5     3
4   |3     17    11    7.67
5   |4           17    11
6   |5     4     4     10.5

It has nothing to do with an empty point (more precisely, missing data). MA with interval 2 is calculated based on (ie, taking average of) current and a previous value. So C3 is =AVERAGE(B2:B3), C4 is =AVERAGE(B3:B4), and so on.

Likewise MA with interval 3 is calculated based on current and previous two values. D4 is =AVERAGE(B2:B4), D5 is =AVERAGE(B3:B5), and D6 is =AVERAGE(B4:B6). You can see that those MA values are exact the same in the plot.

This is called simple moving average. You'd better read this article for more gentle explanation.


问:
How to stop updating the field or variable in object while copyToRealmOrUpdate in realm
```<code>Pojo Class:

public class ChannelResponse extends RealmObject{
   private RealmList<TvChannel> tv_channel;
}

public class TvChannel extends RealmObject{
@PrimaryKey
private String id;
private String stream_display_name;
private String stream_icon;
private String streaming_url;
private int isFavorite;
}
</code>```

here isFavorite is int which should not get updated while updation of other fields when i get from API channelResponse and in api json object TvChannel dosent have isFavorite feild.

i am updating like this:

```<code>Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(channelResponse);
realm.commitTransaction();
realm.close();
</code>```

答:
Query the object if it exists

if yes, save out its isFavorite into a boolean variable

say copyToRealmOrUpdate()

you receive a proxy

then call setFavorite(isFavorite) on the proxy you received from  copyToRealmOrUpdate().

Body:
Pojo Class:

public class ChannelResponse extends RealmObject{
   private RealmList<TvChannel> tv_channel;
}

public class TvChannel extends RealmObject{
@PrimaryKey
private String id;
private String stream_display_name;
private String stream_icon;
private String streaming_url;
private int isFavorite;
}

here isFavorite is int which should not get updated while updation of other fields when i get from API channelResponse and in api json object TvChannel dosent have isFavorite feild.

i am updating like this:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(channelResponse);
realm.commitTransaction();
realm.close();


问:
How do I escape a reserved word in Oracle?
In TSQL I could use something like Select [table] from tablename to select a column named "table".

How do I do this for reserved words in oracle?

Edit: I've tried square braces, double quotes, single quotes, and backquotes, they don't work...

As a further clarification, I have a column which someone named comment.  As this is a reserved word oracle is chucking a wobbly trying to select with it, its failing when parsing the query.  I've tried Select "comment" from tablename but it didn't work.  I'll check case and come back.

答:
double quotes worked in oracle when I had the keyword as one of the column name.

eg:

```<code>select t."size" from table t
</code>```

Body:
double quotes worked in oracle when I had the keyword as one of the column name.

eg:

select t."size" from table t


问:
Redirect all URLs to HTTPS/WWW versions using IIS
I have a website and just purchased an SSL. I want all URLs to redirect to their HTTPS/WWW versions. For example:

```<code>1. http://mywebsite.com       ->   https://www.mywebsite.com
2. https://mywebsite.com      ->   https://www.mywebsite.com
3. http://www.mywebsite.com   ->   https://www.mywebsite.com
4. https://www.mywebsite.com  ->   [No redirect needed]
</code>```

I already tried some solutions: this and this from marked-as-answer approaches. But almost all of answers return "Not Found. HTTP Error 404" for case 2, i.e. https://mywebsite.com didn't redirect to https://www.mywebsite.com but returned 404 instead.

Already-tried solutions:

1.

```<code><rule name="Redirect top domains with non-www to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^([^\.]+)\.([^\.]+)$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      <serverVariables>
        <set name="Redirect" value="false" />
      </serverVariables>
</rule>
<rule name="Force HTTPS" enabled="true" stopProcessing="true">
      <match url="(.*)" ignoreCase="false" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
 </rule>
</code>```

2.

```<code><rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAny">
      <add input="{HTTP_HOST}" pattern="^[^www]" />
      <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://www.zzz.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</code>```

It seems some other people have this problem too. But I couldn't find the right solution.

答: The problem was in the Site Bindings section of IIS. There was no record for https://mywebsite.com. I added this record and the solutions in the question worked. For more info about this feature, visit this page.

Body:
I have a website and just purchased an SSL. I want all URLs to redirect to their HTTPS/WWW versions. For example:

1. http://mywebsite.com       ->   https://www.mywebsite.com
2. https://mywebsite.com      ->   https://www.mywebsite.com
3. http://www.mywebsite.com   ->   https://www.mywebsite.com
4. https://www.mywebsite.com  ->   [No redirect needed]

I already tried some solutions: this and this from marked-as-answer approaches. But almost all of answers return "Not Found. HTTP Error 404" for case 2, i.e. https://mywebsite.com didn't redirect to https://www.mywebsite.com but returned 404 instead.

Already-tried solutions:

1.

<rule name="Redirect top domains with non-www to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^([^\.]+)\.([^\.]+)$" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      <serverVariables>
        <set name="Redirect" value="false" />
      </serverVariables>
</rule>
<rule name="Force HTTPS" enabled="true" stopProcessing="true">
      <match url="(.*)" ignoreCase="false" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
 </rule>

2.

<rule name="Force WWW and SSL" enabled="true" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAny">
      <add input="{HTTP_HOST}" pattern="^[^www]" />
      <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://www.zzz.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

It seems some other people have this problem too. But I couldn't find the right solution.


问:
Get line number of beginning and end of Ruby method given a ruby file
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

```<code>1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end
</code>```

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

答:
Ruby source is nothing but a text file. You can use linux commands to find the method line number</p>

```<code>grep -nrw 'def initialize' home.rb | grep -oE '[0-9]+'
</code>```

Body:
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

Body:
Ruby source is nothing but a text file. You can use linux commands to find the method line number

grep -nrw 'def initialize' home.rb | grep -oE '[0-9]+'


问:
Is there something like Statas xtline in R? Or: How do you quickly visualize a panel?
I find some of the Stata functions to quickly get an idea of what your panel is doing extremely useful. xtline is one. It gives you an overview of your variable in different lineplots: one for each country and all over time in one window.

It looks like this and while it isn't fast, its very useful to check if some operation did what you think it did. Does anyone know if a package which does something like that exist? If not, what are your tricks?

答:
Simples:

```<code>dfr <- data.frame(id = rep(1:5, each = 20), time = rep(1991:2010, 5),
      variable = rnorm(100))
</code>```

Equivalent of xtline:

```<code>library(ggplot2)
ggplot(dfr, aes(x = time, y = variable)) + geom_line() + facet_wrap(~id)
</code>```

Equivalent of xtline with overlay option:

```<code>ggplot(dfr, aes(x = time, y = variable, group = id, color = id)) + geom_line()
</code>```

Body:
Simples:

dfr <- data.frame(id = rep(1:5, each = 20), time = rep(1991:2010, 5),
      variable = rnorm(100))

Equivalent of xtline:

library(ggplot2)
ggplot(dfr, aes(x = time, y = variable)) + geom_line() + facet_wrap(~id)

Equivalent of xtline with overlay option:

ggplot(dfr, aes(x = time, y = variable, group = id, color = id)) + geom_line()


问:
c# Using AmazonS3 SDK for RIAK
I am tryng to use amazon S3 SDK to upload images on RIAK, but i am constantly receiving 403 forbidden. Supplied credentials are good. Any ideas?

Here's the code:

```<code>Amazon.S3.AmazonS3Config config = new Amazon.S3.AmazonS3Config();
config.ServiceURL = "http://s3.mydomain.hr";
Amazon.S3.AmazonS3Client client = new Amazon.S3.AmazonS3Client("*********", "**************", config);
Amazon.S3.Model.PutObjectRequest por = new Amazon.S3.Model.PutObjectRequest();
por.BucketName = "mybucket";
por.CannedACL = Amazon.S3.S3CannedACL.PublicRead;
por.Key = key;
por.InputStream = f;
Amazon.S3.Model.PutObjectResponse resp = await client.PutObjectAsync(por);
</code>```

答: It turns out i had to downgrade version of my S3 SDK, due to changes in authorization and signatures in newer versions.</p>

Title: c# Using AmazonS3 SDK for RIAK

Body:
I am tryng to use amazon S3 SDK to upload images on RIAK, but i am constantly receiving 403 forbidden. Supplied credentials are good. Any ideas?

Here's the code:

Amazon.S3.AmazonS3Config config = new Amazon.S3.AmazonS3Config();
config.ServiceURL = "http://s3.mydomain.hr";
Amazon.S3.AmazonS3Client client = new Amazon.S3.AmazonS3Client("*********", "**************", config);
Amazon.S3.Model.PutObjectRequest por = new Amazon.S3.Model.PutObjectRequest();
por.BucketName = "mybucket";
por.CannedACL = Amazon.S3.S3CannedACL.PublicRead;
por.Key = key;
por.InputStream = f;
Amazon.S3.Model.PutObjectResponse resp = await client.PutObjectAsync(por);


问:
Error (400) Bad Request when attempting to connect to Sabre API
I am trying to connect to the Sabre API using  the following code:

```<code>Dim u As String = "https://developer.sabre.com/io-docs/call-api"

' Create the web request
request2 = DirectCast(WebRequest.Create(u), HttpWebRequest)

' Get response
response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

' Get the response stream into a reader
reader2 = New StreamReader(response2.GetResponseStream())

' Console application output

' MsgBox(reader.ReadToEnd())
Response.Write(reader.ReadToEnd())
</code>```

However I am getting the following error:

Server Error in '/' Application.

The remote server returned an error: (400) Bad Request.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Source Error:

Line 49:

Line 50:         ' Get response

Line 51:         response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

Line 52:

Line 53:         ' Get the response stream into a reader

答:
I recommend you to go through the REST basics: https://developer.sabre.com/docs/rest_basics

There you have the different environment URLs, how to create sessions, and how to start consuming the REST APIs, same works for SOAP APIs.

The process on how to actually call each service will depend on the language, since you seem to be using VB.NET here you have 2 guides I found.

Using the REST Services with .NET (Microsoft.com)

https://msdn.microsoft.com/en-us/library/jj819168.aspx

Consuming a Json WebService from a C# or VB Application (Codeproject.com)
https://www.codeproject.com/Articles/233698/Consuming-a-Json-WebService-from-a-Csharp-or-VB-Ap

Body:
I am trying to connect to the Sabre API using  the following code:

Dim u As String = "https://developer.sabre.com/io-docs/call-api"

' Create the web request
request2 = DirectCast(WebRequest.Create(u), HttpWebRequest)

' Get response
response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

' Get the response stream into a reader
reader2 = New StreamReader(response2.GetResponseStream())

' Console application output

' MsgBox(reader.ReadToEnd())
Response.Write(reader.ReadToEnd())

However I am getting the following error:

Server Error in '/' Application.

The remote server returned an error: (400) Bad Request.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Source Error:

Line 49:

Line 50:         ' Get response

Line 51:         response2 = DirectCast(request2.GetResponse(), HttpWebResponse)

Line 52:

Line 53:         ' Get the response stream into a reader


问:
converting datetime variable to timespan variable
I have an interface that is feeding me a datetimeupdated variable with the type of DateTime but I need to read it as type TimeSpan. I'm trying to do the conversion and it kind of worked but not really. I followed this post.
Convert DateTime to TimeSpan

Code:

```<code>if (e.CmsData != null)
{
    List<NewAgent> newAgentList = new List<NewAgent>();

    Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
    {
        foreach (var item in e.CmsData.Agents)
        {
            NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

            newAgents.AgentName = item.AgName;

            newAgents.AgentExtension = item.Extension;

            newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

            newAgents.AuxReasons = item.AuxReasonDescription;

            newAgents.LoginIdentifier = item.LoginId;

            ConvertedDateTimeUpdated = item.DateTimeUpdated - new DateTime(01/01/2000);
            time = ConvertedDateTimeUpdated;
            agentTime = time -  DateTime.Now.TimeOfDay;

            newAgents.AgentDateTimeStateChange = agentTime;
            newAgentList.Add(newAgents);
        }

        datagrid.ItemsSource = newAgentList;
    }));
}
</code>```

XAML:

```<code><DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
    <DataGridTextColumn Header="Aux Reason" Binding="{Binding AuxReasons}" />
    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange}" />
</DataGrid.Columns>
</code>```

AgentClass

```<code>class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }

    }
</code>```

When I print this out to my list I get the below pasted into the fields instead of a format of 00:00:00.

please let me know if this is not enough code to understand what I am trying to accomplish and I'll post all of what I have. Also important to note that item.datetimeupdated is in the format of 00/00/0000 00:00:00.

答:
I think that what you're trying to accomplish is display the time portion of the DateTime instance; but represented as a TimeSpan.

In which case, this should be all you need.

```<code>var timeSpan = item.DateTimeUpdated.TimeOfDay;
</code>```

If you're trying to display "How long ago from now was this updated?" Then you'll need to do something like..

```<code>var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
</code>```

(These answers do not take into account the complexity caused by time-zones, or whether your database values are stored as UTC etc..)

Edit: Looking at the rest of your code, you might also be interested in these two questions on how to change the way the value is displayed in the data grid:

How to format TimeSpan in XAML

Why those different string formats on TimeSpan on XAML?

Body:
I have an interface that is feeding me a datetimeupdated variable with the type of DateTime but I need to read it as type TimeSpan. I'm trying to do the conversion and it kind of worked but not really. I followed this post.
Convert DateTime to TimeSpan

Code:

if (e.CmsData != null)
{
    List<NewAgent> newAgentList = new List<NewAgent>();

    Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
    {
        foreach (var item in e.CmsData.Agents)
        {
            NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

            newAgents.AgentName = item.AgName;

            newAgents.AgentExtension = item.Extension;

            newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

            newAgents.AuxReasons = item.AuxReasonDescription;

            newAgents.LoginIdentifier = item.LoginId;

            ConvertedDateTimeUpdated = item.DateTimeUpdated - new DateTime(01/01/2000);
            time = ConvertedDateTimeUpdated;
            agentTime = time -  DateTime.Now.TimeOfDay;

            newAgents.AgentDateTimeStateChange = agentTime;
            newAgentList.Add(newAgents);
        }

        datagrid.ItemsSource = newAgentList;
    }));
}

XAML:

<DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
    <DataGridTextColumn Header="Aux Reason" Binding="{Binding AuxReasons}" />
    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange}" />
</DataGrid.Columns>

AgentClass

class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }

    }

When I print this out to my list I get the below pasted into the fields instead of a format of 00:00:00.

please let me know if this is not enough code to understand what I am trying to accomplish and I'll post all of what I have. Also important to note that item.datetimeupdated is in the format of 00/00/0000 00:00:00.

Body:
I think that what you're trying to accomplish is display the time portion of the DateTime instance; but represented as a TimeSpan.

In which case, this should be all you need.

var timeSpan = item.DateTimeUpdated.TimeOfDay;

If you're trying to display "How long ago from now was this updated?" Then you'll need to do something like..

var timeSpanSince = DateTime.Now - item.DateTimeUpdated;

(These answers do not take into account the complexity caused by time-zones, or whether your database values are stored as UTC etc..)

Edit: Looking at the rest of your code, you might also be interested in these two questions on how to change the way the value is displayed in the data grid:

How to format TimeSpan in XAML

Why those different string formats on TimeSpan on XAML?


问:
I want totally immutable object in TS
I have some big object, like

```<code>const a={
 b:33,
 c:[78, 99],
 d:{e:{f:{g:true, h:{boom:'selecta'}}}};/// well, even deeper than this...
</code>```

And I'd like TS not to allow me to do

```<code>a.d.e.f.h.boom='respek';
</code>```

How can I immutate the object completely? Is it only by creating interface with "readonly" and interfaces for each deeply nested object?

答:
Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Object.freeze might do what you want but at least WebStorm does not warn you when trying to edit the object and Chrome fails silently.

```<code>const obj = { val: 1 };
Object.freeze(obj);
obj.val = 2;

console.log(obj);
-> { val: 1 }
</code>```

Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a TypeError exception

Title: I want totally immutable object in TS

Body:
I have some big object, like

const a={
 b:33,
 c:[78, 99],
 d:{e:{f:{g:true, h:{boom:'selecta'}}}};/// well, even deeper than this...

And I'd like TS not to allow me to do

a.d.e.f.h.boom='respek';

How can I immutate the object completely? Is it only by creating interface with "readonly" and interfaces for each deeply nested object?

Body:
Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Object.freeze might do what you want but at least WebStorm does not warn you when trying to edit the object and Chrome fails silently.

const obj = { val: 1 };
Object.freeze(obj);
obj.val = 2;

console.log(obj);
-> { val: 1 }

Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a TypeError exception


问:
Waterfall or Ribbon plot of stacked data (XRD) with color constant lines and spacing determined by another variable
I'm struggling to make a plot that I find useful with my current set of X-ray diffraction data.  I have multiple x-ray scans that I'd like to place in a 3d arrangement according to a third variable.  [i.e., compare the theta-two-theta (x,y) measured data to a variable in my control-space]

What I'm looking for is either like a waterfall plot or a ribbon plot, but both appear to be limiting.  For the waterfall plot, it appears spacing is determined not by a variable, but by the function, similarly to a ribbon-plot, which takes x,y data only, and uses equal spacing and colors along the colormap.

This is similar to stacking XRD plots, but I figured it would be nice to have the spacing between each plot be directly linked to a testing variable in our lab.

Color I'd like to be constant for each line, determined by the nice color routine linspecer.

Are there any plots that control the third dimension by a variable for spacing of the lines?  I have each line separate in a data struct right now, but can massage the data to be what is needed for suggested solutions.

答:
If you want control of each individual line, the 3-D line plot plot3() might be what you are looking for.

This short example makes use of the peaks data but changes the spacing between the lines.

```<code>[x,y] = meshgrid(-3:.5:3,-3:.1:3);
z = peaks(x,y);

% Change spacing of x
xNew = sign(x).*sqrt(abs(x));

plot3(x,y,z,'b')
figure
plot3(xNew,y,z,'b')
</code>```

This produces the following two figures. The first one shows the original spacing and the second one uses the modified spacing.

If you want individual colors of each line you can loop through them and set them individually as in this answer at matlab central.

Body:
If you want control of each individual line, the 3-D line plot plot3() might be what you are looking for.

This short example makes use of the peaks data but changes the spacing between the lines.

[x,y] = meshgrid(-3:.5:3,-3:.1:3);
z = peaks(x,y);

% Change spacing of x
xNew = sign(x).*sqrt(abs(x));

plot3(x,y,z,'b')
figure
plot3(xNew,y,z,'b')

This produces the following two figures. The first one shows the original spacing and the second one uses the modified spacing.

If you want individual colors of each line you can loop through them and set them individually as in this answer at matlab central.


问:
How do i get rid of '-managedObjectContext' not found in protocol(s)
my app runs on iPhone device and also in simulator. Everythings seems fine, but i see a compiler warning during build. I hate to deliver code thats not completely correct so i need to get rid of this warning. The compiler warning is:

newsReaderController.m:24: warning: '-managedObjectContext' not found in protocol(s)

The Code is:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    //CORE DATA
    if (managedObjectContext == nil) {
    managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];
    }
}
</code>```

The managedObjectContext for CoreData operation is set up in App Delegate. Core Data Framework is importet and the app works like a charm.

any hint for me ? I'm working with objective-C for some weeks now but there seems to be something new to learn every day :)

答:
Since -[UIApplication delegate] returns an object of type id<UIApplicationDelegate>, the compiler is complaining that no -managedObjectContext method exists in that one protocol. It's there, and you know it's there, so you can solve this issue by casting to your delegate's specific type (MyAppDelegate or whatever it may be called), or by casting to id:

```<code> id appDelegate = (id)[[UIApplication sharedApplication] delegate];
 managedObjectContext = [appDelegate managedObjectContext];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
my app runs on iPhone device and also in simulator. Everythings seems fine, but i see a compiler warning during build. I hate to deliver code thats not completely correct so i need to get rid of this warning. The compiler warning is:

newsReaderController.m:24: warning: '-managedObjectContext' not found in protocol(s)

The Code is:

- (void)viewDidLoad {
    [super viewDidLoad];
    //CORE DATA
    if (managedObjectContext == nil) {
    managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];
    }
}

The managedObjectContext for CoreData operation is set up in App Delegate. Core Data Framework is importet and the app works like a charm.

any hint for me ? I'm working with objective-C for some weeks now but there seems to be something new to learn every day :)

Body:
Since -[UIApplication delegate] returns an object of type id<UIApplicationDelegate>, the compiler is complaining that no -managedObjectContext method exists in that one protocol. It's there, and you know it's there, so you can solve this issue by casting to your delegate's specific type (MyAppDelegate or whatever it may be called), or by casting to id:

 id appDelegate = (id)[[UIApplication sharedApplication] delegate];
 managedObjectContext = [appDelegate managedObjectContext];


问:
Make all absolute links relative
I am looking for a regex solution for this problem. It can be a multiple step solution if this makes things easier. Important notice: The test string is just a snippet of a complete HTML DOM and only images should get addressed by this and any other URL should be left alone.

Here's an image:

```<code><img
src="https://www.example.com/de/wp-content/uploads/sites/1/2017/03/image.jpg"
data-srcset="
 https://www.example.com/de/wp-content/uploads/sites/1/2017/03/img1.jpg 507w,
 https://www.example.com/de/wp-content/uploads/sites/1/2017/03/img2.jpg 780w,
 https://www.example.com/de/wp-content/uploads/sites/74/2017/03/img3.jpg 950w"
data-sizes="
 (min-width: 80em) calc(0.5 * (100vw - (100vw- 57em))),
 (min-width: 48em) calc(0.5 * (100vw - 5em)),
 calc(100vw - 1em)"
alt="image" class="lazyload">
</code>```

As a oneliner:

```<code><img src="https://www.example.com/de/wp-content/uploads/sites/1/2017/03/image.jpg" data-srcset="https://www.example.com/de/wp-content/uploads/sites/1/2017/03/img1.jpg 507w, https://www.example.com/de/wp-content/uploads/sites/1/2017/03/img2.jpg 780w, https://www.example.com/de/wp-content/uploads/sites/74/2017/03/img3.jpg 950w" data-sizes="(min-width: 80em) calc(0.5 * (100vw - (100vw- 57em))), (min-width: 48em) calc(0.5 * (100vw - 5em)), calc(100vw - 1em)" alt="image" class="lazyload">
</code>```

The desired result is that need to get rid of protocol, domain, and first directory - that is to say: everything in front of the /wp-content. The language I am doing this in is php.

For the src part I have

```<code> preg_replace("/(<img.*?src=\")(.*?)(\/wp-content.*?\")(.*>)/", '"$1$3$4"', $string);
</code>```

The answer below is correct. Most HTML documents should be able to load. Do yourself a favor and try to be as valid as possible, this is a good thing anyways. If you don't produce the HTML in question yourself, try to process it before you consume it.

For the data-srcset problem just parse that argument separately.

Compare your DOM before and after completely. The @dom->saveHTML() method makes closed tags which do not need to be closed, closed. Like <meta arg="yada"/> turns to <meta arg="yada"> (closing backslash missing). Also see Are (non-void) self-closing tags valid in HTML5?

答:
Don't. Use a parser to analyze the DOM and apply the regex on the DOM elements/attributes directly.

```<code><?php

$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED);

$xpath = new DOMXPath($dom);
$images = $xpath->query("//img[contains(@src, 'wp-content')]");

$regex = '~^.+?(?=/wp-content/)~';
foreach($images as $img) {
    $img->setAttribute('src',
        preg_replace($regex, 'https://anotherdomain.com', $img->getAttribute('src'))
    );
}

echo $dom->saveHTML();
</code>```

It has been answered a dozen times why it is not a good idea to parse HTML with regular expressions, one of the most favourite answers being this:
RegEx match open tags except XHTML self-contained tags.

However, if your HTML is not valid, you could use the following regex (in verbose mode):

```<code>(?:\G(?!\A)|<img)
(?s:.+?\bsrc=['"])\K
https?://.+?(?=/wp-content/)
</code>```

See it working on regex101.com.

Title: Make all absolute links relative

Body:
I am looking for a regex solution for this problem. It can be a multiple step solution if this makes things easier. Important notice: The test string is just a snippet of a complete HTML DOM and only images should get addressed by this and any other URL should be left alone.

Here's an image:

As a oneliner:

The desired result is that need to get rid of protocol, domain, and first directory - that is to say: everything in front of the /wp-content. The language I am doing this in is php.

For the src part I have

 preg_replace("/()/", '"$1$3$4"', $string);

The answer below is correct. Most HTML documents should be able to load. Do yourself a favor and try to be as valid as possible, this is a good thing anyways. If you don't produce the HTML in question yourself, try to process it before you consume it.

For the data-srcset problem just parse that argument separately.

Compare your DOM before and after completely. The @dom->saveHTML() method makes closed tags which do not need to be closed, closed. Like <meta arg="yada"/> turns to <meta arg="yada"> (closing backslash missing). Also see Are (non-void) self-closing tags valid in HTML5?

Body:
Don't. Use a parser to analyze the DOM and apply the regex on the DOM elements/attributes directly.

<?php

$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED);

$xpath = new DOMXPath($dom);
$images = $xpath->query("//img[contains(@src, 'wp-content')]");

$regex = '~^.+?(?=/wp-content/)~';
foreach($images as $img) {
    $img->setAttribute('src',
        preg_replace($regex, 'https://anotherdomain.com', $img->getAttribute('src'))
    );
}

echo $dom->saveHTML();

It has been answered a dozen times why it is not a good idea to parse HTML with regular expressions, one of the most favourite answers being this:
RegEx match open tags except XHTML self-contained tags.

However, if your HTML is not valid, you could use the following regex (in verbose mode):

(?:\G(?!\A)|<img)
(?s:.+?\bsrc=['"])\K
https?://.+?(?=/wp-content/)

See it working on regex101.com.


问:
convert Youtube URL into Embed iframe in codeigniter
```<code>                     <div class="row">
                      <div class="input-field col s12">
                        <input id="p_video" type="url" name="p_video_link" type="url">
                        <label for="p_video">Post Video</label>
                      </div>
                    </div>
</code>```

Am New to codeigniter ...
I have to convert  this url box url to embed ocde to store in database via codeigniter ... How to do that...........Thanks in Advance

答:
Just save the youtube url in database, with out the iframe format but when you retrive the url from database , you save the result in $youtubeurl var and echo in the html, you do something like

```<code><?php

echo '<iframe width="560" height="315" src="'.$youtubeurl.'" frameborder="0" allowfullscreen></iframe>';

?>
</code>```

so it's just concatenate the html with the variable '.$youtubeurl.'

Body:
                        <input id="p_video" type="url" name="p_video_link" type="url">
                        Post Video

Am New to codeigniter ...
I have to convert  this url box url to embed ocde to store in database via codeigniter ... How to do that...........Thanks in Advance

Body:
Just save the youtube url in database, with out the iframe format but when you retrive the url from database , you save the result in $youtubeurl var and echo in the html, you do something like

<?php

echo '<iframe width="560" height="315" src="'.$youtubeurl.'" frameborder="0" allowfullscreen></iframe>';

?>

so it's just concatenate the html with the variable '.$youtubeurl.'


问:
How can I make hidden files display in Eclipse Project explorer when using a RSE linked folder?
So in my project i link a folder with Remote Systems Explorer.  I have some hidden files I need to edit like .htaccess

What I tried

removed .* filter from Project

explorer windows checked "show hidden
files" in RSE properties

Still doesn't display the hidden files for me

Any light to shed ?

答:
easiest way to show hidden files on eclipse (using mac os)
first you need to show hidden options on the system in the first place
follow this post </p>

<p>then all you need to do is to open finder drag the wanted folder into the quick access navigation bar (on the left of the finder window) . </p>

Body:
easiest way to show hidden files on eclipse (using mac os)
first you need to show hidden options on the system in the first place
follow this post

then all you need to do is to open finder drag the wanted folder into the quick access navigation bar (on the left of the finder window) .


问:
How to replace an entire Pandas DataFrame row if all values equal np.NaN
Example Code & Output:

```<code>data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528
</code>```

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

答:
You can find the rows that have NaN for all elements, and replace them with the rows of the other dataframe using:

```<code># find the indices that are all NaN
na_indices = df_country1.index[df_country1.isnull().all(axis=1)]

# replace those indices with the values of the other dataframe
df_country1.loc[na_indices,:] = df_country2.loc[na_indices,:]
</code>```

This assumes that the data frames are the same shape and you want to match on the missing rows.

Body:
Example Code & Output:

data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

Body:
You can find the rows that have NaN for all elements, and replace them with the rows of the other dataframe using:

# find the indices that are all NaN
na_indices = df_country1.index[df_country1.isnull().all(axis=1)]

# replace those indices with the values of the other dataframe
df_country1.loc[na_indices,:] = df_country2.loc[na_indices,:]

This assumes that the data frames are the same shape and you want to match on the missing rows.


问:
How can I combine elements from different arrays in java?
Suppose a={1,2,3} and b={4,5,6} and I want to return an array containing the middle elements of a and b, i.e., {2,5}. I tried to use "merge":

```<code>public int[] middleValueArray(int[] a, int[] b) {
 int[] both=merge(a[1],b[1]);
 return both;
}
</code>```

This does not seem to work. Is there a simple way to approach this? Thanks!

答:
Use this:-   </p>

```<code>public int[] middleValueArray(int[] a, int[] b) {
     int[] both={a[1],b[1]};
     return both;
    }
</code>```

Body:
Suppose a={1,2,3} and b={4,5,6} and I want to return an array containing the middle elements of a and b, i.e., {2,5}. I tried to use "merge":

public int[] middleValueArray(int[] a, int[] b) {
 int[] both=merge(a[1],b[1]);
 return both;
}

This does not seem to work. Is there a simple way to approach this? Thanks!

Body:
Use this:-

public int[] middleValueArray(int[] a, int[] b) {
     int[] both={a[1],b[1]};
     return both;
    }


问:
Using Application.Run in Excel VBA when workbook name contains spaces
```<code>Application.Run "MyWorkBook.xls!Macro1"
</code>```

will work (run the macro called Macro1 in the MyWorkBook.xls file).

```<code>Application.Run "My Work Book.xls!Macro1"
</code>```

will not work (if the workbook name contains spaces, Excel says "the macro cannot be found").

I just spent hours figuring out that it's the spaces causing this problem...

Is there a way around this without renaming the file?

答:
Replace each of the spaces with %20

```<code>Application.Run "My%20Work%20Book.xls!Macro1"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Application.Run "MyWorkBook.xls!Macro1"

will work (run the macro called Macro1 in the MyWorkBook.xls file).

Application.Run "My Work Book.xls!Macro1"

will not work (if the workbook name contains spaces, Excel says "the macro cannot be found").

I just spent hours figuring out that it's the spaces causing this problem...

Is there a way around this without renaming the file?

Body:
Replace each of the spaces with %20

Application.Run "My%20Work%20Book.xls!Macro1"


问:
How to add class on hover using jquery
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

```<code><div class="flItems"><a class="category_filter" data-value="Fitted bed Sheet " href="http://192.168.1.156/eles/bed-linen/fitted-bed-sheet"> Fitted bed Sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Flat bed sheet " href="http://192.168.1.156/eles/bed-linen/flat-bed-sheet"> Flat bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Full bed sheets  " href="http://192.168.1.156/eles/bed-linen/full-bed-sheets"> Full bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twin bed sheet " href="http://192.168.1.156/eles/bed-linen/twin-bed-sheet"> Twin bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twinxl bed sheets  " href="http://192.168.1.156/eles/bed-linen/twinxl-bed-sheets"> Twinxl bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Queen bed sheet " href="http://192.168.1.156/eles/bed-linen/queen-bed-sheet"> Queen bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King bed sheets " href="http://192.168.1.156/eles/bed-linen/king-bed-sheets"> King bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Cal king bed sheets " href="http://192.168.1.156/eles/bed-linen/cal-king-bed-sheets"> Cal king bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Duvet covers " href="http://192.168.1.156/eles/bed-linen/duvet-covers"> Duvet covers  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Bed skirts " href="http://192.168.1.156/eles/bed-linen/bed-skirts"> Bed skirts  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Standard Pillow cases " href="http://192.168.1.156/eles/bed-linen/standard-pillow-cases"> Standard Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King Pillow cases " href="http://192.168.1.156/eles/bed-linen/king-pillow-cases"> King Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Pillow shells " href="http://192.168.1.156/eles/bed-linen/pillow-shells"> Pillow shells  </a> </div>
</code>```

Jquery Code,

```<code>$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});
</code>```

答:
```<code>$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            $(".category_filter[data-value='"+clickedvalue+"']").addClass("active");
             // $(this).addClass('active');
        }
});
</code>```

Got it working!!! Thx all for your inputs...

Title: How to add class on hover using jquery

Body:
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells

Jquery Code,

$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});

Body:
$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            $(".category_filter[data-value='"+clickedvalue+"']").addClass("active");
             // $(this).addClass('active');
        }
});

Got it working!!! Thx all for your inputs...


答:
More general solution will be:</p>

```<code>public int[] middleValueArray(int[] a, int[] b) {
    return new int[]{a[a.length/2], b[b.length/2]};
}
</code>```

Title: How can I combine elements from different arrays in java?

Body:
More general solution will be:

public int[] middleValueArray(int[] a, int[] b) {
    return new int[]{a[a.length/2], b[b.length/2]};
}


问:
Ajax not triggering for Partial view
I am adding Partial view in to my main view , the partial view code snippet is:

```<code><li class="item-@j deeper parent active">
        <a class="" href="">
            <span data-toggle="collapse" data-parent="#menu-group-1" href="#sub-item-@j" class="sign"><i class="icon-plus icon-white"></i></span>
            <span class="lbl">Brands</span>
        </a>
        <ul class="children nav-child unstyled small collapse" id="sub-item-@j">
            @foreach (var brand in Model.BrandList)
            {
                <li class="item-@j deeper parent active">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" value="@brand._id">
                            @*<a class="" href="@Url.Action("FilterData", "ShopWindow", new {shopKey=house._id,houseKey=house._id,houseName = house.House})">*@
                            <span class="lbl">@brand.Brand</span>
                            @*</a>*@
                        </label>
                    </div>
                </li>
                j++;
            }
        </ul>
    </li>
</code>```

in my main view I have a script to get all the check boxes that user have selected, the script snippet :

```<code><script type="text/javascript">
      var selectedBrand=[];

    $("input[type='checkbox']").change(function () {
          $('#brand input:checked').each(function () {
            selectedBrand.push($(this).attr('value'));
            alert("Test");
        })
        sendAjaxRequest();

    });
</code>```

When I select any check box from the partial view the script's change function is not getting triggered. This change function triggers if I check any checkbox in the main page but not for checkboxes belongs to partial view .

Any idea?

Thanks

答:
I found the solution :

changed

```<code>$("input[type='checkbox']").change(function () {
</code>```

to

```<code> $(document).on('change', '.checkbox', function() {
</code>```

Title: Ajax not triggering for Partial view

Body:
I am adding Partial view in to my main view , the partial view code snippet is:

            Brands

            @foreach (var brand in Model.BrandList)
            {

                            <input type="checkbox" value="@brand._id">
                            @**@
                            @brand.Brand
                            @**@

                j++;
            }

in my main view I have a script to get all the check boxes that user have selected, the script snippet :

Body:
I found the solution :

changed

$("input[type='checkbox']").change(function () {

to

 $(document).on('change', '.checkbox', function() {


问:
format DD/MM/YYYY input react as user types
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

```<code>class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}
</code>```

答:
You could use the MaskInput:
MaskedInput

var CustomInput = React.createClass({
  render() {
    return <MaskedInput
      mask="11-11-1111"
      placeholder="MM-DD-YYYY"
      size="11"
      {...this.props}
      formatCharacters={{
        'W': {
          validate(char) { return /\w/.test(char ) },
          transform(char) { return char.toUpperCase() }
        }
      }
    }/>
  }
})

class ShoppingList extends React.Component {
  render() {
    return (

        Card Number:
        <CustomInput />

    );
  }
}
ReactDOM.render(
  <ShoppingList />,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-maskedinput@3.3.4/umd/react-maskedinput.js"></script>
<div id="root"></div></code>```

Body:
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}

Body:
You could use the MaskInput:
MaskedInput

var CustomInput = React.createClass({
  render() {
    return <MaskedInput
      mask="11-11-1111"
      placeholder="MM-DD-YYYY"
      size="11"
      {...this.props}
      formatCharacters={{
        'W': {
          validate(char) { return /\w/.test(char ) },
          transform(char) { return char.toUpperCase() }
        }
      }
    }/>
  }
})

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="form-field">
        <label htmlFor="card">Card Number:</label>
        <CustomInput />
      </div>
    );
  }
}
ReactDOM.render(
  <ShoppingList />,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-maskedinput@3.3.4/umd/react-maskedinput.js"></script>
<div id="root"></div>


问:
Why isn't it possible to use "await" in f-strings?
Why isn't it possible to use "await" in f-strings? Is there any way to coerce f-strings into evaluating the format expressions in the context of a coroutine function?</p>

```<code>$ python3
Python 3.6.0 (default, Mar  4 2017, 12:32:37)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> async def a(): return 1
...
>>> async def b(): return 'The return value of await a() is {}.'.format(await a())
...
>>> async def c(): return f'The return value of await a() is {await a()}'
...
  File "<fstring>", line 1
    (await a())
           ^
SyntaxError: invalid syntax
</code>```

答:
As of Python 3.6, this is not possible. It will be possible in 3.7 according to the messages on Issue 28942 -- await expressions in f-strings on the Python bug tracker.

As for the reason, the author of the PEP that introduced async/await expressions, Yury Selivanov, had this to say:

I suspect the reason is that async/await aren't proper keywords in
  3.5/3.6, and the hacks we have in tokenizer to recognize them aren't working in f-strings.

I'll assign this issue to myself to make sure it's resolved in 3.7
  once we make async/await keywords.

and indeed, the tokenizer does seem to treat these specially.

You were right to be puzzled by this as formatted strings are documented as supporting all valid Python expressions (with the appropriate limitations those expressions entail i.e await in an async def function).

I don't believe there's any way to circumvent this at the moment. You'll need to stick with the .format route until the issue is resolved.

Body:
Why isn't it possible to use "await" in f-strings? Is there any way to coerce f-strings into evaluating the format expressions in the context of a coroutine function?

$ python3
Python 3.6.0 (default, Mar  4 2017, 12:32:37)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> async def a(): return 1
...
>>> async def b(): return 'The return value of await a() is {}.'.format(await a())
...
>>> async def c(): return f'The return value of await a() is {await a()}'
...
  File "<fstring>", line 1
    (await a())
           ^
SyntaxError: invalid syntax


问:
How to Append Doc files using Byte Array
I am trying to append the multiple files into single file using bytes array but when i try to append the file it converts only single file which is last one. i use below code:

```<code>            byte[] outputBytes = new byte[0];
            byte[] temp1 = System.IO.File.ReadAllBytes(@"D:\2.doc");
            byte[] temp2 = System.IO.File.ReadAllBytes(@"D:\3.doc");

            outputBytes = new byte[temp1.Length + temp2.Length];
            Buffer.BlockCopy(temp1,0,outputBytes,0,temp1.Length * sizeof(byte));
            Buffer.BlockCopy(temp2,0,outputBytes,0,temp2.Length  * sizeof(byte));
            System.IO.File.WriteAllBytes(@"D:\myOutPut.doc",outputBytes);
</code>```

i am creating one output file in which all files content is display.

Thank You.

答:
You need to set the dstOffset with the second BlockCopy

```<code>Buffer.BlockCopy(temp1, 0, outputBytes, 0, temp1.Length * sizeof(byte));
Buffer.BlockCopy(temp2, 0, outputBytes, temp1.Length, temp2.Length * sizeof(byte));
</code>```

But I think you cannot concat doc files with this.

Body:
I am trying to append the multiple files into single file using bytes array but when i try to append the file it converts only single file which is last one. i use below code:

            byte[] outputBytes = new byte[0];
            byte[] temp1 = System.IO.File.ReadAllBytes(@"D:\2.doc");
            byte[] temp2 = System.IO.File.ReadAllBytes(@"D:\3.doc");

            outputBytes = new byte[temp1.Length + temp2.Length];
            Buffer.BlockCopy(temp1,0,outputBytes,0,temp1.Length * sizeof(byte));
            Buffer.BlockCopy(temp2,0,outputBytes,0,temp2.Length  * sizeof(byte));
            System.IO.File.WriteAllBytes(@"D:\myOutPut.doc",outputBytes);

i am creating one output file in which all files content is display.

Thank You.

Body:
You need to set the dstOffset with the second BlockCopy

Buffer.BlockCopy(temp1, 0, outputBytes, 0, temp1.Length * sizeof(byte));
Buffer.BlockCopy(temp2, 0, outputBytes, temp1.Length, temp2.Length * sizeof(byte));

But I think you cannot concat doc files with this.


问:
help on mysql query JOIN, ORDER BY and randomize
i am joining 2 tables using this query

```<code>SELECT DISTINCT (member.id), member_type FROM member
LEFT JOIN member_gallery
ON member.id = member_gallery.member_id
WHERE member.front = 1
ORDER BY member.member_type ASC
</code>```

suppose that i have 4 member types

20 members for type no.1

20 members for type no.2

20 members for type no.3

20 members for type no.4

and i am displaying this on my web as a 6x5 image grid, is it possible for me to randomize the fetch data, while maintaining the ORDER BY member.member_type ASC, like using ORDER BY RAND() ?

thanks

答:
Use</p>

```<code>ORDER BY member.member_type ASC, RAND()
</code>```

Body:
i am joining 2 tables using this query

SELECT DISTINCT (member.id), member_type FROM member
LEFT JOIN member_gallery
ON member.id = member_gallery.member_id
WHERE member.front = 1
ORDER BY member.member_type ASC

suppose that i have 4 member types

20 members for type no.1

20 members for type no.2

20 members for type no.3

20 members for type no.4

and i am displaying this on my web as a 6x5 image grid, is it possible for me to randomize the fetch data, while maintaining the ORDER BY member.member_type ASC, like using ORDER BY RAND() ?

thanks

Body:
Use

ORDER BY member.member_type ASC, RAND()


问:
DAX Need Power Pivot Measure to be SUM of ALL Columns in Each Column. How to ignore column context
I have a Pivot Table with Salespeople as columns. I have income measures that correctly show (in the rows) the income each of them produced. However, I would like to show everyone's income in each column on some of the measures.

The reason is I want them to be paid on some income items (row measures) on the total of all salespeople not on their individual production.

Is there a way to make a measure ignore the column context?

答:
DAX ALL

Try to use ALL function and give your column as a parameter.

It will clear currently applied filters.


问:
Angular.js and Node.js get a GET instead of a POST
I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.

HTML

```<code><form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome" name="nome"><br>
  cognome:<input type="text" name="cognome"><br>
  ragioneSociale:<input type="text" name="regioneSociale"><br>
  partitaIva:<input type="text" name="partitaIva"><br>
<input type="submit" value="Submit" ng-click="send()">
</form>
</code>```

angular

this is my angular function:

```<code><script>
var fmApp = angualr.module('formApp', []);
fmApp.controller('formCtrl',  function($scope){
  $scope.send = function($http){
    var data = $.params(){
      soggetto: JSON.stringify({
      nome: $scope.nome,
      cognome: $scope.cognome,
      regioneSociale: $scope.regioneSociale,
      partitaIva: $scope.partitaIva
      });
      console.log('ok');
      $http({
        method: "POST",
        url: "/ins/sogg",
        data:'data',
        dataType: 'json'
      }).then(function successCallback(response) {
          console.log("sent")
        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
        });
      // $http.post('/inserimento/soggetto', data).success function(data, status) {
      //   console.log('status');

      })
    };
  };
});
</code>```

答:
Your form is submitted without ever touching the $http call, as you don't prevent defaults. Default action of a submit button is to submit the form.

Change

```<code><input type="submit" value="Submit" ng-click="send()">
</code>```

to

```<code><input type="submit" value="Submit" ng-click="send($event)">
</code>```

and

```<code>fmApp.controller('formCtrl',  function($scope){
  $scope.send = function($http){
</code>```

to

```<code>fmApp.controller('formCtrl',  function($scope, $http){
  $scope.send = function(e){
    e.preventDefault();
</code>```

Body:
I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.

HTML

<form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome" name="nome">

  cognome:<input type="text" name="cognome">

  ragioneSociale:<input type="text" name="regioneSociale">

  partitaIva:<input type="text" name="partitaIva">

<input type="submit" value="Submit" ng-click="send()">
</form>

angular

this is my angular function:

Body:
Your form is submitted without ever touching the $http call, as you don't prevent defaults. Default action of a submit button is to submit the form.

Change

<input type="submit" value="Submit" ng-click="send()">

to

<input type="submit" value="Submit" ng-click="send($event)">

and

fmApp.controller('formCtrl',  function($scope){
  $scope.send = function($http){

to

fmApp.controller('formCtrl',  function($scope, $http){
  $scope.send = function(e){
    e.preventDefault();


问:
selecting a set of objects based on index linq
Is there any way to select, from an array of for example 2000 elements, all the elements between the 100th(included) and the 200th(excluded) element without creating your own row index?</p>

答:
```<code>int[] myArray = Enumerable.Range(0, 2000).ToArray();
myArray = myArray.Where((source, index) => index >= 100 && index <= 200).ToArray();
</code>```

you can see the the full csharppad here http://csharppad.com/gist/5cfc902bbe4e5e8b4a3d85826d64170f

Body:
int[] myArray = Enumerable.Range(0, 2000).ToArray();
myArray = myArray.Where((source, index) => index >= 100 && index <= 200).ToArray();

you can see the the full csharppad here http://csharppad.com/gist/5cfc902bbe4e5e8b4a3d85826d64170f


问:
FIPS Capable OpenSSL cross-compiled: incore fingerprint issue
I'm having an issue trying to use the OpenSSL shared library (libcrypto) compiled to be FIPS capable on a MIPS device.

I cross-compiled the FIPS Object Module and then the OpenSSL library in the following way (summarizing):

```<code>export FIPS_SIG=<my_path>/incore
./config fips --with-fipsdir=<my_path>/fips-2.0
make depend
make
make install
</code>```

I did all the needed steps, so I'm able to compile and install the library.

The issue appears when I try to run the FIPS_mod_set(1) API from an application linking the OpenSSL library.

The FIPS mode initialization fails receiving this error:

```<code>2010346568:error:2D06B06F:lib(45):func(107):reason(111):NA:0:
</code>```

Debugging the FIPS code, I found that the issue is inside the FIPS_check_incore_fingerprint(void) function:

the check memcmp(FIPS_signature,sig,sizeof(FIPS_signature)) fails.

Going deeper in the debug I discovered that the FIPS_signature value remains the default one, so I have the doubt that the incore script, called by the fipsld utility, is not embedding properly the fingerprint inside the OpenSSL shared object.

How can I check if the incore script embedded the fingerprint inside the shared object?

How can I print the expected fingerprint?

Do I need to adapt the incore script? (I suppose it's not allowed)

Do you have any suggestion?

Thanks a lot!

P.S.: I'm cross-compiling using an x86 Linux machine.

答:
I found the issue! I'll try to explain the whole debugging process and the solution.

INTRODUCTION:

When OpenSSL is configured to be FIPS capable, during the compilation the Makefile calls a utility, fipsld, which both performs the check of the FIPS
Object Module and generates the new HMAC-SHA-1 digest for the application executable (as explained in the official OpenSSL user guide   https://www.openssl.org/docs/fips/UserGuide-2.0.pdf)

The fipsld command requires that the CC and FIPSLD_CC environment variables be set,
with the latter taking precedence.

In the Makefile you will find something like this:

```<code>libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT)
    @if [ "$(SHLIB_TARGET)" != "" ]; then \
        if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \
            FIPSLD_LIBCRYPTO=libcrypto.a ; \
            FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \
            export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \
        fi; \
        $(MAKE) -e SHLIBDIRS=crypto  CC="$${CC:-$(CC)}" build-shared && \
        (touch -c fips_premain_dso$(EXE_EXT) || :); \
    else \
        echo "There's no support for shared libraries on this platform" >&2; \
        exit 1; \
    fi
</code>```

Then, the fipsld utility invokes a shell script, incore,  used to embed the FIPS Object Module's expected fingerprint in the OpenSSL shared object. It's important to specify the incore path via FIPS_SIG env variable, e.g.:

```<code>export FIPS_SIG=$PWD/opensslfips2.0/util/incore
</code>```

DEBUGGING:

Debugging the incore script, I could see that the script tried to embed the signature into the shared object at the offset 0x001EE6B0 while the FIPS_signature symbol inside the shared object was located at a different offset, to be more specific at 0x001F0630:

```<code>objdump -t libcrypto.so.1.0.0 | grep FIPS_signature
001f0630 g     O .data  00000014              FIPS_signature

readelf -a libcrypto.so.1.0.0 | grep FIPS_signature
   870: 001f0630    20 OBJECT  GLOBAL DEFAULT   18 FIPS_signature
  3925: 001f0630    20 OBJECT  GLOBAL DEFAULT   18 FIPS_signature
</code>```

Furthermore dumping the shared object I wasn't able to find the generated signature at the offset 0x001EE6B0 so I reached the conclusion that the shared object was edited after the signature embedding procedure by some other process.

SOLUTION:

I was using a package Makefile for the OpenSSL packet formatted in the following way:

```<code>$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    all
$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    build-shared
rm $(PKG_BUILD_DIR)/libssl.so.*.*.*
$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    do_linux-shared
$(MAKE) -C $(PKG_BUILD_DIR)
    <options>
    install
</code>```

As suspected, make build-shared and make do_linux-shared commands were responsible for changing the shared object in the wrong way.

NOTICE that make build-shared was called without using the proper environment variables.

I changed the package Makefile:

```<code>$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    all
$(MAKE) -C $(PKG_BUILD_DIR)
    <options>
    install
</code>```

Now the FIPS_check_incore_fingerprint(void) function returns with success and everything is working fine!

NOTE:

The following guide for Android devices has been very useful to find the proper solution.
https://wiki.openssl.org/index.php/FIPS_Library_and_Android

Body:
I'm having an issue trying to use the OpenSSL shared library (libcrypto) compiled to be FIPS capable on a MIPS device.

I cross-compiled the FIPS Object Module and then the OpenSSL library in the following way (summarizing):

export FIPS_SIG=<my_path>/incore
./config fips --with-fipsdir=<my_path>/fips-2.0
make depend
make
make install

I did all the needed steps, so I'm able to compile and install the library.

The issue appears when I try to run the FIPS_mod_set(1) API from an application linking the OpenSSL library.

The FIPS mode initialization fails receiving this error:

2010346568:error:2D06B06F:lib(45):func(107):reason(111):NA:0:

Debugging the FIPS code, I found that the issue is inside the FIPS_check_incore_fingerprint(void) function:

the check memcmp(FIPS_signature,sig,sizeof(FIPS_signature)) fails.

Going deeper in the debug I discovered that the FIPS_signature value remains the default one, so I have the doubt that the incore script, called by the fipsld utility, is not embedding properly the fingerprint inside the OpenSSL shared object.

How can I check if the incore script embedded the fingerprint inside the shared object?

How can I print the expected fingerprint?

Do I need to adapt the incore script? (I suppose it's not allowed)

Do you have any suggestion?

Thanks a lot!

P.S.: I'm cross-compiling using an x86 Linux machine.

Body:
I found the issue! I'll try to explain the whole debugging process and the solution.

INTRODUCTION:

When OpenSSL is configured to be FIPS capable, during the compilation the Makefile calls a utility, fipsld, which both performs the check of the FIPS
Object Module and generates the new HMAC-SHA-1 digest for the application executable (as explained in the official OpenSSL user guide   https://www.openssl.org/docs/fips/UserGuide-2.0.pdf)

The fipsld command requires that the CC and FIPSLD_CC environment variables be set,
with the latter taking precedence.

In the Makefile you will find something like this:

libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT)
    @if [ "$(SHLIB_TARGET)" != "" ]; then \
        if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \
            FIPSLD_LIBCRYPTO=libcrypto.a ; \
            FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \
            export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \
        fi; \
        $(MAKE) -e SHLIBDIRS=crypto  CC="$${CC:-$(CC)}" build-shared && \
        (touch -c fips_premain_dso$(EXE_EXT) || :); \
    else \
        echo "There's no support for shared libraries on this platform" >&2; \
        exit 1; \
    fi

Then, the fipsld utility invokes a shell script, incore,  used to embed the FIPS Object Module's expected fingerprint in the OpenSSL shared object. It's important to specify the incore path via FIPS_SIG env variable, e.g.:

export FIPS_SIG=$PWD/opensslfips2.0/util/incore

DEBUGGING:

Debugging the incore script, I could see that the script tried to embed the signature into the shared object at the offset 0x001EE6B0 while the FIPS_signature symbol inside the shared object was located at a different offset, to be more specific at 0x001F0630:

objdump -t libcrypto.so.1.0.0 | grep FIPS_signature
001f0630 g     O .data  00000014              FIPS_signature

readelf -a libcrypto.so.1.0.0 | grep FIPS_signature
   870: 001f0630    20 OBJECT  GLOBAL DEFAULT   18 FIPS_signature
  3925: 001f0630    20 OBJECT  GLOBAL DEFAULT   18 FIPS_signature

Furthermore dumping the shared object I wasn't able to find the generated signature at the offset 0x001EE6B0 so I reached the conclusion that the shared object was edited after the signature embedding procedure by some other process.

SOLUTION:

I was using a package Makefile for the OpenSSL packet formatted in the following way:

$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    all
$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    build-shared
rm $(PKG_BUILD_DIR)/libssl.so.*.*.*
$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    do_linux-shared
$(MAKE) -C $(PKG_BUILD_DIR)
    <options>
    install

As suspected, make build-shared and make do_linux-shared commands were responsible for changing the shared object in the wrong way.

NOTICE that make build-shared was called without using the proper environment variables.

I changed the package Makefile:

$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR)
    <options>
    all
$(MAKE) -C $(PKG_BUILD_DIR)
    <options>
    install

Now the FIPS_check_incore_fingerprint(void) function returns with success and everything is working fine!

NOTE:

The following guide for Android devices has been very useful to find the proper solution.
https://wiki.openssl.org/index.php/FIPS_Library_and_Android