问:
How to remove keys from a params array of hashes
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

```<code><ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>
</code>```

答:
Try to use each_with_object, which is handy for building hashes or reducing collections down to one object:

```<code>params = {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20",
"sales_attributes"=> [{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first", "code"=>"G32" },
{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33" },
{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34" }
  ]}
</code>```

Solution:

```<code>result = {}
params.each_with_object(result) do |(key, values)|
  if key == 'sales_attributes'
    result[key] =  values.map { |sales_attribute| sales_attribute.except('name', 'code') }
  else
    result[key] = values
  end
end
</code>```

Resulting hash output:

```<code>=> {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1",
"billpayer_id"=>"20", "sales_attributes"=>[{"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}, {"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}, {"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}]}
</code>```

Body:
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

<ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>

Body:
Try to use each_with_object, which is handy for building hashes or reducing collections down to one object:

params = {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20",
"sales_attributes"=> [{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first", "code"=>"G32" },
{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33" },
{ "sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34" }
  ]}

Solution:

result = {}
params.each_with_object(result) do |(key, values)|
  if key == 'sales_attributes'
    result[key] =  values.map { |sales_attribute| sales_attribute.except('name', 'code') }
  else
    result[key] = values
  end
end

Resulting hash output:

=> {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1",
"billpayer_id"=>"20", "sales_attributes"=>[{"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}, {"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}, {"sellable_type"=>"Product", "sellable_id"=>"-2",
"discount"=>"0", "price"=>"0"}]}


来源: stackexchange

问:
What does -> mean in Python function definitions?
I've recently noticed something interesting when looking at Python 3.3 grammar specification:

```<code>funcdef: 'def' NAME parameters ['->' test] ':' suite
</code>```

The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:

```<code>def f(x) -> 123:
    return x
</code>```

I thought that this might be some kind of a precondition syntax, but:

I cannot test x here, as it is still undefined,

No matter what I put after the arrow (e.g. 2 < 1), it doesn't affect the function behavior.

Could anyone familiar with this syntax style explain it?

答:
```<code>def f(x) -> 123:
    return x
</code>```

My summary:

Simply -> is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107

This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.

You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.

You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.

ContentLicense: CC BY-SA 4.0

Body:
I've recently noticed something interesting when looking at Python 3.3 grammar specification:

funcdef: 'def' NAME parameters ['->' test] ':' suite

The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:

def f(x) -> 123:
    return x

I thought that this might be some kind of a precondition syntax, but:

I cannot test x here, as it is still undefined,

No matter what I put after the arrow (e.g. 2 < 1), it doesn't affect the function behavior.

Could anyone familiar with this syntax style explain it?

Body:
def f(x) -> 123:
    return x

My summary:

Simply -> is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107

This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.

You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.

You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.


问:
Is there a way to use window.hasOwnProperty() in Internet Explorer?
I have a method, that perfectly works in Firefox, with which I can determine the name of an instance of a particular javascript object (please don't ask why I need it...).
Fr example:

```<code>var temp = new String("hello!");
var theName = getVarName(temp); //returns "temp"
</code>```

This method uses "window.hasOwnProperty()" which doen't work in Internet Explorer: any suggestions?

答:
I have a method, that perfectly works in Firefox, with which I can determine the name of an instance of a particular javascript object

I don't think you do, because that's not possible in JavaScript. JS is a call-by-value language; when you write:

```<code>var temp= 'hello';
getVarName(temp);
</code>```

that's exactly the same as saying:

```<code>getVarName('hello');
</code>```

At which point the reference to ‘temp’ as a variable is lost. What I'm guessing your getVarName function does is basically this:

```<code>function getVarName(value) {
    for (var name in window) {
        if (window[name]===value)
            return name;
    }
}
</code>```

This will work on IE and other browsers without Object.hasOwnProperty(); it will simply return the name of any global variable that matches the argument. The hasOwnProperty() call can be added to this function to refine it a little by only allowing direct properties of window (which act as global variables, including the ones you set explicitly), and not of any of its prototypes. I'm guessing that's what your version of the function is doing, but in practice it has very little effect since almost nothing inherits into ‘window’ by prototype.

You're confusing things a little bit by boxing your 'hello' in an explicit String object (which is very unusual and rarely a good idea), which makes it possible to have two different 'hello' objects that are disinguishable using the === identity comparator, so this will work:

```<code>var a= new String('hello!');
var b= new String('hello!');
getVarName(a); // 'a'
getVarName(b); // 'b' - distinguishable object from a
</code>```

But that still doesn't stop you from doing:

```<code>var a= new String('hello!');
var b= a;
getVarName(a); // 'a' or 'b', depending on implementation
getVarName(b); // the same 'a' or 'b' as in the previous call
</code>```

So, whilst you can fairly harmlessly lose the hasOwnProperty() call as above, what you're doing can't really work properly and you should probably look at a better way of achieving whatever it is you're up to.

OwnerDisplayName: Trigger

ContentLicense: CC BY-SA 2.5

Body:
I have a method, that perfectly works in Firefox, with which I can determine the name of an instance of a particular javascript object (please don't ask why I need it...).
Fr example:

var temp = new String("hello!");
var theName = getVarName(temp); //returns "temp"

This method uses "window.hasOwnProperty()" which doen't work in Internet Explorer: any suggestions?

Body:
I have a method, that perfectly works in Firefox, with which I can determine the name of an instance of a particular javascript object

I don't think you do, because that's not possible in JavaScript. JS is a call-by-value language; when you write:

var temp= 'hello';
getVarName(temp);

that's exactly the same as saying:

getVarName('hello');

At which point the reference to ‘temp’ as a variable is lost. What I'm guessing your getVarName function does is basically this:

function getVarName(value) {
    for (var name in window) {
        if (window[name]===value)
            return name;
    }
}

This will work on IE and other browsers without Object.hasOwnProperty(); it will simply return the name of any global variable that matches the argument. The hasOwnProperty() call can be added to this function to refine it a little by only allowing direct properties of window (which act as global variables, including the ones you set explicitly), and not of any of its prototypes. I'm guessing that's what your version of the function is doing, but in practice it has very little effect since almost nothing inherits into ‘window’ by prototype.

You're confusing things a little bit by boxing your 'hello' in an explicit String object (which is very unusual and rarely a good idea), which makes it possible to have two different 'hello' objects that are disinguishable using the === identity comparator, so this will work:

var a= new String('hello!');
var b= new String('hello!');
getVarName(a); // 'a'
getVarName(b); // 'b' - distinguishable object from a

But that still doesn't stop you from doing:

var a= new String('hello!');
var b= a;
getVarName(a); // 'a' or 'b', depending on implementation
getVarName(b); // the same 'a' or 'b' as in the previous call

So, whilst you can fairly harmlessly lose the hasOwnProperty() call as above, what you're doing can't really work properly and you should probably look at a better way of achieving whatever it is you're up to.

OwnerDisplayName: bobince


问:
How can I pass POST parameters in a URL?
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like >, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like href="https://stackoverflow.com/questions/6210900/how-to-pass-post-parameters-in-a-url#comment7231173_6210900">Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

答:
You could use a form styled as a link. No JavaScript is required:

```<code><form action="/do/stuff.php" method="post">
    <input type="hidden" name="user_id" value="123" />
    <button>Go to user 123</button>
</form>
</code>```

CSS:

```<code>button {
    border: 0;
    padding: 0;
    display: inline;
    background: none;
    text-decoration: underline;
    color: blue;
}
button:hover {
    cursor: pointer;
}
</code>```

See: http://jsfiddle.net/SkQRN/

Body:
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like <a href="process_user.php?user=<user>>, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

Body:
You could use a form styled as a link. No JavaScript is required:

<form action="/do/stuff.php" method="post">
    <input type="hidden" name="user_id" value="123" />
    <button>Go to user 123</button>
</form>

CSS:

button {
    border: 0;
    padding: 0;
    display: inline;
    background: none;
    text-decoration: underline;
    color: blue;
}
button:hover {
    cursor: pointer;
}

See: http://jsfiddle.net/SkQRN/


问:
Can't access property from object in Javascript
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

```<code>{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}
</code>```

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

```<code>category.questions[0].toJSON().questionsCount
</code>```

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

```<code>exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}
</code>```

I loop through the data.rows to get each category object.

The console.log outputs are:

```<code>------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4
</code>```

答: try to do so category.data[0].questions.questionCount

Body:
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

category.questions[0].toJSON().questionsCount

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}

I loop through the data.rows to get each category object.

The console.log outputs are:

------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4


问:
How to remove or disable add -row and delete-row action button from yupgrid?
I am using yup grid for client side data entry. It is has actions column (containing add-row and delete-row buttons) by default. My requirement is to show add-row and delete-row action buttons to specific users only. For unauthorized users I do not even want actions column. I searched a lot in documentation here, but can not find any solution. Please help me on this.</p>

```<code>var data = [];
var ddlData = [{    "ratingID": "1","rating": "1"}, {"ratingID": "2","rating": "2"}, {"ratingID": "3","rating": "3"}];
var gridObject = [];
var options = {
    tableID: "appList",
    debugLog: false,
    singleClickEdit: true,
    allowEmptyRows: false,
    autoStyle: true,
    onRowChange: function (e) {
        //save data
        $.ajax({
            type: "POST",
            url: "url",
            data: {
                data: JSON.stringify(e.yupObj.data[e.dataRowIndex]),
                isNew: e.yupObj.data[e.dataRowIndex].isNew()
            },
            success: function (data) {

            }
        });
    },
    columns: [{
            headerText: 'App',
            columnName: "appName",
            dataType: "any",
            dataValueMember: 'appName',
            dataTextMember: 'appName',
            hidden: false
        },
        {
            headerText: 'Type',
            columnName: "rating",
            dataType: "any",
            dataValueMember: 'ratingID',
            dataTextMember: 'rating',
            hidden: false,
            inputControl: {
                controlType: 'select',
                dataTextMember: 'rating',
                dataValueMember: 'ratingID'
            }
        },
        {
            headerText: 'App ID',
            columnName: "appID",
            dataType: "any",
            dataValueMember: 'appID',
            dataTextMember: 'appID',
            hidden: true
        },
        {
            headerText: 'Category',
            columnName: "categoryID",
            dataType: "any",
            dataValueMember: 'categoryID',
            dataTextMember: 'categoryID',
            hidden: true
        }
    ]
}
$(document).ready(function () {
    gridObject = yupGrid(options);
    options.columns[1].dataSource = ddlData;
    options.columns[1].bindData();;
    gridObject.bindData(data);
});
</code>```

答:
Use following code in onBindDataComplete event. This event is triggered when bindData finishes loading data.

```<code>yupObj.onBindDataComplete = function(){
   $('#appList tr td .grid-row-icon-a[id*="addRow_"]').remove();
};
</code>```

Similarly you can remove delete button also.

Alternately you can use onBeforeRowDelete and onRowInsert events to restrict addition or deletion of rows.

Body:
I am using yup grid for client side data entry. It is has actions column (containing add-row and delete-row buttons) by default. My requirement is to show add-row and delete-row action buttons to specific users only. For unauthorized users I do not even want actions column. I searched a lot in documentation here, but can not find any solution. Please help me on this.

var data = [];
var ddlData = [{    "ratingID": "1","rating": "1"}, {"ratingID": "2","rating": "2"}, {"ratingID": "3","rating": "3"}];
var gridObject = [];
var options = {
    tableID: "appList",
    debugLog: false,
    singleClickEdit: true,
    allowEmptyRows: false,
    autoStyle: true,
    onRowChange: function (e) {
        //save data
        $.ajax({
            type: "POST",
            url: "url",
            data: {
                data: JSON.stringify(e.yupObj.data[e.dataRowIndex]),
                isNew: e.yupObj.data[e.dataRowIndex].isNew()
            },
            success: function (data) {

            }
        });
    },
    columns: [{
            headerText: 'App',
            columnName: "appName",
            dataType: "any",
            dataValueMember: 'appName',
            dataTextMember: 'appName',
            hidden: false
        },
        {
            headerText: 'Type',
            columnName: "rating",
            dataType: "any",
            dataValueMember: 'ratingID',
            dataTextMember: 'rating',
            hidden: false,
            inputControl: {
                controlType: 'select',
                dataTextMember: 'rating',
                dataValueMember: 'ratingID'
            }
        },
        {
            headerText: 'App ID',
            columnName: "appID",
            dataType: "any",
            dataValueMember: 'appID',
            dataTextMember: 'appID',
            hidden: true
        },
        {
            headerText: 'Category',
            columnName: "categoryID",
            dataType: "any",
            dataValueMember: 'categoryID',
            dataTextMember: 'categoryID',
            hidden: true
        }
    ]
}
$(document).ready(function () {
    gridObject = yupGrid(options);
    options.columns[1].dataSource = ddlData;
    options.columns[1].bindData();;
    gridObject.bindData(data);
});

Body:
Use following code in onBindDataComplete event. This event is triggered when bindData finishes loading data.

yupObj.onBindDataComplete = function(){
   $('#appList tr td .grid-row-icon-a[id*="addRow_"]').remove();
};

Similarly you can remove delete button also.

Alternately you can use onBeforeRowDelete and onRowInsert events to restrict addition or deletion of rows.


问:
Should I always use "this" in Dart?
Is it a good practice to use always 'this' in a method.
Even if there is no usage of the same variable name as input to this method.

```<code>String getStory(number) {
   return this.storyData[number];
}
</code>```

By doing this there won't have any conflicts with any input variable name (never).
Thank you in advance for your feedback.

答:
Generally this. is only supposed to be used when there is ambiguity about what variable is being used.

```<code>class Test{
  final int x;

  Test(this.x);
}
</code>```

Title: Should I always use "this" in Dart?

Body:
Is it a good practice to use always 'this' in a method.
Even if there is no usage of the same variable name as input to this method.

String getStory(number) {
   return this.storyData[number];
}

By doing this there won't have any conflicts with any input variable name (never).
Thank you in advance for your feedback.

Body:
Generally this. is only supposed to be used when there is ambiguity about what variable is being used.

class Test{
  final int x;

  Test(this.x);
}


问:
Convert GCLID Parameter To Squarespace Hidden Field
I'm trying to pull a GCLID Parameter (EXAMPLE: https://www.example.com?gclid=CjwKCAjwiMj2BRBFEiwAYfTbCjQ-LBlWhBymAH4piPD3FalPCbl24kE7VQ4JtNJ4Jfj8XPE) from a URL and insert it into a Squarespace hidden field.

Ideally, I'd like to do this through a GTM script, but I can also add it directly into Squarespace via site-wide footer code injection. All Squarespace hidden fields start with the prefix "SQF" (in my case, the hidden field is: SQF_GCLID

I've been playing with something like this:

```<code>`<script>
window.Squarespace.onInitialize(Y, function() {
  /**
   * Get the URL parameters
   * source: https://css-tricks.com/snippets/javascript/get-url-variables/
   * @param  {String} url The URL
   * @return {Object}     The URL parameters
   */
  var getParams = function (url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i=0; i<vars.length; i++) {
      var pair = vars[i].split('=');
      params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
  };

  /**
   * Get UTM parameters from the current URL, insert them into correspondingly-named Squarespace form hidden fields.
   */
  var params = getParams(window.location.href);
  var param;
  var paramMatch;
  var paramBase;
  var formFields;
  var i;
  for (param in params) {
    paramMatch = param.match(/^gclid(.*)/i);
    if (!paramMatch) {
        continue;
    }
    paramBase = paramMatch[1];
    formFields = document.getElementsByName("SQF_GCLID");
    i = formFields.length;
    while (i--) {
      if (formFields[i]) {
        formFields[i].value = params[param];
      }
    }
  }
});
</script>`
</code>```

which is based on the code found here.

There are no other parameters to pass (just gclid).

答:
I'm not exactly sure why I wrote that code (which you referenced) the way I did, but this simpler version should do what you need, and is more flexible for parameters other than utm, as in your case:</p>

```<code><script>
window.Squarespace.onInitialize(Y, function() {
  /**
   * Get the URL parameters
   * source: https://css-tricks.com/snippets/javascript/get-url-variables/
   * @param  {String} url The URL
   * @return {Object}     The URL parameters
   */
  var getParams = function (url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i=0; i<vars.length; i++) {
      var pair = vars[i].split('=');
      params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
  };

  /**
   * Get UTM parameters from the current URL, insert them into correspondingly-named Squarespace form hidden fields.
   */
  var params = getParams(window.location.href);
  var param;
  var paramField;
  for (param in params) {
    paramField = document.getElementsByName("SQF_" + param.toUpperCase())[0];
    if (paramField) {
      paramField.value = params[param];
    }
  }
});
</script>
</code>```

Body:
I'm trying to pull a GCLID Parameter (EXAMPLE: https://www.example.com?gclid=CjwKCAjwiMj2BRBFEiwAYfTbCjQ-LBlWhBymAH4piPD3FalPCbl24kE7VQ4JtNJ4Jfj8XPE) from a URL and insert it into a Squarespace hidden field.

Ideally, I'd like to do this through a GTM script, but I can also add it directly into Squarespace via site-wide footer code injection. All Squarespace hidden fields start with the prefix "SQF" (in my case, the hidden field is: SQF_GCLID

I've been playing with something like this:

``

which is based on the code found here.

There are no other parameters to pass (just gclid).

Body:
I'm not exactly sure why I wrote that code (which you referenced) the way I did, but this simpler version should do what you need, and is more flexible for parameters other than utm, as in your case:

<script>
window.Squarespace.onInitialize(Y, function() {
  /**
   * Get the URL parameters
   * source: https://css-tricks.com/snippets/javascript/get-url-variables/
   * @param  {String} url The URL
   * @return {Object}     The URL parameters
   */
  var getParams = function (url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i=0; i<vars.length; i++) {
      var pair = vars[i].split('=');
      params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
  };

  /**
   * Get UTM parameters from the current URL, insert them into correspondingly-named Squarespace form hidden fields.
   */
  var params = getParams(window.location.href);
  var param;
  var paramField;
  for (param in params) {
    paramField = document.getElementsByName("SQF_" + param.toUpperCase())[0];
    if (paramField) {
      paramField.value = params[param];
    }
  }
});
</script>


问:
How to create an instance of an annotation
I am trying to do some Java annotation magic. I must say I am still catching up on annotation tricks and that certain things are still not quite clear to me.

So... I have some annotated classes, methods and fields. I have a method, which uses reflection to run some checks on the classes and inject some values into a class. This all works fine.

However, I am now facing a case where I need an instance (so to say) of an annotation. So... annotations aren't like regular interfaces and you can't do an anonymous implementation of a class. I get it. I have looked around some posts here regarding similar problems, but I can't seem to be able to find the answer to what I am looking for.

I would basically like to get and instance of an annotation and be able to set some of it's fields using reflection (I suppose). Is there at all a way to do this?

答:
You can also absolutely stupidly (but simply) create a dummy annotation target and get it from there

```<code>@MyAnnotation(foo="bar", baz=Blah.class)
private static class Dummy {}
</code>```

And

```<code>final MyAnnotation annotation = Dummy.class.getAnnotation(MyAnnotation.class)
</code>```

Creating method/parameter targeted annotation instances may be a little more elaborate, but this approach has the benefit of getting the annotation instance as the JVM would normally do.
Needless to say it is as simple as it can get.

ContentLicense: CC BY-SA 3.0

Body:
You can also absolutely stupidly (but simply) create a dummy annotation target and get it from there

@MyAnnotation(foo="bar", baz=Blah.class)
private static class Dummy {}

And

final MyAnnotation annotation = Dummy.class.getAnnotation(MyAnnotation.class)

Creating method/parameter targeted annotation instances may be a little more elaborate, but this approach has the benefit of getting the annotation instance as the JVM would normally do.
Needless to say it is as simple as it can get.


问:
Authentication fails with Uploadify + Paperclip + Clearance
I have Uploadify almost working with Paperclip and Authentication, mostly using this guide.

I've got past the nasty InvalidAuthenticationToken errors by passing the Authentication_token and session information as parameters and using middleware to create a cookie header from them, however the controller authentication filter is still failing and the current_user is not available.

Has anyone any ideas as to why this might be?

I looked through the Clearance plugin and it seems to come down to the user_from_cookie method, which finds the user based on cookies[:remember_token]

```<code>  def user_from_cookie
    if token = cookies[:remember_token]
      ::User.find_by_remember_token(token)
    end
  end
</code>```

So i'm thinking the middleware should also create a remember_token cookie header?

Any help would be appreciated, this is proving a bit much for me!

答:
I don't know if this is your issue, but I run into a similar one, I had setup 2 auth level, one with basic http and one with devise, the session worked beautifully for devise and all, but never got around the basic http...
Hope this helps.

Alex

Body:
I have Uploadify almost working with Paperclip and Authentication, mostly using this guide.

I've got past the nasty InvalidAuthenticationToken errors by passing the Authentication_token and session information as parameters and using middleware to create a cookie header from them, however the controller authentication filter is still failing and the current_user is not available.

Has anyone any ideas as to why this might be?

I looked through the Clearance plugin and it seems to come down to the user_from_cookie method, which finds the user based on cookies[:remember_token]

  def user_from_cookie
    if token = cookies[:remember_token]
      ::User.find_by_remember_token(token)
    end
  end

So i'm thinking the middleware should also create a remember_token cookie header?

Any help would be appreciated, this is proving a bit much for me!


问:
Python - How to make multiply a given number to a given string
I want to display a deck and output the number of cards.

Here are the cards:
side note: middle column is the power, last column is the number of cards for that name.

```<code>Admiral,30,1
General,25,1
Colonel,20,2
Major,15,2
Captain,10,2
Lieutenant,7,2
Sergeant,5,4
Corporal,3,6
Private,1,10
</code>```

The number column represent the number of cards there is for that name. I want it to print out the following below using append. I know I'm suppose to append the rank column to the deck using a for loop, but I'm not sure how to code that.

The output is suppose to be:

```<code>['Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private']
There are 30 cards in the deck.
</code>```

my code here:

```<code>while True:
    text = rankFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    data = text.split(",")
    rankList.append(data[0])
    powerList.append(int(data[1]))
    numberList.append(int(data[2]))

    for i in range(0, len(rankList)):
        rankList.append(numberList[i])  # this wont work since number is an integer but how can I modifiy this...

rankFile.close()

print(50*"=")
print("\t\tLevel 3 Deck")
print(50*"=")
print (rankList)
print (powerList)
print (numberList)
</code>```

答:
You can use also list.extend method to add specific number of cards:

```<code>cards = []
with open('cards.txt', 'r') as f_in:
    for line in f_in:
        r, p, n = line.strip().split(',')
        cards.extend((r, p) for _ in range(int(n)))

ranks, powers = zip(*cards)

print(ranks)
print(powers)
</code>```

Prints:

```<code>('Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private')
('30', '25', '20', '20', '15', '15', '10', '10', '7', '7', '5', '5', '5', '5', '3', '3', '3', '3', '3', '3', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1')
</code>```

Body:
I want to display a deck and output the number of cards.

Here are the cards:
side note: middle column is the power, last column is the number of cards for that name.

Admiral,30,1
General,25,1
Colonel,20,2
Major,15,2
Captain,10,2
Lieutenant,7,2
Sergeant,5,4
Corporal,3,6
Private,1,10

The number column represent the number of cards there is for that name. I want it to print out the following below using append. I know I'm suppose to append the rank column to the deck using a for loop, but I'm not sure how to code that.

The output is suppose to be:

['Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private']
There are 30 cards in the deck.

my code here:

while True:
    text = rankFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    data = text.split(",")
    rankList.append(data[0])
    powerList.append(int(data[1]))
    numberList.append(int(data[2]))

    for i in range(0, len(rankList)):
        rankList.append(numberList[i])  # this wont work since number is an integer but how can I modifiy this...

rankFile.close()

print(50*"=")
print("\t\tLevel 3 Deck")
print(50*"=")
print (rankList)
print (powerList)
print (numberList)

Body:
You can use also list.extend method to add specific number of cards:

cards = []
with open('cards.txt', 'r') as f_in:
    for line in f_in:
        r, p, n = line.strip().split(',')
        cards.extend((r, p) for _ in range(int(n)))

ranks, powers = zip(*cards)

print(ranks)
print(powers)

Prints:

('Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private')
('30', '25', '20', '20', '15', '15', '10', '10', '7', '7', '5', '5', '5', '5', '3', '3', '3', '3', '3', '3', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1')


问:
Acquiring OAuth2 access tokens for Exchange Management Shell cmdlets
In our python application, we use the Exchange Management Shell cmdlets to perform some tasks.
(In fact, the python application runs .Net application, which calls the Exchange Management Shell cmdlets.)
Currently we use basic authentication with the New-PSSession cmdlet.
On the other hand, we are already acquiring OAuth2 access tokens for different APIs and resources.
Now we would like to use OAuth2 authentication with the Exchange Management Shell cmdlets.

We had a look at this article[1].

However we have a few questions:

Is there a way to get access tokens without using ADAL and MSAL?

Is there a way to get a new access token using a refresh token?

It seems there is no chance to use an external(system) browser, isn't there?
Thank you in advance.

[1] https://developermessaging.azurewebsites.net/2018/09/07/acquiring-oauth2-access-tokens-for-automating-exchange-management-shell-cmdlets/?unapproved=96&moderation-hash=9250fbdda0e11fd8af9bafd4c3576139#review-96

答:
Oh, in fact, everything is very simple:

Request for an authorization code: https://login.microsoftonline.com/common/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A55555&client_id=a0c73c16-a7e3-4564-9a95-2bdf47383716&response_type=code

Request for an access token:

URL: https://login.microsoftonline.com/common/oauth2/token

body: resource=https%3A%2F%2Foutlook.office365.com&client_id=a0c73c16-a7e3-4564-9a95-2bdf47383716&redirect_uri=http%3A%2F%2Flocalhost%3A9999&code=YOUR_AUTHORIZATION_CODE&client_secret=&grant_type=authorization_code


问:
How to access an Azure Blob that starts with a '/'?
I have a blob that is (according to Azure) at a URL of: https://surveillanceprodblob.blob.core.windows.net/rpi-events//BAs1nRTx/00001f240_2020-05-12_10-12-06.png

The problem here is that the blob starts with "/BAs1nRTx".

Is it possible to access this object from a browser? I have tried

Removing the second slash so the url is: https://surveillanceprodblob.blob.core.windows.net/rpi-events/BAs1nRTx/00001f240_2020-05-12_10-12-06.png

Replacing the slash with %2F so the url is: https://surveillanceprodblob.blob.core.windows.net/rpi-events/%2FBAs1nRTx/00001f240_2020-05-12_10-12-06.png

Adding another slash so the url is: https://surveillanceprodblob.blob.core.windows.net/rpi-events///BAs1nRTx/00001f240_2020-05-12_10-12-06.png

None of these worked for me.

Is it possible to access this blob from a browser?

EDIT:

Here is what the portal shows

答:
I have a file at /a/b/c/10dec.csv location same as yours.

When I tried to download https://[STORAGE_ACCOUNT].blob.core.windows.net/test-archive-container//a/b/c/10dec.csv it failed.

But, when I tried to download using https://[STORAGE_ACCOUNT].blob.core.windows.net/test-archive-container//a/b/c/10dec.csv?[BLOB SAS TOKEN] it works.

So, I think directly using BLOB URL you cannot download from the Browser, you always need to authenticate. That's why you will need to provide SAS TOKEN.

Please Generate SAS as shown below:

And use that URL in Browser, it will work.

Please let me know if you need more information.


问:
TCP server not receiving data correctly in Python
I'm trying to make a TCP server in Python in which you have to login to be able enter, but when verifying if the user can enter, it always says the user cannot be found, even when the user is supposed to be able to enter. This is the server code:

```<code>import socket
from threading import *

class user:
    def __init__(self, username, password):
        self.username = username
        self.password = password

user1 = user('user', 'pass')

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 9000
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            self.sock.send(b'LOGIN\n')
            self.sock.send(b'Username:')
            name = self.sock.recv(1024).decode()
            print(name)
            print(user1.username)
            self.sock.send(b'Password:')
            pw = self.sock.recv(1024).decode()
            print(pw)
            print(user1.password)
            if (name == user1.username) and (pw == user1.password):
                self.sock.send(b'Welcome, ', name)
            else:
                self.sock.send(b'User not found.')

serversocket.listen(5)
print('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)
</code>```

I'm using telnet to communicate with the server and I can see that the input is correct. This is the output which confirms that they're similar:

```<code>server started and listening
user

user
pass

pass
</code>```

This is the telnet console:

```<code>LOGIN
Username:user
Password:pass
User not found.
</code>```

Any help is appreciated. Thanks

答:
The expected input from telnet to the server isn't what you think it is.

Since telnet adds a trailing \n at the end of the transmitted string, you need to strip the incoming data. So the simplest approach would be:

name = self.sock.recv(1024).decode().strip()
pw = self.sock.recv(1024).decode().strip()
```

<p>Strip simply removes trailing white spaces and is probably most suitable here.<br>
You can debug and check if this is the case by doing:</p>

<pre class="lang-py prettyprint-override"><code>print([name])
</code>```

As a dirty workaround to see the actual contents of the string and not just the printed representation in the terminal. it should show you user\n instead of user which you expect. And it's always a good idea to print or debug your variables to verify the content is what you expect it to be.

Body:
I'm trying to make a TCP server in Python in which you have to login to be able enter, but when verifying if the user can enter, it always says the user cannot be found, even when the user is supposed to be able to enter. This is the server code:

import socket
from threading import *

class user:
    def __init__(self, username, password):
        self.username = username
        self.password = password

user1 = user('user', 'pass')

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 9000
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            self.sock.send(b'LOGIN\n')
            self.sock.send(b'Username:')
            name = self.sock.recv(1024).decode()
            print(name)
            print(user1.username)
            self.sock.send(b'Password:')
            pw = self.sock.recv(1024).decode()
            print(pw)
            print(user1.password)
            if (name == user1.username) and (pw == user1.password):
                self.sock.send(b'Welcome, ', name)
            else:
                self.sock.send(b'User not found.')

serversocket.listen(5)
print('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

I'm using telnet to communicate with the server and I can see that the input is correct. This is the output which confirms that they're similar:

server started and listening
user

user
pass

pass

This is the telnet console:

LOGIN
Username:user
Password:pass
User not found.

Any help is appreciated. Thanks

Body:
The expected input from telnet to the server isn't what you think it is.

Since telnet adds a trailing \n at the end of the transmitted string, you need to strip the incoming data. So the simplest approach would be:

name = self.sock.recv(1024).decode().strip()
pw = self.sock.recv(1024).decode().strip()

Strip simply removes trailing white spaces and is probably most suitable here.

You can debug and check if this is the case by doing:

print([name])

As a dirty workaround to see the actual contents of the string and not just the printed representation in the terminal. it should show you user\n instead of user which you expect. And it's always a good idea to print or debug your variables to verify the content is what you expect it to be.


问:
db2_num_rows() returns -1
I have a query that uses pagination that worked earlier today, but now is returning a fetch failure. I checked the db2_num_rows() and it is giving me -1. When I check the PHP documentation, db2_num_rows() should never return a negative value; it should always return a positive value or false.

Does anyone have an idea what condition would cause it to return -1? Since db2_stmt_error() and db2_stmt_errorMsg() both return empty-string, I'm hoping this would help me troubleshoot the root cause of my problem.

Here is a shortened version of my script. The query itself works correctly when I test with the AS400 console using strsql.

```<code>        $minRow = 1;
        $maxRow = 14;
        $sql = 'SELECT * '
            . 'FROM ('
            . 'SELECT row_number() OVER (ORDER BY FETYPE) AS ID, '
            . 'FETYPE, FECNO, FELC, FEID, FEDESC, FEBLEND, FECALC, '
            . 'CAST(FECOST AS VARCHAR(12)) AS FECOST, '
            . 'CAST(FEMARK AS VARCHAR(12)) AS FEMARK, '
            . 'FEMKTP, '
            . 'CAST(FESRNK AS VARCHAR(12)) AS FESRNK, '
            . 'FEBSIZ, FEUDT, FEUTM, '
            . 'FEMDT, FEUSID, FEINS1, FEMIXINS1, FEMIXINS2, FEMIXINS3, '
            . 'FEVER, FEIMDT, FEANIMAL, '
            . 'CAST(FERATE AS VARCHAR(7)) AS FERATE, '
            . 'FETLA1, FETLA2, FETLA3, '
            . 'FETLA4, FETLA5, FETLA6, FETLA7, FETLA8, FETLA9, FETLA10, '
            . 'FESLNO, FESORV, FECMCD, FEMULTI, FEBRILLDT, FEFLUSH, '
            . 'FEFLUSHQTY, '
            . 'CAST(FECFEE AS VARCHAR(12)) AS FECFEE, '
            . 'FECFTP, FEFILL, FEMIXTIME, FEPURPOSE, FEMEDS, '
            . 'FEMEDTXT, FEDIRECT, FEMORTXT '
            . 'FROM UFFRATH ' . $this->whereClause
            . ') AS P '
            . 'WHERE P.ID BETWEEN ? AND ?';
        db2_bind_param($stmt, 1, 'minRow', DB2_PARAM_IN);
        db2_bind_param($stmt, 2, 'maxRow', DB2_PARAM_IN);
        $exec = db2_execute($stmt);

        if ($exec) {
            $this->log('num_rows = '. db2_num_rows($stmt), true); // writes 'num_rows = -1' to the log file
            while ($row = db2_fetch_object($stmt)) { // throws db2_fetch_object(): Fetch Failure
                array_push($data, $this->buildRation($row));
            }
        }
</code>```

答:
I can confirm that... any "num_rows"-function does not work on IBM-i-db2 (regardless if odbc or native db2).

You have to execute a separate "SELECT COUNT(*) FROM ..." statement...

The simplest solution is to wrap the original SQL statement into an WITH clause, in your case:

```<code>list($count) = db2_fetch_array(db2_execute("WITH X AS(".$stmt.") SELECT COUNT(*) FROM X"));
</code>```

So you can reuse your SQL statement...

(as long as it does not have a "FETCH FIRST ? ROWS ONLY"-part... :-) #paging)
It has also a very good performance because you count the rows of a previously executed statement which is is in the cache for sure...

Regards

Title: db2_num_rows() returns -1

Body:
I have a query that uses pagination that worked earlier today, but now is returning a fetch failure. I checked the db2_num_rows() and it is giving me -1. When I check the PHP documentation, db2_num_rows() should never return a negative value; it should always return a positive value or false.

Does anyone have an idea what condition would cause it to return -1? Since db2_stmt_error() and db2_stmt_errorMsg() both return empty-string, I'm hoping this would help me troubleshoot the root cause of my problem.

Here is a shortened version of my script. The query itself works correctly when I test with the AS400 console using strsql.

        $minRow = 1;
        $maxRow = 14;
        $sql = 'SELECT * '
            . 'FROM ('
            . 'SELECT row_number() OVER (ORDER BY FETYPE) AS ID, '
            . 'FETYPE, FECNO, FELC, FEID, FEDESC, FEBLEND, FECALC, '
            . 'CAST(FECOST AS VARCHAR(12)) AS FECOST, '
            . 'CAST(FEMARK AS VARCHAR(12)) AS FEMARK, '
            . 'FEMKTP, '
            . 'CAST(FESRNK AS VARCHAR(12)) AS FESRNK, '
            . 'FEBSIZ, FEUDT, FEUTM, '
            . 'FEMDT, FEUSID, FEINS1, FEMIXINS1, FEMIXINS2, FEMIXINS3, '
            . 'FEVER, FEIMDT, FEANIMAL, '
            . 'CAST(FERATE AS VARCHAR(7)) AS FERATE, '
            . 'FETLA1, FETLA2, FETLA3, '
            . 'FETLA4, FETLA5, FETLA6, FETLA7, FETLA8, FETLA9, FETLA10, '
            . 'FESLNO, FESORV, FECMCD, FEMULTI, FEBRILLDT, FEFLUSH, '
            . 'FEFLUSHQTY, '
            . 'CAST(FECFEE AS VARCHAR(12)) AS FECFEE, '
            . 'FECFTP, FEFILL, FEMIXTIME, FEPURPOSE, FEMEDS, '
            . 'FEMEDTXT, FEDIRECT, FEMORTXT '
            . 'FROM UFFRATH ' . $this->whereClause
            . ') AS P '
            . 'WHERE P.ID BETWEEN ? AND ?';
        db2_bind_param($stmt, 1, 'minRow', DB2_PARAM_IN);
        db2_bind_param($stmt, 2, 'maxRow', DB2_PARAM_IN);
        $exec = db2_execute($stmt);

        if ($exec) {
            $this->log('num_rows = '. db2_num_rows($stmt), true); // writes 'num_rows = -1' to the log file
            while ($row = db2_fetch_object($stmt)) { // throws db2_fetch_object(): Fetch Failure
                array_push($data, $this->buildRation($row));
            }
        }

Body:
I can confirm that... any "num_rows"-function does not work on IBM-i-db2 (regardless if odbc or native db2).

You have to execute a separate "SELECT COUNT(*) FROM ..." statement...

The simplest solution is to wrap the original SQL statement into an WITH clause, in your case:

list($count) = db2_fetch_array(db2_execute("WITH X AS(".$stmt.") SELECT COUNT(*) FROM X"));

So you can reuse your SQL statement...

(as long as it does not have a "FETCH FIRST ? ROWS ONLY"-part... :-) #paging)
It has also a very good performance because you count the rows of a previously executed statement which is is in the cache for sure...

Regards


问:
Adding a new label where clicked SWIFT
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

```<code>@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }

</code>```

答:
You cannot call copy on NSTextView, that causes the error message.

You implement all the required methods by subclassing the view, but I'd suggest you allocate new text views programmatically and set their style in code instead of Interface builder.

Here's another thread dealing with copying objects: "[something copyWithZone:]: unrecognized selector sent to instance" when using Bindings / Core Data

Title: Adding a new label where clicked SWIFT

Body:
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }


问:
Vue : how to download a file to browser using the download tag
I'm using axios and want to download a PDF and an image file.

I can download both and open the image, but, when I try to open the PDF file, it doesn't open.

```<code>downloadItem({ url, name }) {
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: response.data.type });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = name;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch(console.error);
    },
</code>```

Can anybody help me ? Sorry for my English.

答:
Would this work for you?</p>

```<code>axios
.get(url, {
  headers: {
    'Accept': 'application/pdf'
  },
  responseType: 'blob' })
.then(function (response) {
  switch ([WHAT IS YOUR TYPE]) {
    case "image": {
      const blob = new Blob([response.data], { type: response.data.type });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = name;
      link.click();
      URL.revokeObjectURL(link.href);
      break
    }
    case "pdf": {
      const blob = new Blob([response.data], { type: 'application/pdf' })
      const objectUrl = window.URL.createObjectURL(blob)
      window.open(objectUrl)
      elt.impressionEnCours = false
      break
    }
  }
})
.catch(function (error) {
  console.log(JSON.stringify(error))
})
</code>```

Body:
I'm using axios and want to download a PDF and an image file.

I can download both and open the image, but, when I try to open the PDF file, it doesn't open.

downloadItem({ url, name }) {
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: response.data.type });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = name;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch(console.error);
    },

Can anybody help me ? Sorry for my English.

Body:
Would this work for you?

axios
.get(url, {
  headers: {
    'Accept': 'application/pdf'
  },
  responseType: 'blob' })
.then(function (response) {
  switch ([WHAT IS YOUR TYPE]) {
    case "image": {
      const blob = new Blob([response.data], { type: response.data.type });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = name;
      link.click();
      URL.revokeObjectURL(link.href);
      break
    }
    case "pdf": {
      const blob = new Blob([response.data], { type: 'application/pdf' })
      const objectUrl = window.URL.createObjectURL(blob)
      window.open(objectUrl)
      elt.impressionEnCours = false
      break
    }
  }
})
.catch(function (error) {
  console.log(JSON.stringify(error))
})


问:
Python Excel : openpyxl - copy/select values in dropdown list
I'm trying to automate an excel app using openpyxl in python.

Here is my problem:
I'm copying a set of cells from source tab to another set of cells (same number) in destination tab. Destination tab is already present and populated with values, one of which is a drop-down list. And, when I paste the values, it's deleting the drop-down box and pasting the plain values.

Here is what I would like to achieve:
When I paste, it should just pick a value in the drop-down. I am sure, the value picked up from source tab is present in the drop-down list.

Here is my code:

```<code>    # Copy from src excel to buffer
    for i in range(start_row, end_row + 1):
        for j in range(ord(start_col), ord(end_col)+1):
            cell = chr(j) + str(i)
            buffer[cell] = input_ws[cell].value

    # Find the sheet name from file name of input
    output_ws_name = os.path.basename(file_path).split('_')[0]

    # Output data from buffer to output worksheet for that file
    output_ws = output_wb[output_ws_name]
    for i in range(start_row, end_row + 1):
        for j in range(ord(start_col), ord(end_col)+1):
            cell = chr(j) + str(i)
            output_ws[cell] = buffer[cell]
</code>```

Thanks for your help :-)

答:
Looks like it is a known issue, refer to,
https://bitbucket.org/openpyxl/openpyxl/issues/1458/list-data-validation-lost-from-source-file</p>

Body:
I'm trying to automate an excel app using openpyxl in python.

Here is my problem:
I'm copying a set of cells from source tab to another set of cells (same number) in destination tab. Destination tab is already present and populated with values, one of which is a drop-down list. And, when I paste the values, it's deleting the drop-down box and pasting the plain values.

Here is what I would like to achieve:
When I paste, it should just pick a value in the drop-down. I am sure, the value picked up from source tab is present in the drop-down list.

Here is my code:

    # Copy from src excel to buffer
    for i in range(start_row, end_row + 1):
        for j in range(ord(start_col), ord(end_col)+1):
            cell = chr(j) + str(i)
            buffer[cell] = input_ws[cell].value

    # Find the sheet name from file name of input
    output_ws_name = os.path.basename(file_path).split('_')[0]

    # Output data from buffer to output worksheet for that file
    output_ws = output_wb[output_ws_name]
    for i in range(start_row, end_row + 1):
        for j in range(ord(start_col), ord(end_col)+1):
            cell = chr(j) + str(i)
            output_ws[cell] = buffer[cell]

Thanks for your help :-)


