问:
Python loop through text and set numpy array index
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

```<code>temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]
</code>```

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

答:
Another one-liner (+1 import):</p>

```<code>from io import StringIO
rA = np.loadtxt(StringIO(matrixText.replace(';','\n')), delimiter=',')
</code>```

Body:
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

Body:
Another one-liner (+1 import):

from io import StringIO
rA = np.loadtxt(StringIO(matrixText.replace(';','\n')), delimiter=',')


来源: stackexchange

问:
Association between objects and cameras blender python
I have several objects in bpy.data.objects and several cameras in bpy.data.cameras;
The cameras are linked to some of the objects.
How can I know to which of the objects each of the cameras are linked?
I would be so grateful for a piece of code demonstrating that.
Many thanks,
Igal</p>

答:
Blender uses an object oriented approach to it's data.

The object class contains generic properties such as the location of the object. It then uses it's data property to store object specific data using a class that is specific to the type of object, each of these data types are a subclass of ID

bpy.data.objects is a list of the Object class instances.

```<code>>>> type(bpy.data.objects['Camera'])
<class 'bpy_types.Object'>
</code>```

bpy.data.cameras is a list of the Camera class instances that are linked to the camera objects data property.

```<code>>>> type(bpy.data.cameras['Camera'])
<class 'bpy.types.Camera'>
</code>```

Similarly bpy.data.meshes is a list of the Mesh class instances that contain mesh object data.

```<code>>>> type(bpy.data.objects['Cube'])
<class 'bpy_types.Object'>
>>> type(bpy.data.meshes['Cube'])
<class 'bpy_types.Mesh'>
</code>```

When first created, the object and matching data instances use matching names. While the object names are often renamed, the data names are often left alone.

```<code>import bpy

obj = bpy.data.objects['Camera']

if obj.type == 'CAMERA':
    print('The',obj.name,'object is a camera.')

if bpy.data.cameras[obj.name] == obj.data:
    print('It uses a camera data object with a matching name')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Blender uses an object oriented approach to it's data.

The object class contains generic properties such as the location of the object. It then uses it's data property to store object specific data using a class that is specific to the type of object, each of these data types are a subclass of ID

bpy.data.objects is a list of the Object class instances.

>>> type(bpy.data.objects['Camera'])
<class 'bpy_types.Object'>

bpy.data.cameras is a list of the Camera class instances that are linked to the camera objects data property.

>>> type(bpy.data.cameras['Camera'])
<class 'bpy.types.Camera'>

Similarly bpy.data.meshes is a list of the Mesh class instances that contain mesh object data.

>>> type(bpy.data.objects['Cube'])
<class 'bpy_types.Object'>
>>> type(bpy.data.meshes['Cube'])
<class 'bpy_types.Mesh'>

When first created, the object and matching data instances use matching names. While the object names are often renamed, the data names are often left alone.

import bpy

obj = bpy.data.objects['Camera']

if obj.type == 'CAMERA':
    print('The',obj.name,'object is a camera.')

if bpy.data.cameras[obj.name] == obj.data:
    print('It uses a camera data object with a matching name')


问:
Connecting Python notebook to MySQL Database
How can I connect a MySQL database to my Jupyter notebook to execute queries using Python notebook?

My code:

```<code>import pymysql
conn = MySQLdb.connect(host=dsn_hostname, port=dsn_port, user=dsn_uid, passwd=dsn_pwd, db=dsn_database)
</code>```

After establishing connection how can I start executing queries?

答: It's all written in the documentation: https://pymysql.readthedocs.io/en/latest/user/examples.html</p>

Body:
How can I connect a MySQL database to my Jupyter notebook to execute queries using Python notebook?

My code:

import pymysql
conn = MySQLdb.connect(host=dsn_hostname, port=dsn_port, user=dsn_uid, passwd=dsn_pwd, db=dsn_database)

After establishing connection how can I start executing queries?


问:
MySQL, puzzled why query is slow, have an index?
I'm puzzled why one of my queries is slow, I have indexes and I've just created a new one.

Yet its still been quite slow and appears in my slow log.

Heres my query...

```<code>  SELECT *,
         COUNT( Word ) AS WordCount
    FROM `keywords`
   WHERE `LetterIdx` = 'A'
GROUP BY Word
ORDER BY Word;
</code>```

Heres the query EXPLAIN'd

Heres my table structure and indexes.

答:
You might find it runs a lot faster like this, if you create a composite index across (LetterIdx, Word) it may help more.  This is a 2-column index instead of 2 single-column indexes

```<code>CREATE INDEX keywords_l_w on keywords(letterIdx, Word)

SELECT Word,
     COUNT( Word ) AS WordCount
FROM `keywords`
WHERE `LetterIdx` = 'A'
GROUP BY Word
ORDER BY Word;
</code>```

If my guess is correct that LetterIdx = first letter of Word, this may work even better

```<code># First create index on Word, then
SELECT Word,
     COUNT( Word ) AS WordCount
FROM `keywords`
WHERE `Word` like 'A%'
GROUP BY Word
ORDER BY Word;
</code>```

As for "I'm puzzled why one of my queries is slow, I have indexes and I've just created a new one."

It is because you have asked it to retrieve all columns of the record.  Is that really necessary? Even if it can use the index (~ 1/26 of all data), it will still need to look up the data pages to retrieve all other columns.  If you had a covering index (letteridx, word), it does not need to go back to the data.

For what it's worth, * and GROUP BY are not a good mix in a strict SQL sense.

ContentLicense: CC BY-SA 2.5

Body:
I'm puzzled why one of my queries is slow, I have indexes and I've just created a new one.

Yet its still been quite slow and appears in my slow log.

Heres my query...

  SELECT *,
         COUNT( Word ) AS WordCount
    FROM `keywords`
   WHERE `LetterIdx` = 'A'
GROUP BY Word
ORDER BY Word;

Heres the query EXPLAIN'd

Heres my table structure and indexes.

Body:
You might find it runs a lot faster like this, if you create a composite index across (LetterIdx, Word) it may help more.  This is a 2-column index instead of 2 single-column indexes

CREATE INDEX keywords_l_w on keywords(letterIdx, Word)

SELECT Word,
     COUNT( Word ) AS WordCount
FROM `keywords`
WHERE `LetterIdx` = 'A'
GROUP BY Word
ORDER BY Word;

If my guess is correct that LetterIdx = first letter of Word, this may work even better

# First create index on Word, then
SELECT Word,
     COUNT( Word ) AS WordCount
FROM `keywords`
WHERE `Word` like 'A%'
GROUP BY Word
ORDER BY Word;

As for "I'm puzzled why one of my queries is slow, I have indexes and I've just created a new one."

It is because you have asked it to retrieve all columns of the record.  Is that really necessary? Even if it can use the index (~ 1/26 of all data), it will still need to look up the data pages to retrieve all other columns.  If you had a covering index (letteridx, word), it does not need to go back to the data.

For what it's worth, * and GROUP BY are not a good mix in a strict SQL sense.


问:
How to split header, footer and table body into pages in specific way in Jasperreports
pals!

I have a very special requirements for my report. Let's look at report at first:

```<code>___________
|         |
| header  |
|         |
| row     |
| row     |
| row     |
| footer  |
| footer  |
|_________|
</code>```

This is my typical page in perfect case with all rows, header and footer on same page. Sometimes I have too many rows for one page and my report looks like this:

```<code>__________
|        |
| header |
|        |
| row    |
| row    |
| row    |
| row    |
| row    |
|________|

__________
| row    |
| row    |
| row    |
| row    |
| row    |
| row    |
| row    |
| footer |
|________|

__________
| footer |
|        |
|        |
|        |
|        |
|        |
|        |
|        |
|________|
</code>```

And I can't just insert splitter between last row and footer because my requirements is:
- Headers page must have at least one row
- Footers page must have at least one row

So, I can' find solution to this problem. My footer can be splitted in two pages. My footer can be without rows and this is very bad for printing XLS file. I can use PDF instesad of XLS, but I have same problems. Does anybody have ideas how to solve this problem?

-----=== UPDATE ===-----

So, mr. dada67 provides great solution. We can put group into document and group will do what we need with expression = '1' (Looks like we select all elements). But there are some update to my question.

What if my every row is and subreport with some rows inside? When I use group in master report, Jasper process my every subreport with all his rows as an single row. Can I force Jasper to think that single element is not an whole subreport element but a single row from subreport?

-----=== UPDATE 2 ===-----

So, solution is here. When you need to move last row of your last subreport to next page with some footer - you just need to create group inside subreport with espression = '1' (to gather all rows) and settings from correct answer from dada67. This force jasper to draw footer after every subreport, but you can hide footer in all subreports except last.

Thanks to dada67!

答:
JasperReports 6.4.3 introduced two new group attributes called minDetailsToStartFromTop and preventOrphanFooter which are used to specify if group headers and footer need to be accompanied by one detail band (or more in the case of headers).

So you can create a group in the report with a constant expression, set the two attributes and use the group header and footer band(s).

As in

```<code><group name="Group" minDetailsToStartFromTop="1" preventOrphanFooter="true">
    <groupExpression><![CDATA[1]]></groupExpression>
    <groupHeader>
        ...
    </groupHeader>
    <groupFooter>
        ...
    </groupFooter>