问:
Why jsx code in external js fie doesn't work with babel cdn?
I am trying to use babel standalone to tansform jsx code, but it doesn't work when use an external file

This is the code that works:

```

<p>But when use an external js file, it doesn't work</p>

<p>html</p>

<pre class="lang-html prettyprint-override"><code><div id="root"></div>
<script src="index.js" type="text/babel"></script>
<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://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</code>```

index.js

const App = () => {
   return (
hello world
)
}

ReactDOM.render(<App />, document.getElementById('root'))
```

答:
It works with an external file too. If it does not work for you, it's most likely not related to Babel or React.

My guess is that your browser is simply not able to fetch index.js. If you are testing just the HTML file without a server, then the browser may prevent it from loading index.js due to security reasons. E.g. this is what Chrome told me when I tried your code exactly:

Access to XMLHttpRequest at 'file:///home/xxx/yyy/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I then fired up a basic web server and served index.js at http://localhost:8000/index.js, and voila - it worked just fine.

Check the browser's console to see if you get this or a similar error. Check the network tab to see if index.js is fetched properly. Read about Chrome's (or whatever browser you're using) devtools if you're not sure how to do any of this.

If I am right and you then wish to resolve this problem, it's a completely separate issue, search SO for solutions.

Body:
I am trying to use babel standalone to tansform jsx code, but it doesn't work when use an external file

This is the code that works:

But when use an external js file, it doesn't work

html

index.js

const App = () => {
   return (
hello world
)
}

ReactDOM.render(<App />, document.getElementById('root'))


问:
How the example from Java Concurrency in practice is thread safe
Below is an example from book Java Concurrency in Practice(Listing 2.8) of a thread safe class.

My question is how the below class is thread safe?

For example if two threads Thread A and Thread B enter into service method of CachedFactorizer. Thread B followed by Thread A. Now if Thread A is executing first synchronized block and Thread B obviously waits for the intrinsic lock of the object. And if Thread B makes it to the first synchronized block before the Thread A makes it to the second synchronized block, it will be viewing a stale value and potentially this condition is known as Race Condition.

So, is my understanding right here? Or am I lacking some basic understanding of concurrency?

```<code>@ThreadSafe
public class CachedFactorizer implements Servlet {