</group>
</code>```

Body:
pals!

I have a very special requirements for my report. Let's look at report at first:

___________
|         |
| header  |
|         |
| row     |
| row     |
| row     |
| footer  |
| footer  |
|_________|

This is my typical page in perfect case with all rows, header and footer on same page. Sometimes I have too many rows for one page and my report looks like this:

__________
|        |
| header |
|        |
| row    |
| row    |
| row    |
| row    |
| row    |
|________|

__________
| row    |
| row    |
| row    |
| row    |
| row    |
| row    |
| row    |
| footer |
|________|

__________
| footer |
|        |
|        |
|        |
|        |
|        |
|        |
|        |
|________|

And I can't just insert splitter between last row and footer because my requirements is:
- Headers page must have at least one row
- Footers page must have at least one row

So, I can' find solution to this problem. My footer can be splitted in two pages. My footer can be without rows and this is very bad for printing XLS file. I can use PDF instesad of XLS, but I have same problems. Does anybody have ideas how to solve this problem?

-----=== UPDATE ===-----

So, mr. dada67 provides great solution. We can put group into document and group will do what we need with expression = '1' (Looks like we select all elements). But there are some update to my question.

What if my every row is and subreport with some rows inside? When I use group in master report, Jasper process my every subreport with all his rows as an single row. Can I force Jasper to think that single element is not an whole subreport element but a single row from subreport?

-----=== UPDATE 2 ===-----

So, solution is here. When you need to move last row of your last subreport to next page with some footer - you just need to create group inside subreport with espression = '1' (to gather all rows) and settings from correct answer from dada67. This force jasper to draw footer after every subreport, but you can hide footer in all subreports except last.

Thanks to dada67!

Body:
JasperReports 6.4.3 introduced two new group attributes called minDetailsToStartFromTop and preventOrphanFooter which are used to specify if group headers and footer need to be accompanied by one detail band (or more in the case of headers).

So you can create a group in the report with a constant expression, set the two attributes and use the group header and footer band(s).

As in

<group name="Group" minDetailsToStartFromTop="1" preventOrphanFooter="true">
    <groupExpression><![CDATA[1]]></groupExpression>
    <groupHeader>
        ...
    </groupHeader>
    <groupFooter>
        ...
    </groupFooter>
</group>


问:
How to print environment variables on Heroku?
I'd like to print all environment variables set on my Heroku server. How can I do that with command line only?</p>

答:
Ok, I found the way:</p>
```<code>heroku config
</code>```

Body:
Ok, I found the way:

heroku config

ContentLicense: CC BY-SA 4.0


问:
Modify global value from a onSuccess call?
I am using this function from the aws Cognito docs.

```<code>cognitoUser.forgotPassword({
    onSuccess: function (result) {
        console.log('call result: ' + result);
    },
    onFailure: function(err) {
        alert(err);
    },
    inputVerificationCode() {
        var verificationCode = prompt('Please input verification code ','');
        var newPassword = prompt('Enter new password ' ,'');
        cognitoUser.confirmPassword(verificationCode, newPassword, this);
    }
});
</code>```

Instead of using a prompt, I want to display or not 2 field in HTML so the user can fill them in place of having 2 ugly prompt. All I need to do is replacing the function calling the prompts by a function changing a boolean value.

I tried this: (for some reason, I had to call changevalue() inside the onsuccess or it wouldn't execute)

```<code>cognitoconstruct.forgotPassword({
  onSuccess: function (result) {
    console.log('call result: ' + result);
    this.changevalue()
  }, onFailure: function (err) {
    alert(err);
  }, changevalue() {
    console.log('display', this.display)
    this.display = true;
  }
})
</code>```

However, you guessed it: this.display being undefined in this function, it doesn't change outside. I can't call any variable or function with this.xxx.
How can change this value ?

I tried adding a .then() or change the function to use a legit callback but no luck.

edit: I also tried this: onSuccess: this.changevalue(), the boolean do change value but the whole thing crash  soon after e.onSuccess is not a function

答:
it seem my brain have a surge of creativity after asking a question here  -_-

I placed the whole function calling forgotPassword() in a promise and used a good old callback to switch the value...

```<code>recoverPassword() {
  return new Promise((resolve, reject) => {
   let cognitoconstruct = this.user.recover_password(this.forgot_password.value.email);
   cognitoconstruct.forgotPassword({
     onSuccess: function (result) {
       resolve()
     }, onFailure: function (err) {
       alert(err);
       reject();
     }
   })
 })
}
</code>```

```<code>this.recoverPassword().then(() => this.display = true)
</code>```

Body:
I am using this function from the aws Cognito docs.

cognitoUser.forgotPassword({
    onSuccess: function (result) {
        console.log('call result: ' + result);
    },
    onFailure: function(err) {
        alert(err);
    },
    inputVerificationCode() {
        var verificationCode = prompt('Please input verification code ','');
        var newPassword = prompt('Enter new password ' ,'');
        cognitoUser.confirmPassword(verificationCode, newPassword, this);
    }
});

Instead of using a prompt, I want to display or not 2 field in HTML so the user can fill them in place of having 2 ugly prompt. All I need to do is replacing the function calling the prompts by a function changing a boolean value.

I tried this: (for some reason, I had to call changevalue() inside the onsuccess or it wouldn't execute)

cognitoconstruct.forgotPassword({
  onSuccess: function (result) {
    console.log('call result: ' + result);
    this.changevalue()
  }, onFailure: function (err) {
    alert(err);
  }, changevalue() {
    console.log('display', this.display)
    this.display = true;
  }
})

However, you guessed it: this.display being undefined in this function, it doesn't change outside. I can't call any variable or function with this.xxx.
How can change this value ?

I tried adding a .then() or change the function to use a legit callback but no luck.

edit: I also tried this: onSuccess: this.changevalue(), the boolean do change value but the whole thing crash  soon after e.onSuccess is not a function

Body:
it seem my brain have a surge of creativity after asking a question here  -_-

I placed the whole function calling forgotPassword() in a promise and used a good old callback to switch the value...

recoverPassword() {
  return new Promise((resolve, reject) => {
   let cognitoconstruct = this.user.recover_password(this.forgot_password.value.email);
   cognitoconstruct.forgotPassword({
     onSuccess: function (result) {
       resolve()
     }, onFailure: function (err) {
       alert(err);
       reject();
     }
   })
 })
}

this.recoverPassword().then(() => this.display = true)


问:
Dividing a bag of mixed candy
Assuming I have a bag of candy Ci with N pieces of candy. It's a mix of t different types of candy, Ti. I want to share it between my M friends.

Each of them has a preference for each type of candy, P(m,Ti) where m is one of the M friends. P(m,Ti) is an integer and distinct, and the sum of P(m,T) for each friend is 50 (each friend distributes 50 points as he wishes between the candy types, with no types getting the same amount of points).

We want to divide the N pieces of candy between all the m friends in such a way that everybody is pleased. All the candy needs to be divided. Each person does not need to be given the same amount of candy.

1) Is there any way to objectively reach a solution for the "perfect" way to divide the candy?

Assuming the answer to (1) is "no", we will define it as follows. Sm is sum[P(m,Tj)], where j is subset of i that m is given. The definition of the optimal solution is the distribution with the lowest possible standard deviation of Sm with highest possible average Sm as tie breaker.

2) What is the best way to approach this problem? Is there any known algorithms?

答:
Firstly I'd consider whether you model the problem such that you can apply a version of "the Hungarian Algorithm" to it. Even if not, that could be a useful start point to search for similar approaches.

As a heuristic approach I'd suggest you be better allocating not in a fixed order but in terms of who is least happy with the sweets they have so far and by
trying to order the people in terms of how hard they are to please (for example someone who allocates most of their 50 points to one type is going to be hard to please, especially if there aren't many of that type of sweets).

Title: Dividing a bag of mixed candy


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
It depends on the encoding of your string (ASCII, UTF-8, ...).

For example:

```<code>byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);
</code>```

A small sample why encoding matters:

```<code>string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'
</code>```

ASCII simply isn't equipped to deal with special characters.

Internally, the .NET framework uses UTF-16 to represent strings, so if you simply want to get the exact bytes that .NET uses, use System.Text.Encoding.Unicode.GetBytes (...).

See Character Encoding in the .NET Framework (MSDN) for more information.

OwnerDisplayName: Vulcan Eager

LastEditorDisplayName: Dale Ragan

Body:
It depends on the encoding of your string (ASCII, UTF-8, ...).

For example:

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

A small sample why encoding matters:

string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'

ASCII simply isn't equipped to deal with special characters.

Internally, the .NET framework uses UTF-16 to represent strings, so if you simply want to get the exact bytes that .NET uses, use System.Text.Encoding.Unicode.GetBytes (...).

See Character Encoding in the .NET Framework (MSDN) for more information.

OwnerDisplayName: bmotmans

LastEditorDisplayName: bmotmans


问:
Why is my data set being shortened when I page in my asp gridview?
Its a standard gridview:

```<code><asp:GridView runat="server" ID="gvAlerts" AutoGenerateColumns="false"
    DataKeyNames="Id" CssClass="table table-striped table-bordered table-hover"
    OnRowDataBound="gvAlerts_RowDataBound"
    OnSelectedIndexChanging="gvAlerts_SelectedIndexChanging"
    OnRowDeleting="gvAlerts_RowDeleting"
    EmptyDataText="There are no alerts to manage."
    PageSize="10" AllowPaging="true"
    PagerSettings-Position="TopAndBottom"
    PagerSettings-Visible="true"
    PagerSettings-Mode="NumericFirstLast"
    OnPageIndexChanging="gvAlerts_PageIndexChanging">
    <Columns>
        <asp:BoundField HeaderText="" DataField="ContractEntity"
            SortExpression="Supplier" />
        <asp:BoundField HeaderText="Reference" DataField="Reference"
            SortExpression="Reference" />
        <asp:BoundField HeaderText="Date" DataField="Date"
            SortExpression="Date" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:BoundField HeaderText="Contact Person" DataField="Username"
            SortExpression="Username" />
        <asp:BoundField HeaderText="End Date" DataField="EndDate"
            SortExpression="EndDate" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:BoundField HeaderText="Value" DataField="Value"
            SortExpression="Value" DataFormatString="R{0:# ### ###.00}" />
        <asp:BoundField HeaderText="Category" DataField="ContractCategory"
            SortExpression="Category" />
        <asp:CommandField ShowSelectButton="true" SelectText="<i class='glyphicon glyphicon-pencil'></i>" />
        <asp:CommandField ShowDeleteButton="true" DeleteText="<i class='glyphicon glyphicon-trash'></i>" />
    </Columns>