    @GuardedBy("this") private BigInteger lastNumber;

    @GuardedBy("this") private BigInteger[] lastFactors;

    @GuardedBy("this") private long hits;

    @GuardedBy("this") private long cacheHits;

    public synchronized long getHits() { return hits; }

    public synchronized double getCacheHitRatio() {

        return (double) cacheHits / (double) hits;

    }

    public void service(ServletRequest req, ServletResponse resp) {

        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factor(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(resp, factors);
    }
}
</code>```

答:
what's the difference if  I remove both clone()? eg: factors = lastFactors.clone(); I think it still works. </p>

```<code>public void service(ServletRequest req, ServletResponse resp) {

    BigInteger i = extractFromRequest(req);
    BigInteger[] factors = null;
    synchronized (this) {
        ++hits;
        if (i.equals(lastNumber)) {
            ++cacheHits;
            factors = lastFactors; //not cloned
        }
    }
    if (factors == null) {
        factors = factor(i);
        synchronized (this) {
            lastNumber = i;
            lastFactors = factors;//not cloned
        }
    }
    encodeIntoResponse(resp, factors);
}
</code>```

Body:
Below is an example from book Java Concurrency in Practice(Listing 2.8) of a thread safe class.

My question is how the below class is thread safe?

For example if two threads Thread A and Thread B enter into service method of CachedFactorizer. Thread B followed by Thread A. Now if Thread A is executing first synchronized block and Thread B obviously waits for the intrinsic lock of the object. And if Thread B makes it to the first synchronized block before the Thread A makes it to the second synchronized block, it will be viewing a stale value and potentially this condition is known as Race Condition.

So, is my understanding right here? Or am I lacking some basic understanding of concurrency?

@ThreadSafe
public class CachedFactorizer implements Servlet {

    @GuardedBy("this") private BigInteger lastNumber;

    @GuardedBy("this") private BigInteger[] lastFactors;

    @GuardedBy("this") private long hits;

    @GuardedBy("this") private long cacheHits;

    public synchronized long getHits() { return hits; }

    public synchronized double getCacheHitRatio() {

        return (double) cacheHits / (double) hits;

    }

    public void service(ServletRequest req, ServletResponse resp) {

        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factor(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(resp, factors);
    }
}

Body:
what's the difference if  I remove both clone()? eg: factors = lastFactors.clone(); I think it still works.

public void service(ServletRequest req, ServletResponse resp) {

    BigInteger i = extractFromRequest(req);
    BigInteger[] factors = null;
    synchronized (this) {
        ++hits;
        if (i.equals(lastNumber)) {
            ++cacheHits;
            factors = lastFactors; //not cloned
        }
    }
    if (factors == null) {
        factors = factor(i);
        synchronized (this) {
            lastNumber = i;
            lastFactors = factors;//not cloned
        }
    }
    encodeIntoResponse(resp, factors);
}


问:
How to make one element of a list go to the top on page load?
I need one particular element of an unordered list to appear at the top of the list on page load, but not at the top of the page.

My code below works on Firefox and Safari, but not on Chrome or Opera. I use Javascript only.

Note that if I remove location.replace('#'); , the element will jump to the top of the page on page load, which is unwanted.

location.replace('#e');
location.replace('#');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#e {
 color:#fff;
 background:red;
}

#list {
 overflow:auto;
 height:100vh;
 border:1px solid #000;
}</code>```

LOGO

Link a

Link b

Link c

Link d

Link e

Link f

Link g

Link h

Link i

Link j

Link k

Link l

Link m

Link n

Link o

Link p

Link q

Link r

Link s

Link t

Link u

Link v

Link w

Link x

Link y

Link z

Link aa

Link ab

Link ac

Link ad

Link ae

Link af

Link ag

Link ah

Link ai

Link aj

Link ak

Link al

Link am

Link an

Link ao

Link ap

Link aq

Link ar

Link as

Link at

Link au

Link av

Link aw

Link ax

Link ay

Link az

```

答:
Although there is probably a smoother way to do it, here is the javascript that solves my issue:</p>

```<code>location.replace('#e');

setTimeout(function() {
  location.replace('#');
}, 1);
</code>```

Body:
I need one particular element of an unordered list to appear at the top of the list on page load, but not at the top of the page.

My code below works on Firefox and Safari, but not on Chrome or Opera. I use Javascript only.

Note that if I remove location.replace('#'); , the element will jump to the top of the page on page load, which is unwanted.

location.replace('#e');
location.replace('#');

#e {
 color:#fff;
 background:red;
}

#list {
 overflow:auto;
 height:100vh;
 border:1px solid #000;
}

LOGO

Link a

Link b

Link c

Link d

Link e

Link f

Link g

Link h

Link i

Link j

Link k

Link l

Link m

Link n

Link o

Link p

Link q

Link r

Link s

Link t

Link u

Link v

Link w

Link x

Link y

Link z

Link aa

Link ab

Link ac

Link ad

Link ae

Link af

Link ag

Link ah

Link ai

Link aj

Link ak

Link al

Link am

Link an

Link ao

Link ap

Link aq

Link ar

Link as

Link at

Link au

Link av

Link aw

Link ax

Link ay

Link az

Body:
Although there is probably a smoother way to do it, here is the javascript that solves my issue:

location.replace('#e');

setTimeout(function() {
  location.replace('#');
}, 1);


问:
How to click the element if the value of the id attribute starts with numbers using Selenium in IE11
I checked the existing answers and it looks like there is no answered question regarding this.

Here it is: selenium 32 bit driver, IE 11, windows 10 64bit.
I need to find the elements with the unique static id = 0idMenuTitle or 1idMenuTitle

HTML code

SPAN onmouseover="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOVER;" onmouseout="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOFF;" id=1idMenuTitle class=clsMenuTitle style="MAX-WIDTH: none; MIN-WIDTH: auto; MIN-HEIGHT: auto; MAX-HEIGHT: none; BACKGROUND-COLOR: #cccc" minmax_bound="true" width="100%">menu1

I'm using the following:

```<code>driver.findElement(By.id("0idMenuTitle")).click();
</code>```

and have the error

```<code>org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == #\31 idMenuTitle
</code>```

I'm trying to find with the partial id

```<code>driver.findElement(By.cssSelector("[id*=MenuTitle]")).click();
</code>```

but got

```<code>org.openqa.selenium.ElementNotInteractableException: Element is not displayed
</code>```

I tried with Xpath as well, the same errors.
There is no issue if I'm using FF or GC but I must use IE11, no choice.
There is no problem to find the elements with id that does not start with numbers...

Any idea please?

Update

I'm trying to find the element by id starting with 0, but selenium shows the error regarding css selector (?) and the id #\31 (???)

答:
You need to consider a couple of things as follows:

A WebElement with the value of id attribute as 0idMenuTitle or 1idMenuTitle is not a static id, it's dynamic id, i.e. partial value is assigned when the DOM Tree gets completely loaded. Hence when you use By.id("0idMenuTitle") you face NoSuchElementException.

But when you use [id*=MenuTitle] you are seeing ElementNotInteractableException as the locator strategy finds some other element which is not displayed within the HTML DOM.

Solution

To invoke click on the desired element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

Using id:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("0idMenuTitle"))).click();
</code>```

Using cssSelector:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#0idMenuTitle"))).click();
</code>```

Using xpath:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='0idMenuTitle']"))).click();
</code>```

Body:
I checked the existing answers and it looks like there is no answered question regarding this.

Here it is: selenium 32 bit driver, IE 11, windows 10 64bit.
I need to find the elements with the unique static id = 0idMenuTitle or 1idMenuTitle

HTML code

SPAN onmouseover="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOVER;" onmouseout="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOFF;" id=1idMenuTitle class=clsMenuTitle style="MAX-WIDTH: none; MIN-WIDTH: auto; MIN-HEIGHT: auto; MAX-HEIGHT: none; BACKGROUND-COLOR: #cccc" minmax_bound="true" width="100%">menu1

I'm using the following:

driver.findElement(By.id("0idMenuTitle")).click();

and have the error

org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == #\31 idMenuTitle

I'm trying to find with the partial id

driver.findElement(By.cssSelector("[id*=MenuTitle]")).click();

but got

org.openqa.selenium.ElementNotInteractableException: Element is not displayed

I tried with Xpath as well, the same errors.
There is no issue if I'm using FF or GC but I must use IE11, no choice.
There is no problem to find the elements with id that does not start with numbers...

Any idea please?

Update

I'm trying to find the element by id starting with 0, but selenium shows the error regarding css selector (?) and the id #\31 (???)

Body:
You need to consider a couple of things as follows:

A WebElement with the value of id attribute as 0idMenuTitle or 1idMenuTitle is not a static id, it's dynamic id, i.e. partial value is assigned when the DOM Tree gets completely loaded. Hence when you use By.id("0idMenuTitle") you face NoSuchElementException.

But when you use [id*=MenuTitle] you are seeing ElementNotInteractableException as the locator strategy finds some other element which is not displayed within the HTML DOM.

Solution

To invoke click on the desired element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

Using id:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("0idMenuTitle"))).click();

Using cssSelector:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#0idMenuTitle"))).click();

Using xpath:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='0idMenuTitle']"))).click();


问:
How to resolve conflicts in xcode 4 when using SVN?
On trying to update my working copy, Xcode indicates that there are certain conflicts. A new screen comes up which shows my local file on the left and the server code on the right highlighting whatever conflicts are present. What I'm doing at this stage is, reviewing my code and make necessary changes using this tool:

When I'm finally done reviewing and making changes to my code as necessary, I'd like to update my project with the changes I've made. However the update button at the bottom is still disabled. What is it that I'm missing here? How do I convey to Xcode that I'm done making changes and it may update the project?

答: You have click on a very line that shows conflict and resolve it explicitly by choosing either left or right version. After that update button will be enabled.</p>


问:
why laravel view is showing blank page?
when I open "http://localhost/app/public/"
the default laravel home page works perfectly which is a welcome page where in the routes file there is this:

```<code>Route::get('/', function () {
return view('welcome');
 });
</code>```

but I'm learning so I just changed the "welcome" to "home" and created a new file resources/views/home.blade.php with the following simple code:

```<code><?php
 echo 'hello world of laravel';
 ?>
</code>```

but when I open "http://localhost/app/public/"

it shows a blank page.

what am i missing?

答: This is the solution open .env file make sure no space in your app name.The app name should be one word for example AppOne not App One</p>