</asp:GridView>
</code>```

I can't seem to get the paging working right though.

In the code below I've limited the data to 80 records (for testing purposes). It appears that the data does actually page over when I go to a different page, but that's not all it does; there is also always less data returned every time until eventually paging is no longer possible because there aren't enough records to bind to the gridview.

```<code>private List<Alert> _alerts { get; set; }

protected void gvAlerts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvAlerts.PageIndex = e.NewPageIndex;

    try
    {
        PageData(e.NewPageIndex);
    }
    catch (ArgumentNullException ane)
    {
        // Get all Alerts data again since the collection was apparently
        // emptied on postback.
        _alerts = GetAlerts();
        PageData(e.NewPageIndex);
    }
}

private void PageData(int pageIndex)
{
    List<Alert> alerts = _alerts;
    if (pageIndex >= 2)
    {
        alerts = _alerts.Skip(pageIndex * gvAlerts.PageSize).Take(gvAlerts.PageSize).ToList();
    }

    gvAlerts.DataSource = BuildGridViewModel(alerts);
    gvAlerts.DataBind();
}

private List<AlertListViewModel> BuildGridViewModel(List<Alert> alerts)
{
    var model = new List<AlertListViewModel>();
    var u = HttpContext.Current.User.Identity;

    using (var db = new ApplicationDbContext())
    {
        foreach (Alert alert in alerts)
        {
            // Due to poor database design, these queries are unavoidable.
            var contract = db.Contracts.FirstOrDefault(x => x.Id == alert.ContractId);
            var category = db.Categories.FirstOrDefault(x => x.Id == contract.CategoryId).Name;
            var entity = db.ContractEntities.FirstOrDefault(x => x.Id == contract.ContractEntityId).Name;

            model.Add(new AlertListViewModel
            {
                // Map model properties.
            });
        }
    }
    return model;
}
</code>```

I understand that the .Skip() and .Take() are probably what's shortening the data set but without those, how am I to change the data that is currently visible on the gridview?

I'm missing something here. What is it? How do I get this gridview paging without losing any data?

答:
The downside of the GridVIew is that all the records are retrieved every time and/or all stored in ViewState. So if you want to use Linq create your own paging method. Below a quick example of how this can be done.
If you still want to use the build-in paging, follow the comment of InitLipton

```<code>List<Book> books;
int pageSize = 10;

protected void Page_Load(object sender, EventArgs e)
{
    //fill the collection
    books = fillBooks();

    //create the dynamic pager buttons, this needs to be done on every page load
    createPager();

    //bind the grid for the first time without postback
    if (!IsPostBack)
    {
        bindGrid(0);
    }
}

private void bindGrid(int offSet)
{
    //bind the right amount of items to the grid
    GridView1.DataSource = books.Skip(offSet).Take(pageSize).ToList();
    GridView1.DataBind();
}

private void createPager()
{
    //loop for every x items in the collection
    for (int i = 0; i < (books.Count / pageSize); i++)
    {
        //create a linkbutton
        LinkButton lb = new LinkButton();

        //add the properties
        lb.Text = (i + 1).ToString();
        lb.CommandArgument = i.ToString();

        //bind the command method
        lb.Command += Lb_Command;

        //add the linkbutton to the page
        PlaceHolder1.Controls.Add(lb);

        //add some spacing
        PlaceHolder1.Controls.Add(new Literal() { Text = " " });
    }
}

private void Lb_Command(object sender, CommandEventArgs e)
{
    //rebind the grid with the next 10 items
    bindGrid(Convert.ToInt32(e.CommandArgument) * 10);
}
</code>```

And the aspx

```<code><asp:GridView ID="GridView1" runat="server" EnableViewState="false"></asp:GridView>
<br />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</code>```

Body:
Its a standard gridview:

<asp:GridView runat="server" ID="gvAlerts" AutoGenerateColumns="false"
    DataKeyNames="Id" CssClass="table table-striped table-bordered table-hover"
    OnRowDataBound="gvAlerts_RowDataBound"
    OnSelectedIndexChanging="gvAlerts_SelectedIndexChanging"
    OnRowDeleting="gvAlerts_RowDeleting"
    EmptyDataText="There are no alerts to manage."
    PageSize="10" AllowPaging="true"
    PagerSettings-Position="TopAndBottom"
    PagerSettings-Visible="true"
    PagerSettings-Mode="NumericFirstLast"
    OnPageIndexChanging="gvAlerts_PageIndexChanging">
    <Columns>
        <asp:BoundField HeaderText="" DataField="ContractEntity"
            SortExpression="Supplier" />
        <asp:BoundField HeaderText="Reference" DataField="Reference"
            SortExpression="Reference" />
        <asp:BoundField HeaderText="Date" DataField="Date"
            SortExpression="Date" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:BoundField HeaderText="Contact Person" DataField="Username"
            SortExpression="Username" />
        <asp:BoundField HeaderText="End Date" DataField="EndDate"
            SortExpression="EndDate" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:BoundField HeaderText="Value" DataField="Value"
            SortExpression="Value" DataFormatString="R{0:# ### ###.00}" />
        <asp:BoundField HeaderText="Category" DataField="ContractCategory"
            SortExpression="Category" />
        <asp:CommandField ShowSelectButton="true" SelectText="" />
        <asp:CommandField ShowDeleteButton="true" DeleteText="" />
    </Columns>
</asp:GridView>

I can't seem to get the paging working right though.

In the code below I've limited the data to 80 records (for testing purposes). It appears that the data does actually page over when I go to a different page, but that's not all it does; there is also always less data returned every time until eventually paging is no longer possible because there aren't enough records to bind to the gridview.

private List<Alert> _alerts { get; set; }

protected void gvAlerts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvAlerts.PageIndex = e.NewPageIndex;

    try
    {
        PageData(e.NewPageIndex);
    }
    catch (ArgumentNullException ane)
    {
        // Get all Alerts data again since the collection was apparently
        // emptied on postback.
        _alerts = GetAlerts();
        PageData(e.NewPageIndex);
    }
}

private void PageData(int pageIndex)
{
    List<Alert> alerts = _alerts;
    if (pageIndex >= 2)
    {
        alerts = _alerts.Skip(pageIndex * gvAlerts.PageSize).Take(gvAlerts.PageSize).ToList();
    }

    gvAlerts.DataSource = BuildGridViewModel(alerts);
    gvAlerts.DataBind();
}

private List<AlertListViewModel> BuildGridViewModel(List<Alert> alerts)
{
    var model = new List<AlertListViewModel>();
    var u = HttpContext.Current.User.Identity;

    using (var db = new ApplicationDbContext())
    {
        foreach (Alert alert in alerts)
        {
            // Due to poor database design, these queries are unavoidable.
            var contract = db.Contracts.FirstOrDefault(x => x.Id == alert.ContractId);
            var category = db.Categories.FirstOrDefault(x => x.Id == contract.CategoryId).Name;
            var entity = db.ContractEntities.FirstOrDefault(x => x.Id == contract.ContractEntityId).Name;

            model.Add(new AlertListViewModel
            {
                // Map model properties.
            });
        }
    }
    return model;
}

I understand that the .Skip() and .Take() are probably what's shortening the data set but without those, how am I to change the data that is currently visible on the gridview?

I'm missing something here. What is it? How do I get this gridview paging without losing any data?

Body:
The downside of the GridVIew is that all the records are retrieved every time and/or all stored in ViewState. So if you want to use Linq create your own paging method. Below a quick example of how this can be done.
If you still want to use the build-in paging, follow the comment of InitLipton

List<Book> books;
int pageSize = 10;

protected void Page_Load(object sender, EventArgs e)
{
    //fill the collection
    books = fillBooks();

    //create the dynamic pager buttons, this needs to be done on every page load
    createPager();

    //bind the grid for the first time without postback
    if (!IsPostBack)
    {
        bindGrid(0);
    }
}

private void bindGrid(int offSet)
{
    //bind the right amount of items to the grid
    GridView1.DataSource = books.Skip(offSet).Take(pageSize).ToList();
    GridView1.DataBind();
}

private void createPager()
{
    //loop for every x items in the collection
    for (int i = 0; i < (books.Count / pageSize); i++)
    {
        //create a linkbutton
        LinkButton lb = new LinkButton();

        //add the properties
        lb.Text = (i + 1).ToString();
        lb.CommandArgument = i.ToString();

        //bind the command method
        lb.Command += Lb_Command;

        //add the linkbutton to the page
        PlaceHolder1.Controls.Add(lb);

        //add some spacing
        PlaceHolder1.Controls.Add(new Literal() { Text = "&nbsp;" });
    }
}

private void Lb_Command(object sender, CommandEventArgs e)
{
    //rebind the grid with the next 10 items
    bindGrid(Convert.ToInt32(e.CommandArgument) * 10);
}

And the aspx

<asp:GridView ID="GridView1" runat="server" EnableViewState="false"></asp:GridView>
<br />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>


问:
Conditional wont be read in do while statement
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated. </p>

```<code>import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here
</code>```

答:
You have a few problems here:

```<code>String answer = kbReader.next();
} while (answer == 'y'); // error received here
</code>```

Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.

This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".

Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.

You could do something like:

```<code>case 30:
case 31:
case 32: // ...
</code>```

but that seems like a thoroughly painful way to do that. See also this question for more details.

This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:

```<code>switch ((int) num/10) {
    case 1:
        System.out.println("10-19");
        break;
    case 2:
        System.out.println("20-29");
        break;
    case 3:
        System.out.println("30-39");
        break;
    case 4:
        System.out.println("40-49");
        break;
    default:
        break;
}
</code>```

(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).

Also:

```<code>int studentNumber = kbReader.nextInt();
</code>```

You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?

Body:
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.

import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here

Body:
You have a few problems here:

String answer = kbReader.next();
} while (answer == 'y'); // error received here

Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.

This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".

Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.

You could do something like:

case 30:
case 31:
case 32: // ...

but that seems like a thoroughly painful way to do that. See also this question for more details.

This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:

switch ((int) num/10) {
    case 1:
        System.out.println("10-19");
        break;
    case 2:
        System.out.println("20-29");
        break;
    case 3:
        System.out.println("30-39");
        break;
    case 4:
        System.out.println("40-49");
        break;
    default:
        break;
}

(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).

Also:

int studentNumber = kbReader.nextInt();

You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?


问:
Re-use Query Parts in T-SQL
I have a very complicated stored procedure that repeats a very complicated query with different where clauses based on certain values passed in.  The stored procedure takes up over 500 lines of code, with the common part of the query taking up just over 100 lines.  That common part is repeated 3 times.

I originally thought to use CTE (Common Table Expressions) except in T-SQL you can't define the common part, do your IF statement and then apply the WHERE clause.  That's essentially what I need.

As a workaround I created a view for the common code, but it's only used in one stored procedure.

Is there any way to do this without creating a full view or temp tables?

Ideally I would like to do something like this:

```<code>WITH SummaryCTE (col1, col2, col3...)
AS
(
    SELECT concat("Pending Attachments - ", ifnull(countCol1, 0)) col1
    -- all the rest of the stuff
    FROM x as y
    LEFT JOIN attachments z on z.attachmentId = x.attachmentId
    -- and more complicated stuff
)