Title: why laravel view is showing blank page?

Body:
when I open "http://localhost/app/public/"
the default laravel home page works perfectly which is a welcome page where in the routes file there is this:

Route::get('/', function () {
return view('welcome');
 });

but I'm learning so I just changed the "welcome" to "home" and created a new file resources/views/home.blade.php with the following simple code:

<?php
 echo 'hello world of laravel';
 ?>

but when I open "http://localhost/app/public/"

it shows a blank page.

what am i missing?


问:
C++ friend template that use SFINAE
This is a simple question in fact. I have a template class with one parameter.
In an other object, I make it a friend of it, like this :

```<code>template< typename type_t >
class A
{
    ...
}

template< typename type_t >
class B
{
    template< typename >
    friend class A; // Works fine !

    ...
}
</code>```

After that, I wanted to add a condition to discard integral number when instancing the class A (and B by the way), by doing this :

```<code>template< typename type_t, std::enable_if_t< std::is_floating_point_v< type_t >, bool > = false >
class A
{
    ...
}

template< typename type_t, std::enable_if_t< std::is_floating_point_v< type_t >, bool > = false >
class B
{
    template< typename >
    friend class A; // ============> Error!

    ...
}
</code>```

By reading the compiler message, I understood the template now has two parameters. But what should I put to the second parameter when I'm friending the class ? I tried template< typename, typename >, template< typename, bool > and template< typename, true >... All fails to compile.

What is the solution here ?

答:
As StoryTeller said in the comments, a static_assert inside the class B or A might be a simpler solution. It will not use a second template parameter and will enable the familiar friend declaration.

However, if you still want to go through the SFINAE way, you can declare your friend using the full SFINAE expression in it:

```<code>template<typename type_t, std::enable_if_t<std::is_floating_point_v<type_t>, bool> = false>
class B
{
    template<typename T, std::enable_if_t<std::is_floating_point_v<T>, bool>>
    friend class A;
};
</code>```

Title: C++ friend template that use SFINAE

Body:
This is a simple question in fact. I have a template class with one parameter.
In an other object, I make it a friend of it, like this :

template< typename type_t >
class A
{
    ...
}

template< typename type_t >
class B
{
    template< typename >
    friend class A; // Works fine !

    ...
}

After that, I wanted to add a condition to discard integral number when instancing the class A (and B by the way), by doing this :

template< typename type_t, std::enable_if_t< std::is_floating_point_v< type_t >, bool > = false >
class A
{
    ...
}

template< typename type_t, std::enable_if_t< std::is_floating_point_v< type_t >, bool > = false >
class B
{
    template< typename >
    friend class A; // ============> Error!

    ...
}

By reading the compiler message, I understood the template now has two parameters. But what should I put to the second parameter when I'm friending the class ? I tried template< typename, typename >, template< typename, bool > and template< typename, true >... All fails to compile.