IF (@originatorId = @userId)
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- handle this security case
END
ELSE IF (@anotherCondition = 1)
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- a different where clause
END
ELSE
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- the generic case
END
</code>```

Hopefully the pseudo code gives you an idea of what I would like.  Right now my workaround is to create a view for the contents of what I defined SummaryCTE as, and then handle the IF/ELSE IF/ELSE clause.  Executing this structure will throw an error at the first IF statement because the next command is supposed to be a SELECT instead.  At least in T-SQL.

Maybe this doesn't exist in any other way, but I wanted to know for sure.

答:
Well, aside from the temp tables and views that you've identified, you could go with dynamic SQL to build the code then execute it.  This keeps you from having to repeat code, but makes it a bit hard to just deal with.  Like this:

```<code>declare @sql varchar(max) = 'with myCTE (col1, col2) as ( select * from myTable) select * from myCTE'

if (@myVar = 1)
begin
    @sql = @sql + ' where col1 = 2'
end
else if (@myVar = 2)
begin
    @sql = @sql + ' where col2 = 4'
end
-- ...

exec @sql
</code>```

Another option would be to incorporate your different where clauses into the original query.

```<code>WITH SummaryCTE (col1, col2, col3...)
AS
(
    SELECT concat("Pending Attachments - ", ifnull(countCol1, 0)) col1
    -- all the rest of the stuff
    FROM x as y
    LEFT JOIN attachments z on z.attachmentId = x.attachmentId
    -- and more complicated stuff
)
select *
from SummaryCTE
where
(
    -- this was your first if
    @originatorId = @userId
    and ( whatever you do for your security case )
)
or
(
    -- this was your second branch
    @anotherCondition = 1
    and ( handle another case here )
)
or
-- etc. etc.
</code>```

This eliminates the if/else chain but makes the query more complicated.  It also can cause some bad cached query plans because of parameter sniffing, but that may not matter much depending on your data.  Test that before making a decision.  (You can also add optimizer hints to not cache the query plan.  You won't get a bad one, but you also take a hit on every execution to create the query plan again.  Test to find out, don't guess.  Also, a solution with a view and the if/else chain will suffer from the same parameter sniffing/cached query plan problem.)

Title: Re-use Query Parts in T-SQL

Body:
I have a very complicated stored procedure that repeats a very complicated query with different where clauses based on certain values passed in.  The stored procedure takes up over 500 lines of code, with the common part of the query taking up just over 100 lines.  That common part is repeated 3 times.

I originally thought to use CTE (Common Table Expressions) except in T-SQL you can't define the common part, do your IF statement and then apply the WHERE clause.  That's essentially what I need.

As a workaround I created a view for the common code, but it's only used in one stored procedure.

Is there any way to do this without creating a full view or temp tables?

Ideally I would like to do something like this:

WITH SummaryCTE (col1, col2, col3...)
AS
(
    SELECT concat("Pending Attachments - ", ifnull(countCol1, 0)) col1
    -- all the rest of the stuff
    FROM x as y
    LEFT JOIN attachments z on z.attachmentId = x.attachmentId
    -- and more complicated stuff
)

IF (@originatorId = @userId)
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- handle this security case
END
ELSE IF (@anotherCondition = 1)
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- a different where clause
END
ELSE
BEGIN
    SELECT * FROM SummaryCTE
    WHERE
       -- the generic case
END

Hopefully the pseudo code gives you an idea of what I would like.  Right now my workaround is to create a view for the contents of what I defined SummaryCTE as, and then handle the IF/ELSE IF/ELSE clause.  Executing this structure will throw an error at the first IF statement because the next command is supposed to be a SELECT instead.  At least in T-SQL.

Maybe this doesn't exist in any other way, but I wanted to know for sure.

Body:
Well, aside from the temp tables and views that you've identified, you could go with dynamic SQL to build the code then execute it.  This keeps you from having to repeat code, but makes it a bit hard to just deal with.  Like this:

declare @sql varchar(max) = 'with myCTE (col1, col2) as ( select * from myTable) select * from myCTE'

if (@myVar = 1)
begin
    @sql = @sql + ' where col1 = 2'
end
else if (@myVar = 2)
begin
    @sql = @sql + ' where col2 = 4'
end
-- ...

exec @sql

Another option would be to incorporate your different where clauses into the original query.

WITH SummaryCTE (col1, col2, col3...)
AS
(
    SELECT concat("Pending Attachments - ", ifnull(countCol1, 0)) col1
    -- all the rest of the stuff
    FROM x as y
    LEFT JOIN attachments z on z.attachmentId = x.attachmentId
    -- and more complicated stuff
)
select *
from SummaryCTE
where
(
    -- this was your first if
    @originatorId = @userId
    and ( whatever you do for your security case )
)
or
(
    -- this was your second branch
    @anotherCondition = 1
    and ( handle another case here )
)
or
-- etc. etc.

This eliminates the if/else chain but makes the query more complicated.  It also can cause some bad cached query plans because of parameter sniffing, but that may not matter much depending on your data.  Test that before making a decision.  (You can also add optimizer hints to not cache the query plan.  You won't get a bad one, but you also take a hit on every execution to create the query plan again.  Test to find out, don't guess.  Also, a solution with a view and the if/else chain will suffer from the same parameter sniffing/cached query plan problem.)


问:
Yii2 register mix of JS Files and Inline JS in order
I'm trying to register the following from the Google Analytics docs:

```<code><!-- Google Analytics -->
<script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
</code>```

So I did the following in my widget:

```<code>$this->view->registerJs('
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga(\'create\', \'UA-XXXXX-Y\', \'auto\');
    ga(\'send\', \'pageview\');
', View::POS_HEAD);

$this->view->registerJsFile(
    'https://www.google-analytics.com/analytics.js',
    [
       'async'=>'async',
       'position' => View::POS_HEAD,
    ]
);
</code>```

But the registered JS File came out BEFORE the Inline JS. Is there a way to get the scripts to respect the order?

I thought about using an AssetBundle and the 'depends' protocol, but there's nothing in the Yii2 Docs about Inline JS in an AssetBundle.

You can give the Inline JS a key, but sadly the 'depends' protocol requires a class name.

答: Unfortunately, the only easy way to do this is by not using AssetBundle in this particular case and manually embed the code in your partial/layout file, after<?php $this->head() ?>

Body:
I'm trying to register the following from the Google Analytics docs:

So I did the following in my widget:

$this->view->registerJs('
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga(\'create\', \'UA-XXXXX-Y\', \'auto\');
    ga(\'send\', \'pageview\');
', View::POS_HEAD);

$this->view->registerJsFile(
    'https://www.google-analytics.com/analytics.js',
    [
       'async'=>'async',
       'position' => View::POS_HEAD,
    ]
);

But the registered JS File came out BEFORE the Inline JS. Is there a way to get the scripts to respect the order?

I thought about using an AssetBundle and the 'depends' protocol, but there's nothing in the Yii2 Docs about Inline JS in an AssetBundle.

You can give the Inline JS a key, but sadly the 'depends' protocol requires a class name.


问:
How Entity Framework 4 domain mapping work exactly?
I know Linq to SQL work such as setting META attributes around your model. What i am looking to do is building my model then setting this model to work with EF 4.

Are the same approach working with EF 4 ?

Is this called the Code-First approach or its totally something else ?

Ive done some research but i can't seem to figure out how exactly to map a domain to work with EF 4. This include keys/relations integrity.

I would love to see a simple code example with some explanations.

Thanks.

答:
Model-first development allows you to build the model in the designer, then generate the database based on that model.  Code-first allows  you to generate the database based on your code, or use the code to work with an existing database too.

Both those options are viable; for code-first, V5 has a lot of improvements you will want to look out for.

HTH.


问:
How can a time function exist in functional programming?
I've to admit that I don't know much about functional programming. I read about it from here and there, and so came to know that in functional programming, a function returns the same output, for same input, no matter how many times the function is called. It's exactly like a mathematical function which evaluates to the same output for the same value of the input parameters which involves in the function expression.

For example, consider this:

```<code>f(x,y) = x*x + y; // It is a mathematical function
</code>```

No matter how many times you use f(10,4), its value will always be 104. As such, wherever you've written f(10,4), you can replace it with 104, without altering the value of the whole expression. This property is referred to as referential transparency of an expression.

As Wikipedia says (link),

Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times.

Can a time function (which returns the current time) exist in functional programming?

If yes, then how can it exist? Does it not violate the principle of functional programming? It particularly violates referential transparency which is one of the property of functional programming (if I correctly understand it).

Or if no, then how can one know the current time in functional programming?

答:
If yes, then how can it exist? Does it not violate the principle of
  functional programming? It particularly violates referential
  transparency

It does not exist in a purely functional sense.

Or if no, then how can one know the current time in functional
  programming?

It may first be useful to know how a time is retrieved on a computer. Essentially there is onboard circuitry that keeps track of the time (which is the reason a computer would usually need a small cell battery). Then there might be some internal process that sets the value of time at a certain memory register. Which essentially boils down to a value that can be retrieved by the CPU.

For Haskell, there is a concept of an 'IO action'  which represents a type that can be made to carry out some IO process. So instead of referencing a time value we reference a IO Time value. All this would be purely functional. We aren't referencing time but something along the lines of 'read the value of the time register'.

When we actually execute the Haskell program, the IO action would actually take place.

Body:
I've to admit that I don't know much about functional programming. I read about it from here and there, and so came to know that in functional programming, a function returns the same output, for same input, no matter how many times the function is called. It's exactly like a mathematical function which evaluates to the same output for the same value of the input parameters which involves in the function expression.

For example, consider this:

f(x,y) = x*x + y; // It is a mathematical function

No matter how many times you use f(10,4), its value will always be 104. As such, wherever you've written f(10,4), you can replace it with 104, without altering the value of the whole expression. This property is referred to as referential transparency of an expression.

As Wikipedia says (link),

Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times.

Can a time function (which returns the current time) exist in functional programming?

If yes, then how can it exist? Does it not violate the principle of functional programming? It particularly violates referential transparency which is one of the property of functional programming (if I correctly understand it).

Or if no, then how can one know the current time in functional programming?


问:
Open Word Document and Bring to Front
Below is a working code snippet that opens a Microsoft Word document, and goes to a specific index from the Table of Contents. filePath is a filepath, and strTopic is a value that links to the Table of Contents in the Word document.

```<code>Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=True)

docWord.Bookmarks(strTopic).Range.Select
</code>```

I need to bring the Word document to the foreground.

Is there a toFront() type "function" in VBA?

答:
This seems to work every time. Word running or not, multiple docs open or not.</p>

```<code>OpenAlready:

On Error GoTo 0
With wrdApp
    .Selection.Goto What:=1, Which:=2, Name:=PageNumber
    .Visible = True
    .Activate '<---seems to work well. regardless of number of Word docs open OR not open.
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
</code>```

Title: Open Word Document and Bring to Front

Body:
Below is a working code snippet that opens a Microsoft Word document, and goes to a specific index from the Table of Contents. filePath is a filepath, and strTopic is a value that links to the Table of Contents in the Word document.

Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=True)

docWord.Bookmarks(strTopic).Range.Select

I need to bring the Word document to the foreground.

Is there a toFront() type "function" in VBA?

Body:
This seems to work every time. Word running or not, multiple docs open or not.

OpenAlready:

On Error GoTo 0
With wrdApp
    .Selection.Goto What:=1, Which:=2, Name:=PageNumber
    .Visible = True
    .Activate '<---seems to work well. regardless of number of Word docs open OR not open.
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing


问:
SSRS Predicament with expressions
I have an SSRS dataset that looks like this:

The dataset rows are generated independent of each other using UNION ALL.
I need to display these rows in my report as is, but I need to add an additional row that will calculate Total Won / Total Lost, so the result should look like this:

This is just sample as I have more columns (1 per month) and the whole thing is broken down by product, so if I have 10 different products, I will have 10 different tablix tables.

Basically I need to somehow create an expression that will only calculate values in 2 rows of the tablix out of 3 (based on the value of the Status column) and take into consideration that some values can be zeroes.

Here's the query (I simplified it a bit for better understanding):

```<code>select * from
(
select 'Created' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
) created
pivot
(
count(created.opportunityid)
for created.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivCreated
union all
select * from
(
select 'Won' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and regionalfeeincome >= 250000
and fo.jna is not null
) won
pivot
(
count(won.opportunityid)
for won.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivWon
union all
select * from
(
select 'Lost' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
and fo.sys_phasename <> 'Pre-Bid'
) lost
pivot
(
count(lost.opportunityid)
for lost.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivLost
</code>```

TIA
-TS.

答:
I can't fully test this as I don't have time to build sample data but it should work...

If you use this as your report's dataset query then you should be able to add a simple matrix with a row group by State and a column group by City

```<code>/*
You can optimise this a bit but I've kept it fairly procedural so it's easier to follow
*/
-- First do your 3 basic queries but this time we don't pivot and we dump the results into temp tables
-- I've also removed columns that don't appear to be used based on your sample output and remaned a column to City to make it easier to read
select 'Total Created' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Created
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000

select 'Total Won' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Won
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000
        and fo.jna is not null

select 'Total Lost' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Lost
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000
        and fo.sys_phasename <> 'Pre-Bid'

-- Now we calculate your Ratio
SELECT
    'Win Ratio' as 'State'
    , coalesce(w.City, l.City) as City -- use coalesce in case 1 side of join is null
    , CASE WHEN ISNULL(l.cnt,0) = 0 THEN 0 ELSE w.Cnt/l.Cnt END as Cnt -- if lost is null or 0 return 0 else calc ratio
into #Ratio
 FROM #Won w
    full join #Lost l on w.City = l.City

-- finaly, get the results and add a sort to help the report row sorting.
SELECT 1 as Sort, * FROM #Created
UNION SELECT 2, * FROM #Won
UNION SELECT 3, * FROM #Lost
UNION SELECT 4, * FROM #Ratio
</code>```

Title: SSRS Predicament with expressions

Body:
I have an SSRS dataset that looks like this:

The dataset rows are generated independent of each other using UNION ALL.
I need to display these rows in my report as is, but I need to add an additional row that will calculate Total Won / Total Lost, so the result should look like this:

This is just sample as I have more columns (1 per month) and the whole thing is broken down by product, so if I have 10 different products, I will have 10 different tablix tables.

Basically I need to somehow create an expression that will only calculate values in 2 rows of the tablix out of 3 (based on the value of the Status column) and take into consideration that some values can be zeroes.

Here's the query (I simplified it a bit for better understanding):

select * from
(
select 'Created' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
) created
pivot
(
count(created.opportunityid)
for created.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivCreated
union all
select * from
(
select 'Won' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and regionalfeeincome >= 250000
and fo.jna is not null
) won
pivot
(
count(won.opportunityid)
for won.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivWon
union all
select * from
(
select 'Lost' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
and fo.sys_phasename <> 'Pre-Bid'
) lost
pivot
(
count(lost.opportunityid)
for lost.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivLost

TIA
-TS.

Body:
I can't fully test this as I don't have time to build sample data but it should work...

If you use this as your report's dataset query then you should be able to add a simple matrix with a row group by State and a column group by City

/*
You can optimise this a bit but I've kept it fairly procedural so it's easier to follow
*/
-- First do your 3 basic queries but this time we don't pivot and we dump the results into temp tables
-- I've also removed columns that don't appear to be used based on your sample output and remaned a column to City to make it easier to read
select 'Total Created' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Created
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000

select 'Total Won' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Won
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000
        and fo.jna is not null

select 'Total Lost' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Lost
    from FilteredOpportunity fo
    where fo.regionidname = 'Americas Region'
        and fo.createdon >= dateadd(year, -1, getdate())
        and fo.regionalfeeincome >= 250000
        and fo.sys_phasename <> 'Pre-Bid'

-- Now we calculate your Ratio
SELECT
    'Win Ratio' as 'State'
    , coalesce(w.City, l.City) as City -- use coalesce in case 1 side of join is null
    , CASE WHEN ISNULL(l.cnt,0) = 0 THEN 0 ELSE w.Cnt/l.Cnt END as Cnt -- if lost is null or 0 return 0 else calc ratio
into #Ratio
 FROM #Won w
    full join #Lost l on w.City = l.City

-- finaly, get the results and add a sort to help the report row sorting.
SELECT 1 as Sort, * FROM #Created
UNION SELECT 2, * FROM #Won
UNION SELECT 3, * FROM #Lost
UNION SELECT 4, * FROM #Ratio


问:
Unable to get my three.js scene when deployed through react.js
I have been trying to setup my plain JavaScript three.js scene by loading .obj and .mtl files using ReactJS.

However, I'm facing an issue while loading .obj and .mtl files using  Facebook's create-react-app boilerplate.  It always throws an error stating:

unexpected line <!DOCTYPE html>

I have tried:

loading the scripts tags from componentWillMount.

importing the three.js scene and its associated files in the same folder.

答: I think maybe you are trying to serve your .obj and .mtl file from a local development server.  Often local development servers for single-page apps are designed to respond to all requests with the HTML of the single page app.  These apps use special locations for serving static files.  You need to follow the directions for including static files using create-react-app (place the files in the public folder.)


问:
Using bootbox in RequireJS app
I have a sample app.js file with:

```<code>requirejs.config({
    "baseUrl": "js/lib",
    "paths": {
      "jquery": "jquery",
      "app": "../app",
      "bootstrap": "bootstrap/js/bootstrap.bundle",
      "bootbox": "bootbox.min"
    },
    "shim": {
        "bootstrap": {
            "deps": ["jquery"],
            "exports": 'bootbox'
             },
        "main": { "deps": ["jquery","bootstrap"] },
        "bootbox": {
            "deps": ["jquery","bootstrap"],
            "exports": 'bootbox'
        },
    }
});

require(['jquery','bootstrap','bootbox'], function($){

    $(function(jquery) {
        bootbox.alert("bla")
    });
});
</code>```

When I run my page, I can see the correct JS files being grabbed:

...yet my code fails:

```<code>bootbox.alert("bla")
</code>```

Gives:

ReferenceError: bootbox is not defined

I must be missing something simple (again, apologies if this is a newbie error - I'm still trying to get my head around this library)

答:
Don't use shim with Bootbox. If you look at the source code of Bootbox, you'll see it calls define, which registers it as a proper AMD module. The shim option is only for code which is not a proper AMD module.

Now, the define in Bootbox does this:

```<code>define(["jquery"], factory);
</code>```

It sets a dependency on jQuery, but that is wrong, because in fact Bootbox also depends on Bootstrap being present. So we need to fix this. The following shows how you can fix it. You can use a map configuration option so that when Bootbox requires jQuery, it gets Bootstrap. And you set a shim for Bootstrap so that, in addition to having a dependency on jQuery, its module value is the same as jQuery ($).

Without the map setup, there's no guarantee that Bootstrap will load before Bootbox and you'll be facing a race condition: sometimes it'll work, sometimes not.

requirejs.config({
  baseUrl: ".",
  paths: {
    jquery: "//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min",
    bootstrap: "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min",
    bootbox: "//github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min"
  },
  shim: {
    "bootstrap": {
      "deps": ["jquery"],
      // We set bootstrap up so that when we require it, the value with get is just $.
      // This enables the map below.
      "exports": "$"
    },
  },
  map: {
    // When bootbox requires jquery, give it bootstrap instead. This makes it so that
    // bootstrap is **necessarily** loaded before bootbox.
    bootbox: {
      jquery: "bootstrap",
    },
  }
});

require(["jquery", "bootbox"], function($, bootbox) {
  $(function(jquery) {
    bootbox.alert("bla");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /></code>```

Title: Using bootbox in RequireJS app

Body:
I have a sample app.js file with:

requirejs.config({
    "baseUrl": "js/lib",
    "paths": {
      "jquery": "jquery",
      "app": "../app",
      "bootstrap": "bootstrap/js/bootstrap.bundle",
      "bootbox": "bootbox.min"
    },
    "shim": {
        "bootstrap": {
            "deps": ["jquery"],
            "exports": 'bootbox'
             },
        "main": { "deps": ["jquery","bootstrap"] },
        "bootbox": {
            "deps": ["jquery","bootstrap"],
            "exports": 'bootbox'
        },
    }
});

require(['jquery','bootstrap','bootbox'], function($){

    $(function(jquery) {
        bootbox.alert("bla")
    });
});

When I run my page, I can see the correct JS files being grabbed:

...yet my code fails:

bootbox.alert("bla")

Gives:

ReferenceError: bootbox is not defined

I must be missing something simple (again, apologies if this is a newbie error - I'm still trying to get my head around this library)

Body:
Don't use shim with Bootbox. If you look at the source code of Bootbox, you'll see it calls define, which registers it as a proper AMD module. The shim option is only for code which is not a proper AMD module.

Now, the define in Bootbox does this:

define(["jquery"], factory);

It sets a dependency on jQuery, but that is wrong, because in fact Bootbox also depends on Bootstrap being present. So we need to fix this. The following shows how you can fix it. You can use a map configuration option so that when Bootbox requires jQuery, it gets Bootstrap. And you set a shim for Bootstrap so that, in addition to having a dependency on jQuery, its module value is the same as jQuery ($).

Without the map setup, there's no guarantee that Bootstrap will load before Bootbox and you'll be facing a race condition: sometimes it'll work, sometimes not.

requirejs.config({
  baseUrl: ".",
  paths: {
    jquery: "//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min",
    bootstrap: "//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min",
    bootbox: "//github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min"
  },
  shim: {
    "bootstrap": {
      "deps": ["jquery"],
      // We set bootstrap up so that when we require it, the value with get is just $.
      // This enables the map below.
      "exports": "$"
    },
  },
  map: {
    // When bootbox requires jquery, give it bootstrap instead. This makes it so that
    // bootstrap is **necessarily** loaded before bootbox.
    bootbox: {
      jquery: "bootstrap",
    },
  }
});

require(["jquery", "bootbox"], function($, bootbox) {
  $(function(jquery) {
    bootbox.alert("bla");
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


问:
Using a CMake cache variable "before" it is defined
CMake cache variables can be set from virtually everywhere (see here @Florian's What's the CMake syntax to set and use variables?). I was under the assumption that the set value is visible everywhere, even to CMake lists parsed before, but this isn't the case.

Use case

Module A uses ${CMAKE_MYDEF}.

Module B sets the cache variable CMAKE_MYDEF.

add_subdirectory(A) is called before add_subdirectory(B).

Short example showing the behavior

```<code>cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_compile_definitions(EXEC PRIVATE MYDEF=${CMAKE_MYDEF})
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
</code>```

Questions

How can I make sure CMAKE_MYDEF has the desired value regardless the order I add module A and module B?

Are there any ways to ensure the CMake configuration step is re-run twice or, if applicable, as long as the cache variables get changed? (This isn't probably a clean solution, but since I'm working with legacy code not everything can be done beautifully.)

Are there alternatives to cache variables to achieve the same result without re-running the CMake configuration by hand?

Is it possible to set compiler definitions in the generation phase (i.e. when all CMake cache variables are known and set)? Using some kind of generator expressions?

Edit: Short example solution

Following @Florian's answer, here the adapted example showing the solution:

```<code>cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_link_libraries(EXEC MyOtherLib)

add_library(MyOtherLib INTERFACE)
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
target_compile_definitions(MyOtherLib INTERFACE MYDEF=${CMAKE_MYDEF})
</code>```

答:
CMake processes scripts sequentially, starting from top-level CMakeLists.txt and executing its lines one by one.

So, if read variable before assigning it, you will get nothing. The only specific of CACHE variable in that scenario is possibility for that variable to be assigned on previous cmake invocation.

Needs for using a variable before its assigning taking a place usually signals about bad design. In many situations (even with legacy code), design can be fixed gracefully.

Forcing CMake to reconfigure the project can be accomplished e.g. by touching current script:

to force a re-configure, one could "cmake -E touch"
  the CMAKE_CURRENT_LIST_FILE, somehow during target building
  or some such.

Body:
CMake cache variables can be set from virtually everywhere (see here @Florian's What's the CMake syntax to set and use variables?). I was under the assumption that the set value is visible everywhere, even to CMake lists parsed before, but this isn't the case.

Use case

Module A uses ${CMAKE_MYDEF}.

Module B sets the cache variable CMAKE_MYDEF.

add_subdirectory(A) is called before add_subdirectory(B).

Short example showing the behavior

cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_compile_definitions(EXEC PRIVATE MYDEF=${CMAKE_MYDEF})
set(CMAKE_MYDEF "MyValue" CACHE STRING "")

Questions

How can I make sure CMAKE_MYDEF has the desired value regardless the order I add module A and module B?

Are there any ways to ensure the CMake configuration step is re-run twice or, if applicable, as long as the cache variables get changed? (This isn't probably a clean solution, but since I'm working with legacy code not everything can be done beautifully.)

Are there alternatives to cache variables to achieve the same result without re-running the CMake configuration by hand?

Is it possible to set compiler definitions in the generation phase (i.e. when all CMake cache variables are known and set)? Using some kind of generator expressions?

Edit: Short example solution

Following @Florian's answer, here the adapted example showing the solution:

cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_link_libraries(EXEC MyOtherLib)

add_library(MyOtherLib INTERFACE)
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
target_compile_definitions(MyOtherLib INTERFACE MYDEF=${CMAKE_MYDEF})


问:
Why I can only reach my date object when I dump() it before using it?
Why I can only reach my date object when I dump() it before using it?

Here is my function:

```<code>public function checkSubscriptionEndDate($user){

    $subscriptionEndDate = $user->getSubscriptionEndDate();

    dump($subscriptionEndDate);

    if($subscriptionEndDate==null){
        $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionEndDateMessage');
        $subscriptionStatus = "error";
    }else{

        $subscriptionEndDateDate = $subscriptionEndDate->date;
        // CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
        if (date('now') < $subscriptionEndDateDate) {
            dump('before');
            $subscriptionStatus = "success";
            $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionStatusSuccess').' '.date('d/m/Y',strtotime($subscriptionEndDateDate));
        }else{
            dump('after');
            $subscriptionStatus = "error";
            $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionStatusError').' '.date('d/m/Y',strtotime($subscriptionEndDateDate));
        }
    }

    return array(
        'subscriptionEndDateMessage' => $subscriptionEndDateMessage,
        'subscriptionStatus' => $subscriptionStatus
    );

    return $subscriptionEndDateMessage;

}
</code>```

When I do this, the page loads as expected, there is no problem. But if I remove this line:

dump($subscriptionEndDate);

I can no more load the $subscriptionEndDate->date as illustrated in this error page:

答:
This looks like another example of this strange-looking thing with var_dump/print_r and DateTime objects that people often ask about.

The date property is added to the DateTime object in $subscriptionEndDate by the dump function, to provide a human readable representation of the internal data, but it isn't a property of the object by default.

Instead of getting the string, you can just create a new DateTime object to represent the current date and time. Those objects are directly comparable (since PHP 5.2.2).

So instead of this:

```<code>$subscriptionEndDateDate = $subscriptionEndDate->date;
// CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
if (date('now') < $subscriptionEndDateDate) {
</code>```

use this:

```<code>$now = new DateTime;
// CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
if ($now < $subscriptionEndDate) {
</code>```

If you haven't converted $subscriptionEndDate to the string $subscriptionEndDateDate, this later part won't work:

```<code>date('d/m/Y',strtotime($subscriptionEndDateDate)
</code>```

So you can use the format method instead.

```<code>$subscriptionEndDate->format('d/m/Y')
</code>```

This seems better anyway, in my opinion, because you won't be converting from DateTime to string to timestamp back to string, you'll just go directly to string once.

Body:
Why I can only reach my date object when I dump() it before using it?

Here is my function:

public function checkSubscriptionEndDate($user){

    $subscriptionEndDate = $user->getSubscriptionEndDate();

    dump($subscriptionEndDate);

    if($subscriptionEndDate==null){
        $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionEndDateMessage');
        $subscriptionStatus = "error";
    }else{

        $subscriptionEndDateDate = $subscriptionEndDate->date;
        // CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
        if (date('now') < $subscriptionEndDateDate) {
            dump('before');
            $subscriptionStatus = "success";
            $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionStatusSuccess').' '.date('d/m/Y',strtotime($subscriptionEndDateDate));
        }else{
            dump('after');
            $subscriptionStatus = "error";
            $subscriptionEndDateMessage = $this->get('translator')->trans('subscriptionStatusError').' '.date('d/m/Y',strtotime($subscriptionEndDateDate));
        }
    }

    return array(
        'subscriptionEndDateMessage' => $subscriptionEndDateMessage,
        'subscriptionStatus' => $subscriptionStatus
    );

    return $subscriptionEndDateMessage;

}

When I do this, the page loads as expected, there is no problem. But if I remove this line:

dump($subscriptionEndDate);

I can no more load the $subscriptionEndDate->date as illustrated in this error page:

Body:
This looks like another example of this strange-looking thing with var_dump/print_r and DateTime objects that people often ask about.

The date property is added to the DateTime object in $subscriptionEndDate by the dump function, to provide a human readable representation of the internal data, but it isn't a property of the object by default.

Instead of getting the string, you can just create a new DateTime object to represent the current date and time. Those objects are directly comparable (since PHP 5.2.2).

So instead of this:

$subscriptionEndDateDate = $subscriptionEndDate->date;
// CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
if (date('now') < $subscriptionEndDateDate) {

use this:

$now = new DateTime;
// CHECK IF SUBSCRIPTION END DATE IS BEFORE NOW
if ($now < $subscriptionEndDate) {

If you haven't converted $subscriptionEndDate to the string $subscriptionEndDateDate, this later part won't work:

date('d/m/Y',strtotime($subscriptionEndDateDate)

So you can use the format method instead.

$subscriptionEndDate->format('d/m/Y')

This seems better anyway, in my opinion, because you won't be converting from DateTime to string to timestamp back to string, you'll just go directly to string once.


问:
How can I get the ID of an element using jQuery?
```<code><div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });
</script>
</code>```

Why doesn't the above work, and how should I do this?

答: Since the id is an attribute, you can get it by using the attr method.


问:
Trying to retrieve data from URL and store in a local DB and then append to a listview
I was trying to retrieve data from URL and store it in a local DB and then appending that data to listview.
I was trying to new so please dont mind if the code have big mistakes or wrong procedure... suggest me how to do it.

my Database class is

```<code>public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "placesmanager";

// Contacts table name
private static final String TABLE_PLACES = "places";
public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists TABLE_PLACES(name varchar(50),rating varchar(50),icon varchar(50))");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLACES);

    // Create tables again
    onCreate(db);

}
//adding contact
public void addContact(PlacesData data) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("name", data.getName());
    values.put("rating", data.getRating());
    values.put("icon", data.getIcon());

    // Inserting Row
    db.insert(TABLE_PLACES, null, values);
    db.close(); // Closing database connection
}

// Getting All Contacts
public ArrayList<PlacesData> getAllContacts() {
    ArrayList<PlacesData> contactList = new ArrayList<>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_PLACES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            PlacesData contact = new PlacesData();
            contact.setName(cursor.getString(0));
            contact.setRating(cursor.getString(1));
            contact.setIcon(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}
</code>```

and the method of recyclerview that iam appending to Database and trying to retrive it is

```<code> public void onBindViewHolder(MyRecycler holder, final int position) {

    DatabaseHandler handler = new DatabaseHandler(activity);
    handler.addContact(new PlacesData(data.get(position).getName(),data.get(position).getRating(),data.get(position).getIcon()));
  //  Log.i("Database",handler+"");

    ArrayList<PlacesData> contacts = handler.getAllContacts();

    for (PlacesData cn : contacts) {
        String log = "Name: "+cn.getName()+" ,Rating: " + cn.getRating() + " ,Icon: " + cn.getIcon();
        Log.i("Name: ", log);
        holder.tvName.setText(cn.getName());
        holder.tvRating.setText(cn.getRating());
        Picasso.with(activity).load(cn.getIcon()).into(holder.imgIcon);
    }
        }
    });
</code>```

Appending the DB data to recyclerview is done, but not in correct way the fields are repeating in view.and in Android Monitor the following  error is showing.

I am doing this by following some google examples suggest me possible changes.

and finally the output is

答: Declare an ID in your Database's onCreate. I think that's the problem. Every table must contain a ID (primary key) which is unique for each row.</p>

Body:
I was trying to retrieve data from URL and store it in a local DB and then appending that data to listview.
I was trying to new so please dont mind if the code have big mistakes or wrong procedure... suggest me how to do it.

my Database class is

public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "placesmanager";

// Contacts table name
private static final String TABLE_PLACES = "places";
public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists TABLE_PLACES(name varchar(50),rating varchar(50),icon varchar(50))");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLACES);

    // Create tables again
    onCreate(db);

}
//adding contact
public void addContact(PlacesData data) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("name", data.getName());
    values.put("rating", data.getRating());
    values.put("icon", data.getIcon());

    // Inserting Row
    db.insert(TABLE_PLACES, null, values);
    db.close(); // Closing database connection
}

// Getting All Contacts
public ArrayList<PlacesData> getAllContacts() {
    ArrayList<PlacesData> contactList = new ArrayList<>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_PLACES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            PlacesData contact = new PlacesData();
            contact.setName(cursor.getString(0));
            contact.setRating(cursor.getString(1));
            contact.setIcon(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

and the method of recyclerview that iam appending to Database and trying to retrive it is

 public void onBindViewHolder(MyRecycler holder, final int position) {

    DatabaseHandler handler = new DatabaseHandler(activity);
    handler.addContact(new PlacesData(data.get(position).getName(),data.get(position).getRating(),data.get(position).getIcon()));
  //  Log.i("Database",handler+"");

    ArrayList<PlacesData> contacts = handler.getAllContacts();

    for (PlacesData cn : contacts) {
        String log = "Name: "+cn.getName()+" ,Rating: " + cn.getRating() + " ,Icon: " + cn.getIcon();
        Log.i("Name: ", log);
        holder.tvName.setText(cn.getName());
        holder.tvRating.setText(cn.getRating());
        Picasso.with(activity).load(cn.getIcon()).into(holder.imgIcon);
    }
        }
    });

Appending the DB data to recyclerview is done, but not in correct way the fields are repeating in view.and in Android Monitor the following  error is showing.

I am doing this by following some google examples suggest me possible changes.

and finally the output is


问:
HtmlUnit doesn't load javascript correctly
I'm trying to scrap contents of a table from link.

It's the "Match Stats" table under "Stats" tab.

However, by examine the source using Chrome, the content is actually missing from the container:

```<code><tbody class="matchCentreStatsContainer"></tbody>
</code>```

So I'm assuming the content is handled by JavaScript.

I use the following code to load the page, click on "Stats" tab, and then check the page content.

```<code>    WebClient wc = new WebClient(BrowserVersion.CHROME);
    WebRequest request = new WebRequest(new URL("https://www.premierleague.com/match/14252"));
    wc.getOptions().setThrowExceptionOnScriptError(false);
    wc.setJavaScriptTimeout(10000);
    wc.getOptions().setJavaScriptEnabled(true);

    HtmlPage page = wc.getPage(request);
    wc.waitForBackgroundJavaScript(30000);
    HtmlUnorderedList ul = (HtmlUnorderedList) page.getByXPath("//ul[contains(@class, 'tablist')]").get(0);

    //get the stats tab
    HtmlListItem li = (HtmlListItem) ul.getChildNodes().get(2);
    li.click();
    wc.waitForBackgroundJavaScript(10000);
    String pageAsXml = page.asXml();
</code>```

But there's still nothing inside the table in my pageAsXml, anything I did wrong?

答:
Have done a short test with your code.
If you disable the line wc.getOptions().setThrowExceptionOnScriptError(false); you will see that there is a js error (only with HtmlUnit and not in the browser). Usually this means some javascript code will not be executed. Please open an HtmlUnit issue for this and we can try to solve this problem. Please have a look at Submitting JavaScript bugs.</p>

Body:
I'm trying to scrap contents of a table from link.

It's the "Match Stats" table under "Stats" tab.

However, by examine the source using Chrome, the content is actually missing from the container:

So I'm assuming the content is handled by JavaScript.

I use the following code to load the page, click on "Stats" tab, and then check the page content.

    WebClient wc = new WebClient(BrowserVersion.CHROME);
    WebRequest request = new WebRequest(new URL("https://www.premierleague.com/match/14252"));
    wc.getOptions().setThrowExceptionOnScriptError(false);
    wc.setJavaScriptTimeout(10000);
    wc.getOptions().setJavaScriptEnabled(true);

    HtmlPage page = wc.getPage(request);
    wc.waitForBackgroundJavaScript(30000);
    HtmlUnorderedList ul = (HtmlUnorderedList) page.getByXPath("//ul[contains(@class, 'tablist')]").get(0);

    //get the stats tab
    HtmlListItem li = (HtmlListItem) ul.getChildNodes().get(2);
    li.click();
    wc.waitForBackgroundJavaScript(10000);
    String pageAsXml = page.asXml();

But there's still nothing inside the table in my pageAsXml, anything I did wrong?


问:
What unit test to write for a class using generics in Java?
Taking the very specific example of the JpaDao class defined in this article:

```<code>public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}
</code>```

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

答:
You could write an abstract test class for entities which subclass this.

Eg:

```<code>public abstract class JpaDaoTest<K,E> {

    abstract protected E getEntity();
    abstract protected JpaDao getDAO();

    @Test
    public void testPersistCreatesEntity()
    {
         JpaDao dao = getDAO();
         dao.persist(getEntity());
         // assert
     }
}
</code>```

The contract you generic classes implement should be able to be tested just as genericlly, assuming that getEntity() sets up and relational dependencies correctly.

Therefore, by subclassing this test class for all the test cases for your generic subclasses, you get the tests for free.

Body:
Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

Body:
You could write an abstract test class for entities which subclass this.

Eg:

public abstract class JpaDaoTest<K,E> {

    abstract protected E getEntity();
    abstract protected JpaDao getDAO();

    @Test
    public void testPersistCreatesEntity()
    {
         JpaDao dao = getDAO();
         dao.persist(getEntity());
         // assert
     }
}

The contract you generic classes implement should be able to be tested just as genericlly, assuming that getEntity() sets up and relational dependencies correctly.

Therefore, by subclassing this test class for all the test cases for your generic subclasses, you get the tests for free.


问:
How to sum two cells into one and delete the formula after that?
I have this very niche problem. For instance Lets say the value in the cell A1 is 5 and A2 is 10, what I want to do is add A1 to A2 i.e A2 is now 15 and then when I delete the value in A1 the sum should remain in A2. I cannot use the paste special option to copy just the values because i want to retain the formula for later use i.e when I again input a value to A1 lets say 3 then the sum in A2 should be 18. Any help???
VBA code that triggers this sort of action will be helpful
Thanks In advance.</p>

答:
In the worksheet's code sheet (right-click worksheet name tab then View, Code).</p>

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1, A2")) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        if application.count(Range("A1, A2")) = 2 then
            Range("A3") = application.sum(Range("A1, A2"))
        end if
    End If

bm_Safe_Exit:
    If CBool(Val(Err.Number)) Then _
        Debug.Print Err.Number & ": " & Err.Description
    Application.EnableEvents = True

End Sub
</code>```

Body:
In the worksheet's code sheet (right-click worksheet name tab then View, Code).

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1, A2")) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        if application.count(Range("A1, A2")) = 2 then
            Range("A3") = application.sum(Range("A1, A2"))
        end if
    End If

bm_Safe_Exit:
    If CBool(Val(Err.Number)) Then _
        Debug.Print Err.Number & ": " & Err.Description
    Application.EnableEvents = True

End Sub


问:
How to separate whole number and decimal number to two different variable
I am  trying to separate whole number and decimal number
two int variable

```<code>#include <iostream>
#include <iomanip>
#include<math.h>

using namespace std;
int main()
{
    double initialAmount = 42800.13;
    double fractionalPart = initialAmount - floor(initialAmount);
    cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";

}
</code>```

Present output is

```<code>42800
0.13
</code>```

expected output

```<code>42800
13
</code>```

It can be more than two decimal places .
any easy way to do that

答:
Maybe not the best solution, but at least it is simple :)

Store your double initialAmount in a int - which will truncate the decimal part. Then you have the number before the decimal point. Then subtract that from the initial value and you'll be left with just the part after the decimal point. Multiply that by however many powers of 10 that you deem significant and then again store that in a int and you'll have your two values.

Body:
I am  trying to separate whole number and decimal number
two int variable

#include <iostream>
#include <iomanip>
#include<math.h>

using namespace std;
int main()
{
    double initialAmount = 42800.13;
    double fractionalPart = initialAmount - floor(initialAmount);
    cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";

}

Present output is

42800
0.13

expected output

42800
13

It can be more than two decimal places .
any easy way to do that