What is the solution here ?

Body:
As StoryTeller said in the comments, a static_assert inside the class B or A might be a simpler solution. It will not use a second template parameter and will enable the familiar friend declaration.

However, if you still want to go through the SFINAE way, you can declare your friend using the full SFINAE expression in it:

template<typename type_t, std::enable_if_t<std::is_floating_point_v<type_t>, bool> = false>
class B
{
    template<typename T, std::enable_if_t<std::is_floating_point_v<T>, bool>>
    friend class A;
};


问:
Python: need the name of index
I am still very new to Python so forgive me if I do not make full sense. I have a long DataFrame and it has two columns: one with the name of tennis players and the other one with the number of titles won. I am trying to retrieve the player with the most titles won but by only showing the name of the player and not the number of titles. I tried using max() to find out the player with most titles won but I cannot figure out how to retrieve the name of the player. The "players" column is the index.

As I said, I tried using max() but it throws an error "TypeError: 'Index' object is not callable"

```<code> max(df['Titles'], key=df.index)
</code>```

Many thanks

答:
You can use a lambda expression , it's like a function that simplify lot of things , like your case " selecting the max of elements refering to the number of wins " , you can do it like this :</p>

```<code>c = max(list, key= lambda x : x[1] )
print( c[0] ) # prinx the name
</code>```

Title: Python: need the name of index

Body:
I am still very new to Python so forgive me if I do not make full sense. I have a long DataFrame and it has two columns: one with the name of tennis players and the other one with the number of titles won. I am trying to retrieve the player with the most titles won but by only showing the name of the player and not the number of titles. I tried using max() to find out the player with most titles won but I cannot figure out how to retrieve the name of the player. The "players" column is the index.

As I said, I tried using max() but it throws an error "TypeError: 'Index' object is not callable"

 max(df['Titles'], key=df.index)

Many thanks

Body:
You can use a lambda expression , it's like a function that simplify lot of things , like your case " selecting the max of elements refering to the number of wins " , you can do it like this :

c = max(list, key= lambda x : x[1] )
print( c[0] ) # prinx the name


问:
Is Interceptor.Chain.proceed() a Thread Blocking Method?
Suppose I create my own implementation of an Interceptor from OkHttp3:

class MyInterceptor: Interceptor {

    private val gson = Gson()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // Will this block the main thread?
        val response = chain.proceed(request)

        return Response.Builder()
            .code(200)
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .message("OK")
            .body(
                gson.toJson("foo").toResponseBody("application/json".toMediaType())
            )
            .build()
    }
}
```

Will the call to chain.proceed() block the main thread? This seems counter-intuitive to what is provided Retrofit's support of suspend functions, which is built on top of OkHttp3. Because I've chosen to use an interceptor, do I now lose that async support?

答:
Will the call to chain.proceed() block the main thread?

It will block whatever thread intercept() was called on. If that is the main application thread, you will have other problems (e.g., NetworkOnMainThreadException), and that situation is unrelated to whether or not you have this interceptor.

Because I've chosen to use an interceptor, do I now lose that async support?

No. This is all operating underneath that async support. If this OkHttp request was kicked off by a Retrofit suspend API, then intercept() should be called on a background thread (whichever one OkHttp/Retrofit is using from its thread pool).

Body:
Suppose I create my own implementation of an Interceptor from OkHttp3:

class MyInterceptor: Interceptor {

    private val gson = Gson()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // Will this block the main thread?
        val response = chain.proceed(request)

        return Response.Builder()
            .code(200)
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .message("OK")
            .body(
                gson.toJson("foo").toResponseBody("application/json".toMediaType())
            )
            .build()
    }
}

Will the call to chain.proceed() block the main thread? This seems counter-intuitive to what is provided Retrofit's support of suspend functions, which is built on top of OkHttp3. Because I've chosen to use an interceptor, do I now lose that async support?


问:
Host Menu Items are not visible in DotNetNUke
I am using DNN 5.2.2, host menu items are not visible on site when i click on host menu it return me blank page http://...../host.aspx
Can any let me know what is the problem.
Thanks </p>

答:
Here is the answer.(Dnn 5.6)
The following SQL scripts were run:

UPDATE Tabs SET PortalID = Null
where TabPath Like '//Host%' AND
PortalID Is Not Null

UPDATE Tabs SET ParentId = Null
where TabID=7