问:
Error in glm() in R
I would like to perform a logistic regression but get errors - don't know where the mistake might be.

The structure of my data:

```<code>'data.frame':   3911 obs. of  29 variables:
 $ vn1              : Factor w/ 2 levels "maennlich","weiblich": 1 1 2 1 1 2 1 1 1 1 ...
 $ vn2c             : int  1976 1943 1927 1949 1965 1977 1986 1976 1944 1994 ...
 $ vn35             : Factor w/ 7 levels "keine Angabe",..: 6 4 5 3 3 5 7 6 5 5 ...
 $ v39              : Factor w/ 8 levels "keine Angabe",..: 8 4 5 8 7 7 5 6 6 6 ...
 $ n39              : Factor w/ 9 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ v41              : Factor w/ 7 levels "keine Angabe",..: 6 5 5 2 7 7 5 5 6 6 ...
 $ n41              : Factor w/ 7 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ vn42a            : Factor w/ 8 levels "keine Angabe",..: 8 4 8 8 5 5 6 6 6 4 ...
 $ vn42b            : Factor w/ 8 levels "keine Angabe",..: 5 4 7 5 5 5 6 7 6 5 ...
 $ vn43a            : Factor w/ 8 levels "keine Angabe",..: 7 5 8 6 2 6 6 2 7 7 ...
 $ vn43b            : Factor w/ 8 levels "keine Angabe",..: 7 4 6 4 4 7 6 2 6 5 ...
 $ vn62             : Factor w/ 14 levels "keine Angabe",..: 8 11 9 2 3 3 8 6 5 7 ...
 $ vn119a           : Factor w/ 15 levels "keine Angabe",..: 6 3 8 14 10 8 14 8 6 6 ...
 $ ostwest          : Factor w/ 2 levels "Ost","West": 2 2 2 2 2 2 2 2 2 2 ...
 $ prefmerkel       : Factor w/ 2 levels "Steinbrueck",..: 1 2 2 NA NA NA 2 2 1 1 ...
 $ angst            : num  1 3 2 4 4 2 0 1 2 2 ...
 $ crisismerkel     : num  0 4 3 0 1 1 3 2 2 2 ...
 $ leadership42     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 5 1 5 5 2 2 3 3 3 1 ...
 $ leadership43     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 2 5 3 NA 3 3 NA 4 4 ...
 $ leadership       : num  1 -1 0 2 NA -1 0 NA -1 -3 ...
 $ trustworthiness42: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 2 1 4 2 2 2 3 4 3 2 ...
 $ trustworthiness43: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 1 3 1 1 4 3 NA 3 2 ...
 $ trustworthiness  : num  -2 0 1 1 1 -2 0 NA 0 0 ...
 $ ideology         : num  5 8 6 NA NA NA 5 3 2 4 ...
 $ pid              : Factor w/ 10 levels "none","CDU/CSU",..: 3 2 5 1 7 5 1 5 3 3 ...
 $ age              : num  37 70 86 64 48 36 27 37 69 19 ...
 $ agegroups        : Factor w/ 7 levels "bis 25 Jahre",..: 3 6 7 5 4 3 2 3 6 1 ...
 $ gender           : Factor w/ 2 levels "male","female": 1 1 2 1 1 2 1 1 1 1 ...
 $ region           : Factor w/ 2 levels "west","east": 1 1 1 1 1 1 1 1 1 1 ...
</code>```

The regression command returns the following error:

```<code>summary(glm(prefmerkel~angst+crisismerkel+leadership+trustworthiness+ideology+pid+agegroups+gender+region,data=gles))

Error in glm.fit(x = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  :
  NA/NaN/Inf in 'y'

In addition: Warning messages:
1: In Ops.factor(y, mu) : ‘-’ nicht sinnvoll für Faktoren
2: In Ops.factor(eta, offset) : ‘-’ nicht sinnvoll für Faktoren
3: In Ops.factor(y, mu) : ‘-’ nicht sinnvoll für Faktoren
</code>```

答: If your variable is binomial mention 'family=binomial'. This will solve the problem</p>

Title: Error in glm() in R

Body:
I would like to perform a logistic regression but get errors - don't know where the mistake might be.

The structure of my data:

'data.frame':   3911 obs. of  29 variables:
 $ vn1              : Factor w/ 2 levels "maennlich","weiblich": 1 1 2 1 1 2 1 1 1 1 ...
 $ vn2c             : int  1976 1943 1927 1949 1965 1977 1986 1976 1944 1994 ...
 $ vn35             : Factor w/ 7 levels "keine Angabe",..: 6 4 5 3 3 5 7 6 5 5 ...
 $ v39              : Factor w/ 8 levels "keine Angabe",..: 8 4 5 8 7 7 5 6 6 6 ...
 $ n39              : Factor w/ 9 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ v41              : Factor w/ 7 levels "keine Angabe",..: 6 5 5 2 7 7 5 5 6 6 ...
 $ n41              : Factor w/ 7 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ vn42a            : Factor w/ 8 levels "keine Angabe",..: 8 4 8 8 5 5 6 6 6 4 ...
 $ vn42b            : Factor w/ 8 levels "keine Angabe",..: 5 4 7 5 5 5 6 7 6 5 ...
 $ vn43a            : Factor w/ 8 levels "keine Angabe",..: 7 5 8 6 2 6 6 2 7 7 ...
 $ vn43b            : Factor w/ 8 levels "keine Angabe",..: 7 4 6 4 4 7 6 2 6 5 ...
 $ vn62             : Factor w/ 14 levels "keine Angabe",..: 8 11 9 2 3 3 8 6 5 7 ...
 $ vn119a           : Factor w/ 15 levels "keine Angabe",..: 6 3 8 14 10 8 14 8 6 6 ...
 $ ostwest          : Factor w/ 2 levels "Ost","West": 2 2 2 2 2 2 2 2 2 2 ...
 $ prefmerkel       : Factor w/ 2 levels "Steinbrueck",..: 1 2 2 NA NA NA 2 2 1 1 ...
 $ angst            : num  1 3 2 4 4 2 0 1 2 2 ...
 $ crisismerkel     : num  0 4 3 0 1 1 3 2 2 2 ...
 $ leadership42     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 5 1 5 5 2 2 3 3 3 1 ...
 $ leadership43     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 2 5 3 NA 3 3 NA 4 4 ...
 $ leadership       : num  1 -1 0 2 NA -1 0 NA -1 -3 ...
 $ trustworthiness42: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 2 1 4 2 2 2 3 4 3 2 ...
 $ trustworthiness43: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 1 3 1 1 4 3 NA 3 2 ...
 $ trustworthiness  : num  -2 0 1 1 1 -2 0 NA 0 0 ...
 $ ideology         : num  5 8 6 NA NA NA 5 3 2 4 ...
 $ pid              : Factor w/ 10 levels "none","CDU/CSU",..: 3 2 5 1 7 5 1 5 3 3 ...
 $ age              : num  37 70 86 64 48 36 27 37 69 19 ...
 $ agegroups        : Factor w/ 7 levels "bis 25 Jahre",..: 3 6 7 5 4 3 2 3 6 1 ...
 $ gender           : Factor w/ 2 levels "male","female": 1 1 2 1 1 2 1 1 1 1 ...
 $ region           : Factor w/ 2 levels "west","east": 1 1 1 1 1 1 1 1 1 1 ...

The regression command returns the following error:

summary(glm(prefmerkel~angst+crisismerkel+leadership+trustworthiness+ideology+pid+agegroups+gender+region,data=gles))

Error in glm.fit(x = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  :
  NA/NaN/Inf in 'y'

In addition: Warning messages:
1: In Ops.factor(y, mu) : ‘-’ nicht sinnvoll für Faktoren
2: In Ops.factor(eta, offset) : ‘-’ nicht sinnvoll für Faktoren
3: In Ops.factor(y, mu) : ‘-’ nicht sinnvoll für Faktoren


来源: stackexchange

问:
Angular 2 nested forms with child components and validation
I'm trying achieve a nested form with validation in Angular 2, I've seen posts and followed the documentation but I'm really struggling, hope you can point me in the right direction.

What I am trying to achieve is having a validated form with multiple children components. These children components are a bit complex, some of them have more children components, but for the sake of the question I think we can attack the problem having a parent and a children.

What am I trying to accomplish

Having a form that works like this:

```<code><div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div>
        <label>Dummy</label>
        <input formControlName="dummyInput">
    </div>
</div>
</code>```

This requires having a class like this:

```<code>private userForm: FormGroup;
constructor(private fb: FormBuilder){
    this.createForm();
}
private createForm(): void{
    this.userForm = this.fb.group({
        userId: ["", Validators.required],
        dummyInput: "", Validators.required]
    });
}
</code>```

This works as expected, but now I want to decouple the code, and put the "dummyInput" functionality in a separate, different component. This is where I get lost. This is what I tried, I think I'm not far from getting the answer, but I'm really out of ideas, I'm fairly new to the scene:

parent.component.html

```<code><div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div>
        <dummy></dummy>
    </div>
</div>
</code>```

parent.component.ts

```<code>private createForm(): void{
    this.userForm = this.fb.group({
    userId: ["", Validators.required],
    dummy: this.fb.group({
        dummyInput: ["", Validators.required]
    })
});
</code>```

children.component.html

```<code><div [formGroup]="dummyGroup">
    <label>Dummy Input: </label>
    <input formControlName="dummyInput">
</div>
</code>```

children.component.ts

```<code>private dummyGroup: FormGroup;
</code>```

I know something is not right with the code, but I'm really in a roadblock. Any help would be aprreciated.

Thanks.

答:
you can add an Input in your children component to pass the FormGroup to it.and use FormGroupName to pass the name of your FormGroup :)

children.component.ts

```<code>@Input('group');
private dummyGroup: FormGroup;
</code>```

parent.component.html

```<code><div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div formGroupName="dummy">
        <dummy [group]="userForm.controls['dummy']"></dummy>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying achieve a nested form with validation in Angular 2, I've seen posts and followed the documentation but I'm really struggling, hope you can point me in the right direction.

What I am trying to achieve is having a validated form with multiple children components. These children components are a bit complex, some of them have more children components, but for the sake of the question I think we can attack the problem having a parent and a children.

What am I trying to accomplish

Having a form that works like this:

        User Id
        <input formControlName="userId">

        Dummy
        <input formControlName="dummyInput">

This requires having a class like this:

private userForm: FormGroup;
constructor(private fb: FormBuilder){
    this.createForm();
}
private createForm(): void{
    this.userForm = this.fb.group({
        userId: ["", Validators.required],
        dummyInput: "", Validators.required]
    });
}

This works as expected, but now I want to decouple the code, and put the "dummyInput" functionality in a separate, different component. This is where I get lost. This is what I tried, I think I'm not far from getting the answer, but I'm really out of ideas, I'm fairly new to the scene:

parent.component.html

        User Id
        <input formControlName="userId">

        <dummy></dummy>

parent.component.ts

private createForm(): void{
    this.userForm = this.fb.group({
    userId: ["", Validators.required],
    dummy: this.fb.group({
        dummyInput: ["", Validators.required]
    })
});

children.component.html

    Dummy Input:
    <input formControlName="dummyInput">

children.component.ts

private dummyGroup: FormGroup;

I know something is not right with the code, but I'm really in a roadblock. Any help would be aprreciated.

Thanks.

Body:
you can add an Input in your children component to pass the FormGroup to it.and use FormGroupName to pass the name of your FormGroup :)

children.component.ts

@Input('group');
private dummyGroup: FormGroup;

parent.component.html

<div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div formGroupName="dummy">
        <dummy [group]="userForm.controls['dummy']"></dummy>
    </div>
</div>


问:
c# delete excel sheets using for loop
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}
</code>```

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

答:
Keep in mind that while deleting a worksheet, index position might get change so you'll also need to decrease the int value to get correct index otherwise you'll again get the same exception while deleting the sheets afterwards or lead to delete a sheet which you dont want to delete</p>

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;

for (int i = 0; i < max; i++)
{
    if (i != index)
    {
        Excel.Worksheet worksheet = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheet.Delete();

        //decrease the value
        --i;
    }
}
</code>```

Title: c# delete excel sheets using for loop

Body:
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

Body:
Keep in mind that while deleting a worksheet, index position might get change so you'll also need to decrease the int value to get correct index otherwise you'll again get the same exception while deleting the sheets afterwards or lead to delete a sheet which you dont want to delete

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;

for (int i = 0; i < max; i++)
{
    if (i != index)
    {
        Excel.Worksheet worksheet = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheet.Delete();

        //decrease the value
        --i;
    }
}


问:
Why after using strcat function original string changed?
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

```<code>#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}
</code>```

output:-

```<code>before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!
</code>```

答:
strcat() appends source string to the destination string and returns the destination string.

```<code>char * strcat ( char * destination, const char * source );
</code>```

So your statement

```<code>c = strcat(b,a)
</code>```

So array b and c will have the same values. strcat()

EDIT :
"a" changed because you're overflowing "b" array. Since its c++ you can just use std::string instead of a character array.

```<code>std::string a = "hi" ;
std::string b = "this is concat" ;
std::string c = a + b ;
</code>```

Body:
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}

output:-

before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!

Body:
strcat() appends source string to the destination string and returns the destination string.

char * strcat ( char * destination, const char * source );

So your statement

c = strcat(b,a)

So array b and c will have the same values. strcat()

EDIT :
"a" changed because you're overflowing "b" array. Since its c++ you can just use std::string instead of a character array.

std::string a = "hi" ;
std::string b = "this is concat" ;
std::string c = a + b ;


问:
How can I get a HTML web page from a Windows Mobile Application?
I'm working with C#.net developing applications for windows mobile 6, and i need get the HTML code from a web page, i mean, i need download the page and then get the code or parse it to string.

someone know how can i do it?

I know there is the WebClient Class for desktop app, but i didn't find something like that for mobile app

答: You can use the HttpWebRequest class to make a GET request and read the HTML code.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: kgiannakakis


问:
checking for URL validity in VB.net
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

```<code>Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub
</code>```

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

```<code>function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}
</code>```

答:
If you can use javascript, here's one really good way to do it: How to Test a URL in jQuery

Edit: How about one of these approaches then?

Search for "Does a URL exist?" on this page.

How to check if a URL exists in javascript

Javascript to check if URL exist

Title: checking for URL validity in VB.net

Body:
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}


问:
Finding all ng-model elements of a particular child elements
I have written on directive I just want all the ng-model elements inside the element where the directive is placed
This is my html element with loggerhelp  directive

```<code><input type="text" loggerhelp  />
</code>```

This is my directive

```<code>    angular
 .module('app').directive('loggerhelp', loggerhelp);

loggerhelp($mdDialog) {
        var Popupdirective = {
            restrict: 'A',
            scope: false,
            link: popupController
        }
        return Popupdirective
        function popupController(scope, element, attr) {
// Here i want all the child ng-model elements.
            console.log(element)
            alert();
        }
    }
</code>```

答:
Have you tried searching by attribute like element.find("[ng-model]")? element is the jqLite-wrapped element that this directive matches so find and the selectors should work for you.

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {

}])
.directive('loggerhelp', function loggerhelp() {
        var loggerhelpDirective = {
            restrict: 'A',
            scope: false,
            link: loggerhelpController
        }
        return loggerhelpDirective
        function loggerhelpController(scope, element, attr) {
            var innerElementsWithNgModel = element.find("[ng-model]");
            console.log(innerElementsWithNgModel.length);
            console.log(angular.element(innerElementsWithNgModel[2]).attr('ng-model'));

            //so now you have an array with all the elements that have ng-model attr
            //you can attach event handler function for blur
            innerElementsWithNgModel.on('blur', function(){
                var ngModelAttr = angular.element(this).attr('ng-model');
                //we can evaluate this now using $eval
                if (ngModelAttr){
                  console.log(scope.$eval(ngModelAttr));
                }
            });
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">

    <div loggerhelp>
      <input type="text" ng-model="$ctrl.model1"  />
      <input type="text" ng-model="$ctrl.model2"  />
      <input type="text" ng-model="$ctrl.model3"  />
      <input type="text" ng-model="$ctrl.model4"  />
    </div>
  </div>
</div></code>```

UPDATE 1: Working snippet to illustrate how it works.

UPDATE 2: Now we can attach event handler function for blur event using .on() and evaluate the attribute using $eval().

Body:
I have written on directive I just want all the ng-model elements inside the element where the directive is placed
This is my html element with loggerhelp  directive

<input type="text" loggerhelp  />

This is my directive

    angular
 .module('app').directive('loggerhelp', loggerhelp);

loggerhelp($mdDialog) {
        var Popupdirective = {
            restrict: 'A',
            scope: false,
            link: popupController
        }
        return Popupdirective
        function popupController(scope, element, attr) {
// Here i want all the child ng-model elements.
            console.log(element)
            alert();
        }
    }

Body:
Have you tried searching by attribute like element.find("[ng-model]")? element is the jqLite-wrapped element that this directive matches so find and the selectors should work for you.

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {

}])
.directive('loggerhelp', function loggerhelp() {
        var loggerhelpDirective = {
            restrict: 'A',
            scope: false,
            link: loggerhelpController
        }
        return loggerhelpDirective
        function loggerhelpController(scope, element, attr) {
            var innerElementsWithNgModel = element.find("[ng-model]");
            console.log(innerElementsWithNgModel.length);
            console.log(angular.element(innerElementsWithNgModel[2]).attr('ng-model'));

            //so now you have an array with all the elements that have ng-model attr
            //you can attach event handler function for blur
            innerElementsWithNgModel.on('blur', function(){
                var ngModelAttr = angular.element(this).attr('ng-model');
                //we can evaluate this now using $eval
                if (ngModelAttr){
                  console.log(scope.$eval(ngModelAttr));
                }
            });
        }
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">

    <div loggerhelp>
      <input type="text" ng-model="$ctrl.model1"  />
      <input type="text" ng-model="$ctrl.model2"  />
      <input type="text" ng-model="$ctrl.model3"  />
      <input type="text" ng-model="$ctrl.model4"  />
    </div>
  </div>
</div>

UPDATE 1: Working snippet to illustrate how it works.

UPDATE 2: Now we can attach event handler function for blur event using .on() and evaluate the attribute using $eval().


问:
Storing API keys on the Realtime Database (Firebase)
My android app requires using the Google Place Search API but since it's not available for android, I'll have to call the Web API. I've considered using Cloud Functions but that's too expensive and can be done for a lot less if done locally on each client. The problem is storing the API key on the user's devices as it can be easily retrieved. Thus is it safe if I store the key on the RT DB and reference it only when needed?

Also, if you have suggestions, I'd me more than happy to implement them :D

答:
Storing the key in the database still requires that users can access it. So while it's one level more effort to retrieve, malicious users will still be able to retrieve it.

A server-side key should simply not be used in client-side code.


问:
How to create a gaussian blur effect in libGDX without shaders
How do you create a gaussian blur effect without any shaders? I tried many shader tutorials but I never got it to work. I also tried this link. https://github.com/mattdesl/lwjgl-basics/wiki/OpenGL-ES-Blurs
But, I couldn't get the screen to be transformed into a pixmap. Can you guys point me in the right direction on where to go to get the right answer?

Thanks in advance!

答:
To draw blur without shaders you would need to draw the original scene to some texture. Then draw this texture NxN times on your main buffer with some blending. Alpha must correspond to the factor that depends on the offset in the NxN matrix. Just as pseudo:

```<code>for(int heightDiff=-N; heightDiff<=N; heightDiff++) {
    for(int widthDiff=-N; widthDiff<=N; widthDiff++) {
       float alpha = 1.0/max(width, height); // Not a correct equation
       glColor(1.0, 1.0, 1.0, alpha):
       drawFullscreenWithOffset(widthDiff, heightDiff);
    }
}
</code>```

It might be an optimization to separate vertical and horizontal blur though. That would mean you need to choose one of them and draw it to a new texture and then use that one to draw the other blur on the main buffer. You gain an extra texture but you reduce NxN draws to 2*N.

Body:
To draw blur without shaders you would need to draw the original scene to some texture. Then draw this texture NxN times on your main buffer with some blending. Alpha must correspond to the factor that depends on the offset in the NxN matrix. Just as pseudo:

for(int heightDiff=-N; heightDiff<=N; heightDiff++) {
    for(int widthDiff=-N; widthDiff<=N; widthDiff++) {
       float alpha = 1.0/max(width, height); // Not a correct equation
       glColor(1.0, 1.0, 1.0, alpha):
       drawFullscreenWithOffset(widthDiff, heightDiff);
    }
}

It might be an optimization to separate vertical and horizontal blur though. That would mean you need to choose one of them and draw it to a new texture and then use that one to draw the other blur on the main buffer. You gain an extra texture but you reduce NxN draws to 2*N.


答: Why not use WebClient.DownloadString() method instead?

Title: checking for URL validity in VB.net


问:
COUNT in CASE statement?
I would like to categorize records based on the count of one field.
My code is :

```<code> select `posts`.`post_customer_fs_id` AS `post_customer_fs_id`,count(`post_id`) AS `open_post_count`,
CASE count(`post_id`)
WHEN count(`post_id`)=1 THEN 'A'
WHEN count(`post_id`)>1 THEN 'B'
END AS AAA
from `posts` where (`posts`.`post_status` = '3') AND posts.post_type_id='1' group by `posts`.`post_customer_fs_id` ;
</code>```

For some reason I m receiving A for the records with COUNT 1 but NULL for the records with COUNT bigger than 1.
The post_id is an INTEGER field..
Any help it will be very appreciated!

答:
In

```<code>CASE count(post_id)
  WHEN count(post_id)=1 THEN 'A'
</code>```

You are comparing count(post_id) with count(post_id)=1 where the latter results in true or false which equals 1 or 0 in MySQL. You want

```<code>CASE
  WHEN count(post_id)=1 THEN 'A'
</code>```

instead.

Title: COUNT in CASE statement?

Body:
I would like to categorize records based on the count of one field.
My code is :

 select `posts`.`post_customer_fs_id` AS `post_customer_fs_id`,count(`post_id`) AS `open_post_count`,
CASE count(`post_id`)
WHEN count(`post_id`)=1 THEN 'A'
WHEN count(`post_id`)>1 THEN 'B'
END AS AAA
from `posts` where (`posts`.`post_status` = '3') AND posts.post_type_id='1' group by `posts`.`post_customer_fs_id` ;

For some reason I m receiving A for the records with COUNT 1 but NULL for the records with COUNT bigger than 1.
The post_id is an INTEGER field..
Any help it will be very appreciated!

Body:
In

CASE count(post_id)
  WHEN count(post_id)=1 THEN 'A'

You are comparing count(post_id) with count(post_id)=1 where the latter results in true or false which equals 1 or 0 in MySQL. You want

CASE
  WHEN count(post_id)=1 THEN 'A'

instead.


问:
Doctrine2.3 and OneToOne cascade persist doesn't seem to work
I have two entites (User and UserPreferences) that I want to map OneToOne unidirectional.

The code looks something like this:

```<code>/**
 * @ORM\Table("users")
 * @ORM\Entity
 */
class User
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     */
    protected $id;

    ...

    /**
     * @ORM\Column(name="user_preferences_id", type="integer")
     * @ORM\OneToOne
     * (
     *      targetEntity="UserPreferences",
     *      cascade={"persist"}
     * )
     */
    protected $userPreferences;

    public function __construct() {
        $this->userPreferences = new UserPreferences();
    }
}

/**
 * @ORM\Table("user_preferences")
 * @ORM\Entity
 */
class UserPreferences extends UserPreferencesEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(name="user_id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    ...
}
</code>```

Now when a new User is created, userPreferences is initialized with a new UserPreferences object. When trying to persist user, Doctrine throws an Exception, claiming

A new entity was found through the relationship '...\Entity\User#userPreferences' that was not configured to cascade persist operations for entity: ...\Entity\UserPreferences@000000003ae25e5700000000a6eaafc9. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist  this association in the mapping for example @ManyToOne(..,cascade={"persist"}).

But what else should I do? User#userPreferences is configured to cascade persist but it doesn't. Am I getting something wrong here?

答:
Bug was with

```<code> * @ORM\Column(name="user_preferences_id", type="integer")
</code>```

Your code should contain

```<code> * @ORM\JoinColumn(name="user_preferences_id", referencedColumnName="id")
</code>```

instead of this.

Body:
I have two entites (User and UserPreferences) that I want to map OneToOne unidirectional.

The code looks something like this:

/**
 * @ORM\Table("users")
 * @ORM\Entity
 */
class User
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     */
    protected $id;

    ...

    /**
     * @ORM\Column(name="user_preferences_id", type="integer")
     * @ORM\OneToOne
     * (
     *      targetEntity="UserPreferences",
     *      cascade={"persist"}
     * )
     */
    protected $userPreferences;

    public function __construct() {
        $this->userPreferences = new UserPreferences();
    }
}

/**
 * @ORM\Table("user_preferences")
 * @ORM\Entity
 */
class UserPreferences extends UserPreferencesEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(name="user_id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    ...
}

Now when a new User is created, userPreferences is initialized with a new UserPreferences object. When trying to persist user, Doctrine throws an Exception, claiming

A new entity was found through the relationship '...\Entity\User#userPreferences' that was not configured to cascade persist operations for entity: ...\Entity\UserPreferences@000000003ae25e5700000000a6eaafc9. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist  this association in the mapping for example @ManyToOne(..,cascade={"persist"}).

But what else should I do? User#userPreferences is configured to cascade persist but it doesn't. Am I getting something wrong here?

Body:
Bug was with

 * @ORM\Column(name="user_preferences_id", type="integer")

Your code should contain

 * @ORM\JoinColumn(name="user_preferences_id", referencedColumnName="id")

instead of this.


问:
what is the difference between @Transactional and @Transactional(readOnly=true)
Can anyone tell me what is the difference between @Transactional and @Transactional(readOnly=true) in spring/hibernate.

Why we need to use @Transactional/@Transactional(readOnly=true) annotations in Service layer and not in DAO layer?

Please advise

答:
@Transactional vs @Transactional(readOnly=true):

The boolean readOnly is by default, which means @Transactional = @Transactional(readOnly=false), which effectively means you are hinting that the method would require write access. For a method that doesn't need data modification, you would annotate it with readOnly=true. This doesn't mean that using the annotation will automatically handle that for you, though - you will still need your entity managers, etc set up to effectively use it. Check out this page for more info.

One main reasons why we put the annotation on the Service layer and not the DAO layer, is we usually define the business logic on the service layer, and a logic may require multiple database interactions, and having it on the service layer encapsulates all the db calls will be done in one transaction (e.g. a rollback on all the db calls if it fails, etc).


问:
Select first row after goup
I have the below query which return the name of a class which is less than 20 and if there is no class less than 20 it adds a new one. the problem is that when I delete a user from the class which was full than this query returns two row.
I need to get only the first row that returns.</p>

```<code>SELECT exam_venue AS venue
  FROM application
 WHERE class_level = 1
   AND rownumber = 1
 GROUP
    BY venue
HAVING COUNT(id) < 20
</code>```

答:
SELECT exam_venue AS venue FROM application WHERE class_level = 1 AND rownumber = 1
GROUP BY venue HAVING COUNT(id) < 20 LIMIT 0,1</p>

Title: Select first row after goup

Body:
I have the below query which return the name of a class which is less than 20 and if there is no class less than 20 it adds a new one. the problem is that when I delete a user from the class which was full than this query returns two row.
I need to get only the first row that returns.

SELECT exam_venue AS venue
  FROM application
 WHERE class_level = 1
   AND rownumber = 1
 GROUP
    BY venue
HAVING COUNT(id) < 20


答:
According to strcat spec:

"The behavior is undefined if the destination array is not large
  enough for the contents of both src and dest and the terminating null
  character."

Your destination array is "b", which is obviously not large enough to store contents of both "a" and "b", so you got an undefined behavior which resulted in modification of "a" string.

Title: Why after using strcat function original string changed?


问:
jquery, javascript - how to remove this parameter from variable
I have some coding and already pushed this into a variable. I would like to remove it and reinsert another value. Please note that I am programming a lot of the coding with perl. I would like to remove menu_mode value. Any tips would be a great since javascript/jquery are a new language to me.</p>

```<code>    print qq|
               \$("#extractparam").click(function () {
                   \$("#grapharea").html(" ");|;

    foreach my $num (1 .. $count)
    {
        if ($num eq 1)
        {
            print STDOUT qq|var params = \$("#volt$num").serializeArray();|;
        } else
        {
            print STDOUT qq|var volt$num = \$("#volt$num").serializeArray();|;
            print STDOUT qq|params = \$.merge(params, volt$num);|;
        }
    }

print qq|          params.push({ name: 'menu_mode', value: '3C-extractparameters' });
                   \$.get("./scripts/banana_extract.cgi", params, function(data){ \$("#paramselection").html(data) });

                   // would like to remove the menu_mode value

                   params.push({ name: 'menu_mode', value: '3D-extractparameters' });
                   \$.get("./scripts/banana_extract.cgi", params, function(data){ \$("#graphoptionselection").html(data) });

                    \$("#extractparam").removeAttr('style');
                    \$("#Execute_Button").css("background-color","lightblue");

               });
</code>```

答:
If I understand your question correctly you want this:

```<code>params.pop();
</code>```

That'll remove the last element from the array (the one you just pushed).

Body:
I have some coding and already pushed this into a variable. I would like to remove it and reinsert another value. Please note that I am programming a lot of the coding with perl. I would like to remove menu_mode value. Any tips would be a great since javascript/jquery are a new language to me.

    print qq|
               \$("#extractparam").click(function () {
                   \$("#grapharea").html(" ");|;

    foreach my $num (1 .. $count)
    {
        if ($num eq 1)
        {
            print STDOUT qq|var params = \$("#volt$num").serializeArray();|;
        } else
        {
            print STDOUT qq|var volt$num = \$("#volt$num").serializeArray();|;
            print STDOUT qq|params = \$.merge(params, volt$num);|;
        }
    }

print qq|          params.push({ name: 'menu_mode', value: '3C-extractparameters' });
                   \$.get("./scripts/banana_extract.cgi", params, function(data){ \$("#paramselection").html(data) });

                   // would like to remove the menu_mode value

                   params.push({ name: 'menu_mode', value: '3D-extractparameters' });
                   \$.get("./scripts/banana_extract.cgi", params, function(data){ \$("#graphoptionselection").html(data) });

                    \$("#extractparam").removeAttr('style');
                    \$("#Execute_Button").css("background-color","lightblue");

               });

Body:
If I understand your question correctly you want this:

params.pop();

That'll remove the last element from the array (the one you just pushed).


问:
Generic list and for-each loop
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

```<code>public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}
</code>```

I am not sure why is this error as i am using generic list ?

答:
The fix is very simple. Instead of:

```<code> TestThrows testThrows = new TestThrows();
</code>```

use:

```<code>TestThrows<Throwable> testThrows = new TestThrows<Throwable>();
</code>```

Title: Generic list and for-each loop

Body:
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}

I am not sure why is this error as i am using generic list ?

Body:
The fix is very simple. Instead of:

 TestThrows testThrows = new TestThrows();

use:

TestThrows<Throwable> testThrows = new TestThrows<Throwable>();


问:
print lines after finding a key word in perl
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

```<code>$string=~ /apple /;
</code>```

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

答:
Just keep a flag variable, set it to true when you see the string, print if the flag is true.</p>

```<code>perl -ne 'print if $seen ||= /apple/'
</code>```

Body:
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

$string=~ /apple /;

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

Body:
Just keep a flag variable, set it to true when you see the string, print if the flag is true.

perl -ne 'print if $seen ||= /apple/'


问:
Generate entities with cascade delete
I am generating entities for our large database via JBoss hibernate reverse engineering. I was hoping to see cascade annotations in entities, but did not see them on generation.

Is there a way to direct hibernate to consider foreign keys and generate entities with cascade annotations?

答:
Unfortunately, it hasn't been documented although this is possible.
It should have been documented at 6.2.4.3. foreign-key.

Look at hibernate-reverse-engineering-3.0.dtd, there's a cascade attribute in elements :

foreign-key/many-to-one

foreign-key/one-to-one

foreign-key/inverse-one-to-one

foreign-key/set

The code is the truth !
Looking at it (hibernate-tools branch 5.2), we can see the possible values of cascade :

For Hibernate in org.hibernate.tool.hbm2x.pojo.EntityPOJOClass#getHibernateCascadeTypeAnnotation :
https://github.com/hibernate/hibernate-tools/blob/5.2/src/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java#L497

Values are [ all-delete-orphan, delete-orphan, save-update, replicate, lock, evict ] (multiple accepted).

The enum type used is org.hibernate.annotations.CascadeType.

For JPA in org.hibernate.tool.hbm2x.pojo.EntityPOJOClass#getCascadeTypes :
https://github.com/hibernate/hibernate-tools/blob/5.2/src/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java#L421

Values are [ persist, merge, delete, refresh, all ] (multiple accepted).

The enum type used is javax.persistence.CascadeType.

Title: Generate entities with cascade delete


问:
DOMDocument missing in php5.6
I'm attempting to set up a store using opencart which i am honestly very new to.
I bought a theme and for some reason the team uses vqmod.
I was able to install the vqmod using:

localhost/mystore/vqmod/install

and i get this response.

VQMOD ALREADY INSTALLED!

Now, when i navigate to

localhost/mystore

An error pops up saying

DomDocument

The full error message is

```<code>VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod
</code>```

After a little research, i figured i had to install the php5.6-xml and php7.0-xml which i have.

However the error is still showing.

I went into the vqmod code and noticed the section raising the error is this.

```<code>if(!class_exists('DOMDocument')) {
        die('VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod');
    }
</code>```

which means there's a DOMDocument class i'm missing.

However, i have tried everything i've seen online.
From installing php-xml, purging php, installing php-dom,restarting apache2, checking phpinfo.

None of these seem to solve the issue.

How do i get the DOMDocument class?

答:
VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod

Best resolution which helped me is to write in PHP.ini:

```<code>extension=dom.so
</code>```

This will solve the issue :)

Title: DOMDocument missing in php5.6

Body:
I'm attempting to set up a store using opencart which i am honestly very new to.
I bought a theme and for some reason the team uses vqmod.
I was able to install the vqmod using:

localhost/mystore/vqmod/install

and i get this response.

VQMOD ALREADY INSTALLED!

Now, when i navigate to

localhost/mystore

An error pops up saying

DomDocument

The full error message is

VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod

After a little research, i figured i had to install the php5.6-xml and php7.0-xml which i have.

However the error is still showing.

I went into the vqmod code and noticed the section raising the error is this.

if(!class_exists('DOMDocument')) {
        die('VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod');
    }

which means there's a DOMDocument class i'm missing.

However, i have tried everything i've seen online.
From installing php-xml, purging php, installing php-dom,restarting apache2, checking phpinfo.

None of these seem to solve the issue.

How do i get the DOMDocument class?

Body:
VQMod::bootup - ERROR - YOU NEED THE PHP "DOMDocument" EXTENSION INSTALLED TO USE VQMod

Best resolution which helped me is to write in PHP.ini:

extension=dom.so

This will solve the issue :)


问:
Cast List<int> to List<string> in .NET 2.0
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

答:
result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()

replace the parameters result and listOfInt to your parameters

OwnerDisplayName: lomaxx


问:
neural network for sudoku solver
I recently started learning neural networks, and I thought that creating a sudoku solver would be a nice application for NN. I started learning them with backward propagation neural network, but later I figured that there are tens of neural networks. At this point, I find it hard to learn all of them and then pick an appropriate one for my purpose. Hence, I am asking what would be a good choice for creating this solver. Can back propagation NN work here? If not, can you explain why and tell me which one can work.
Thanks!</p>

答:
Just like was mentioned in the comments, you probably want to take a look at convolutional networks. You basically input the sudoku bord as an two dimensional 'image'. I think using a receptive field of 3x3 would be quite interesting, and I don't really think you need more than one filter.

The harder thing is normalization: the numbers 1-9 don't have an underlying relation in sudoku, you could easily replace them by A-I for example. So they are categories, not numbers. However, one-hot encoding every output would mean a lot of inputs, so i'd stick to numerical normalization (1=0.1, 2 = 0.2, etc.)

The output of your network should be a softmax with of some kind: if you don't use softmax, and instead outupt just an x and y coordinate, then you can't assure that the outputedd square has not been filled in yet.

A numerical value should be passed along with the output, to show what number the network wants to fill in.

Title: neural network for sudoku solver


问:
mongodb java driver - raw command?
Is it possible to execute raw commands as javascript through the Java driver for MongoDB?

I'm tired of wrapping everything in Java objects using Rhino, and would happily sacrifice performance for the convenience of passing javascript directly through to the DB.

If not, I can always use sleepymongoose or something, but I don't really want to add yet another language (python) to the stack at this point.

Any insights are appreciated.

答:
actually no. This command(String) can run any kind of mongo database commands, not arbitrary javascript. For the latter you would need DB.eval() which would block your whole DB unless you are using 1.7.2 mongo or later and the noblock option set.

references:
http://api.mongodb.org/java/2.4-rc0/index.html
http://mongodb.onconfluence.com/display/DOCS/List+of+Database+Commands

Title: mongodb java driver - raw command?


问:
When connecting to an API do I need an access token per each user using my application?
I'm connected to an API that provides information about cars based on their registration. According to the docs the api can provide both user specific data and general data about the registration supplied.

I am using the connection method which does require specific users data, and therefore does not require me to gain access to any specific users account.

On my end users will visit my application and enter a registration number which I will use to call the API and return all of the information about the car.

Am I right in my thinking that my application is essentially the 'user' as far as the api is concerned, and I will only need to use one access token. I can then use this access token to make multiple API calls (one for each user that searches on my application)?

Or will i need to set up an access token for each user that visits my application and treat them separately.

答:
Only your application making the API requests requires a token, unless the licence agreement/documentation of this car API says otherwise.

As far as your users are concerned, your application is just magically sourcing the registration info from its database.


问:
'CREATE VIEW' must be the first statement in a query batch
Basically its what the title says. This is my code.

```<code>USE Assignment2;
GO

/* Player View (2 marks)
    Create a view which shows the following details of all players:
        • The ID number of the player
        • The first name and surname of the player concatenated and given an alias of “full_name”
        • The team ID number of the player (if applicable)
        • The team name of the player (if applicable)
        • The coach ID number of the player (if applicable)
        • The name of the player’s coach (if applicable)

   Creating this view requires a select statement using multiple joins and concatenation of names.
   Make sure that you use the appropriate type of join to ensure that players without teams or coaches are still included in the results.

*/

-- Write your Player View here
PRINT 'Creating Player View'

CREATE VIEW playerView AS
SELECT player.id, player.firstName + ' ' + player.surname AS 'Full name', player.team, team.name, player.coach, coach.firstName, coach.surname
FROM player
LEFT OUTER JOIN team
    ON player.team = team.id
    LEFT OUTER JOIN player as coach
        ON player.coach = coach.id;

GO
/* Race View (3 marks)
   Create a view which shows the following details of all races:
        • All of the columns in the race table
        • The name of the race type, course and team involved in the race
        • The full name of the player observing the race and the full name of the MVP (if applicable)
        • A calculated column with an alias of “unpenalised_score”, which adds the points penalised to the final score

   Creating this view requires a select statement using multiple joins and concatenation of names.
   Make sure that you use the appropriate type of join to ensure that races without MVPs are still included in the results.
*/

-- Write your Race View here
PRINT 'Creating Race View'

CREATE VIEW raceView AS
SELECT race.id, race.dateOfRace, race.raceType, raceType.name AS raceTypeName, race.course, course.name AS courseName, race.team, team.name AS teamName, race.observer, obs.firstName + ' ' + obs.surname AS observer_name, race.mvp, mvp.firstName + ' ' + mvp.surname AS mvp_name, race.pointsPenalised, race.finalScore + race.pointsPenalised AS unpenalised_score, race.finalScore
FROM race
INNER JOIN raceType
    ON race.raceType = raceType.id
    INNER JOIN course
        ON race.course = course.id
        INNER JOIN team
            ON race.team = team.id
            LEFT OUTER JOIN player AS mvp
                ON race.mvp = mvp.id
                LEFT OUTER JOIN player AS obs
                    ON race.observer = obs.id;
GO

SELECT *
FROM playerView

SELECT *
FROM raceView

/* Additional Information:
   The views are very convenient replacements for the tables they represent, as they include the names and calculated values that you will often need in queries.
   You are very much encouraged to use the views to simplify the queries that follow.  You can use a view in a SELECT statement in exactly the same way as you can use a table.

   If you wish to create additional views to simplify the queries which follow, include them in this file.
*/
</code>```

When I run each CREATE VIEW separately, it seems to run it correctly with no errors. But when I try to run the entire script, it gives me this error.

Msg 111, Level 15, State 1, Line 20

  'CREATE VIEW' must be the first statement in a query batch.

  Msg 111, Level 15, State 1, Line 15

  'CREATE VIEW' must be the first statement in a query batch.

  Msg 208, Level 16, State 1, Line 2

  Invalid object name 'playerView'.

Before attempting to run this script, I first delete database, recreate the tables, populate them and then run this script.

Any ideas where I'm going wrong?

答:
Put the CREATE VIEW Code inside EXECUTE</p>

```<code>SOME CONDITION..

EXECUTE('CREATE  VIEW vwName...')
</code>```

Body:
Basically its what the title says. This is my code.

USE Assignment2;
GO

/* Player View (2 marks)
    Create a view which shows the following details of all players:
        • The ID number of the player
        • The first name and surname of the player concatenated and given an alias of “full_name”
        • The team ID number of the player (if applicable)
        • The team name of the player (if applicable)
        • The coach ID number of the player (if applicable)
        • The name of the player’s coach (if applicable)

   Creating this view requires a select statement using multiple joins and concatenation of names.
   Make sure that you use the appropriate type of join to ensure that players without teams or coaches are still included in the results.

*/

-- Write your Player View here
PRINT 'Creating Player View'

CREATE VIEW playerView AS
SELECT player.id, player.firstName + ' ' + player.surname AS 'Full name', player.team, team.name, player.coach, coach.firstName, coach.surname
FROM player
LEFT OUTER JOIN team
    ON player.team = team.id
    LEFT OUTER JOIN player as coach
        ON player.coach = coach.id;

GO
/* Race View (3 marks)
   Create a view which shows the following details of all races:
        • All of the columns in the race table
        • The name of the race type, course and team involved in the race
        • The full name of the player observing the race and the full name of the MVP (if applicable)
        • A calculated column with an alias of “unpenalised_score”, which adds the points penalised to the final score

   Creating this view requires a select statement using multiple joins and concatenation of names.
   Make sure that you use the appropriate type of join to ensure that races without MVPs are still included in the results.
*/

-- Write your Race View here
PRINT 'Creating Race View'

CREATE VIEW raceView AS
SELECT race.id, race.dateOfRace, race.raceType, raceType.name AS raceTypeName, race.course, course.name AS courseName, race.team, team.name AS teamName, race.observer, obs.firstName + ' ' + obs.surname AS observer_name, race.mvp, mvp.firstName + ' ' + mvp.surname AS mvp_name, race.pointsPenalised, race.finalScore + race.pointsPenalised AS unpenalised_score, race.finalScore
FROM race
INNER JOIN raceType
    ON race.raceType = raceType.id
    INNER JOIN course
        ON race.course = course.id
        INNER JOIN team
            ON race.team = team.id
            LEFT OUTER JOIN player AS mvp
                ON race.mvp = mvp.id
                LEFT OUTER JOIN player AS obs
                    ON race.observer = obs.id;
GO

SELECT *
FROM playerView

SELECT *
FROM raceView

/* Additional Information:
   The views are very convenient replacements for the tables they represent, as they include the names and calculated values that you will often need in queries.
   You are very much encouraged to use the views to simplify the queries that follow.  You can use a view in a SELECT statement in exactly the same way as you can use a table.

   If you wish to create additional views to simplify the queries which follow, include them in this file.
*/

When I run each CREATE VIEW separately, it seems to run it correctly with no errors. But when I try to run the entire script, it gives me this error.

Msg 111, Level 15, State 1, Line 20

  'CREATE VIEW' must be the first statement in a query batch.

  Msg 111, Level 15, State 1, Line 15

  'CREATE VIEW' must be the first statement in a query batch.

  Msg 208, Level 16, State 1, Line 2

  Invalid object name 'playerView'.

Before attempting to run this script, I first delete database, recreate the tables, populate them and then run this script.

Any ideas where I'm going wrong?

Body:
Put the CREATE VIEW Code inside EXECUTE

SOME CONDITION..

EXECUTE('CREATE  VIEW vwName...')


答:
Prior to version 5.0, FriendlyId overrode the default finder methods to perform friendly finds all the time

It will use both columns slug and id to find record when you use find method, if you want it is searched only by id, you need to change code to something like:

company = Company.where(id: "1403045688").take

Title: Unexpected behavior while in Rails console

Body:
Rails 3.2

I am in a Rails console session, and I am trying to find a company by id. I have a companies tables, with an id column.

I did

company = Company.find_by_id("1403045688")

Here's what I got in the console:

  Company Load (161.2ms)  SELECT `companies`.* FROM `companies` WHERE `companies`.`slug` = '1403045688' LIMIT 1
  EXPLAIN (162.2ms)  EXPLAIN SELECT `companies`.* FROM `companies` WHERE `companies`.`slug` = '1403045688' LIMIT 1
EXPLAIN for: SELECT  `companies`.* FROM `companies`  WHERE `companies`.`slug` = '1403045688' LIMIT 1
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                                               |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
|  1 | SIMPLE      | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | Impossible WHERE noticed after reading const tables |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
1 row in set (0.20 sec)

  Company Load (1.6ms)  SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = '1403045688' LIMIT 1
  EXPLAIN (80.7ms)  EXPLAIN SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = '1403045688' LIMIT 1
EXPLAIN for: SELECT  `companies`.* FROM `companies`  WHERE `companies`.`id` = '1403045688' LIMIT 1
+----+-------------+-----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table     | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+-----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | companies | const | PRIMARY       | PRIMARY | 182     | const |    1 |       |
+----+-------------+-----------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.08 sec)

=> #<Company id: "1403045688", name: "AAA Electric", slug: "aaa-electric-inc", created_at: "2014-06-17 22:54:48", updated_at: "2016-03-12 05:13:26">

Shouldn't it go straight to search by id, instead of trying first to look using the slug? and why does it seem to be confused, and wants to have the query explained?


问:
Sharepoint 2010 Custom Webpart - Access Denied Error
we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.

Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.

Below is the backend code

```<code>using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace Test.TestWebPart
{

    public partial class TestWebPartUserControl : UserControl
    {
        //Global variable call
        private SPSite thisSite = SPContext.Current.Site;
        private SPWebCollection thisWeb;
        private DataTable dt;
        private SPListCollection siteLists;
        private DataTableWrapper myDataTable;

        //Occurs when the page loads
        protected void Page_Load(object sender, EventArgs e)
        {
            //Pulls all the websites in the site into a webcollection
            thisWeb = thisSite.AllWebs;

            //If the page is not postback call BindToGrid()
            if (!Page.IsPostBack)
            {
                BindToGrid();
            }
        }

        private void BindToGrid()
        {
            //Create a new DataTable along with the columns and headers
            dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Created");
            dt.Columns.Add("List");

            //Call to populate the DataTable
            dt = SelectData();

            //Populate DataTableWrapper class and get the type
            myDataTable = new DataTableWrapper(dt);
            Type t = myDataTable.GetType();

            //Create a ObjectDataSource to hold data and bind to spgridview
            ObjectDataSource ds = new ObjectDataSource();
            ds.ID = "myDataSource";
            ds.TypeName = t.AssemblyQualifiedName;
            ds.SelectMethod = "GetTable";
            ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
            this.Controls.Add(ds);

            grid.ID = "gridID";

            BoundField column = new BoundField();
            column.DataField = "Title";
            column.HtmlEncode = false;
            //column.SortExpression = "Title";
            column.HeaderText = "Title";
            grid.Columns.Add(column);

            BoundField column1 = new BoundField();
            column1.DataField = "Created";
            column1.HtmlEncode = true;
            //column1.SortExpression = "Created";
            column1.HeaderText = "Created";
            grid.Columns.Add(column1);

            BoundField column2 = new BoundField();
            column2.DataField = "List";
            column2.HtmlEncode = false;
            //column2.SortExpression = "List";
            column2.HeaderText = "List";
            grid.Columns.Add(column2);

            //Provide the SPGridview with the DataSource
            grid.DataSourceID = "myDataSource";
            this.Controls.Add(grid);

            //grid.PageSize =10;
            //grid.AllowPaging = true;

            //Default Pagination - commented out due to not working
            //grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
            //grid.PagerTemplate = null;

            //Bind the data to the grid
            grid.DataBind();

        }

        //private void GenerateColumns()
        //{

        //}

        //Used to deal with the PageIndexChange event
        void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            grid.DataBind();
        }

        //Used to deal with the ObjectCreated event
        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            myDataTable = new DataTableWrapper(dt);
            e.ObjectInstance = myDataTable;
        }

        //Pulls the data from lists which will be displayed
        public DataTable SelectData()
        {
            try
            {
                //Create a new instance of type DataRow
                DataRow row;

                //Loop through each website in the webcollection
                foreach (SPWeb web in thisWeb)
                {
                    //Pull the lists from the site into a list collection
                    siteLists = web.Lists;
                    //Display only lists the current user has access to
                    siteLists.ListsForCurrentUser = true;

                    //Loop through each list within the list collection
                    foreach (SPList list in siteLists)
                    {

                            //If the list is an announcement list continue otherwise skip
                            if (list.BaseTemplate.ToString() == "Announcements")
                            {
                                //Exclude the lists stated from those whose data will be collected
                                if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
                                {
                                }
                                else
                                {
                                    //Create a item collection for each item within the current list
                                    SPListItemCollection listItem = list.Items;

                                    //Loop through each item within the item collection
                                    foreach (SPListItem item in listItem)
                                    {
                                        //Get the url of the current website
                                        string weburl = web.Url;
                                        //Gets the URL of the current item
                                        string dispurl = item.ContentType.DisplayFormUrl;
                                        dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

                                        //Joins together the full URL for the current item into a single variable
                                        dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
                                        //Create a new in the datatable as an instance of row
                                        row = dt.Rows.Add();

                                        //Put the correct information and links into the correct column
                                        row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
                                        row["Created"] = item["Created"].ToString();
                                        row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
                                    }
                                }
                            }
                    }
                }
                //Return the completed DataTable
                return dt;
            }

            //Exception to catch any errors
            catch (Exception s)
            {
                return dt;
            }
        }
    }
}
</code>```

Thanks

答:
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-</p>

```<code>using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace Test.TestWebPart
{
    public partial class TestWebPartUserControl : UserControl
    {
        //Global variable call
        private SPSite thisSite = SPContext.Current.Site;
        //private SPWebCollection thisWeb;//
        private SPWeb thisWeb = SPContext.Current.Web;
        private DataTable dt;
        private SPListCollection siteLists;
        private DataTableWrapper myDataTable;

        //Occurs when the page loads
        protected void Page_Load(object sender, EventArgs e)
        {
            //Pulls all the websites in the site into a webcollection
            //thisWeb = thisSite.AllWebs.;//

            //If the page is not postback call BindToGrid()
            if (!Page.IsPostBack)
            {
                BindToGrid();
            }
        }

        private void BindToGrid()
        {
            //Create a new DataTable along with the columns and headers
            dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Created");
            dt.Columns.Add("List");

            //Call to populate the DataTable
            dt = SelectData();

            //Populate DataTableWrapper class and get the type
            myDataTable = new DataTableWrapper(dt);
            Type t = myDataTable.GetType();

            //Create a ObjectDataSource to hold data and bind to spgridview
            ObjectDataSource ds = new ObjectDataSource();
            ds.ID = "myDataSource";
            ds.TypeName = t.AssemblyQualifiedName;
            ds.SelectMethod = "GetTable";
            ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
            this.Controls.Add(ds);

            grid.ID = "gridID";

            //Sorting, Filtering & paging does not work so has been commented out for now
            //this.grid.AllowSorting = true;

            //Bind the three columns to the SPGridView
            //HtmlEncode must be false for the links to appear as true html
            BoundField column = new BoundField();
            column.DataField = "Title";
            column.HtmlEncode = false;
            //column.SortExpression = "Title";
            column.HeaderText = "Title";
            grid.Columns.Add(column);

            BoundField column1 = new BoundField();
            column1.DataField = "Created";
            column1.HtmlEncode = true;
            //column1.SortExpression = "Created";
            column1.HeaderText = "Created";
            grid.Columns.Add(column1);

            BoundField column2 = new BoundField();
            column2.DataField = "List";
            column2.HtmlEncode = false;
            //column2.SortExpression = "List";
            column2.HeaderText = "List";
            grid.Columns.Add(column2);

            //Has been commented out due to these sections not working
            //grid.AllowFiltering = true;

            //grid.FilterDataFields = "Title";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //grid.FilterDataFields = "Created";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //grid.FilterDataFields = "ListName";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //Provide the SPGridview with the DataSource
            grid.DataSourceID = "myDataSource";
            this.Controls.Add(grid);

            //grid.PageSize =10;
            //grid.AllowPaging = true;

            //Default Pagination - commented out due to not working
            //grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
            //grid.PagerTemplate = null;

            //Bind the data to the grid
            grid.DataBind();

        }

        //private void GenerateColumns()
        //{

        //}

        //Used to deal with the PageIndexChange event
        void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            grid.DataBind();
        }

        //Used to deal with the ObjectCreated event
        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            myDataTable = new DataTableWrapper(dt);
            e.ObjectInstance = myDataTable;
        }

        //Pulls the data from lists which will be displayed
        public DataTable SelectData()
        {
            try
            {
                //Create a new instance of type DataRow
                DataRow row;

                //Loop through each website in the webcollection

                {
                    //Pull the lists from the site into a list collection
                    siteLists = thisWeb.Lists;
                    //Display only lists the current user has access to
                    siteLists.ListsForCurrentUser = true;

                    SPBasePermissions perms = SPBasePermissions.ViewListItems;

                    //Loop through each list within the list collection
                    foreach (SPList list in siteLists)
                    {
                        if (list.DoesUserHavePermissions(perms))
                        {
                            //If the list is an announcement list continue otherwise skip
                            if (list.BaseTemplate.ToString() == "Announcements")
                            {
                                //Exclude the lists stated from those whose data will be collected
                                if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
                                {
                                }
                                else
                                {
                                    //Create a item collection for each item within the current list
                                    SPListItemCollection listItem = list.Items;

                                    //Loop through each item within the item collection
                                    foreach (SPListItem item in listItem)
                                    {
                                        //Get the url of the current website
                                        string weburl = thisWeb.Url;
                                        //Gets the URL of the current item
                                        string dispurl = item.ContentType.DisplayFormUrl;
                                        dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

                                        //Joins together the full URL for the current item into a single variable
                                        dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
                                        //Create a new in the datatable as an instance of row
                                        row = dt.Rows.Add();

                                        //Put the correct information and links into the correct column
                                        row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
                                        row["Created"] = item["Created"].ToString();
                                        row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
                                    }
                                }
                            }
                        }
                    }
                }
                //Return the completed DataTable
                return dt;
            }

            //Exception to catch any errors
            catch (Exception s)
            {
                return dt;
            }
        }
    }
}
</code>```

Body:
we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.

Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.

Below is the backend code

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace Test.TestWebPart
{

    public partial class TestWebPartUserControl : UserControl
    {
        //Global variable call
        private SPSite thisSite = SPContext.Current.Site;
        private SPWebCollection thisWeb;
        private DataTable dt;
        private SPListCollection siteLists;
        private DataTableWrapper myDataTable;

        //Occurs when the page loads
        protected void Page_Load(object sender, EventArgs e)
        {
            //Pulls all the websites in the site into a webcollection
            thisWeb = thisSite.AllWebs;

            //If the page is not postback call BindToGrid()
            if (!Page.IsPostBack)
            {
                BindToGrid();
            }
        }

        private void BindToGrid()
        {
            //Create a new DataTable along with the columns and headers
            dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Created");
            dt.Columns.Add("List");

            //Call to populate the DataTable
            dt = SelectData();

            //Populate DataTableWrapper class and get the type
            myDataTable = new DataTableWrapper(dt);
            Type t = myDataTable.GetType();

            //Create a ObjectDataSource to hold data and bind to spgridview
            ObjectDataSource ds = new ObjectDataSource();
            ds.ID = "myDataSource";
            ds.TypeName = t.AssemblyQualifiedName;
            ds.SelectMethod = "GetTable";
            ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
            this.Controls.Add(ds);

            grid.ID = "gridID";

            BoundField column = new BoundField();
            column.DataField = "Title";
            column.HtmlEncode = false;
            //column.SortExpression = "Title";
            column.HeaderText = "Title";
            grid.Columns.Add(column);

            BoundField column1 = new BoundField();
            column1.DataField = "Created";
            column1.HtmlEncode = true;
            //column1.SortExpression = "Created";
            column1.HeaderText = "Created";
            grid.Columns.Add(column1);

            BoundField column2 = new BoundField();
            column2.DataField = "List";
            column2.HtmlEncode = false;
            //column2.SortExpression = "List";
            column2.HeaderText = "List";
            grid.Columns.Add(column2);

            //Provide the SPGridview with the DataSource
            grid.DataSourceID = "myDataSource";
            this.Controls.Add(grid);

            //grid.PageSize =10;
            //grid.AllowPaging = true;

            //Default Pagination - commented out due to not working
            //grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
            //grid.PagerTemplate = null;

            //Bind the data to the grid
            grid.DataBind();

        }

        //private void GenerateColumns()
        //{

        //}

        //Used to deal with the PageIndexChange event
        void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            grid.DataBind();
        }

        //Used to deal with the ObjectCreated event
        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            myDataTable = new DataTableWrapper(dt);
            e.ObjectInstance = myDataTable;
        }

        //Pulls the data from lists which will be displayed
        public DataTable SelectData()
        {
            try
            {
                //Create a new instance of type DataRow
                DataRow row;

                //Loop through each website in the webcollection
                foreach (SPWeb web in thisWeb)
                {
                    //Pull the lists from the site into a list collection
                    siteLists = web.Lists;
                    //Display only lists the current user has access to
                    siteLists.ListsForCurrentUser = true;

                    //Loop through each list within the list collection
                    foreach (SPList list in siteLists)
                    {

                            //If the list is an announcement list continue otherwise skip
                            if (list.BaseTemplate.ToString() == "Announcements")
                            {
                                //Exclude the lists stated from those whose data will be collected
                                if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
                                {
                                }
                                else
                                {
                                    //Create a item collection for each item within the current list
                                    SPListItemCollection listItem = list.Items;

                                    //Loop through each item within the item collection
                                    foreach (SPListItem item in listItem)
                                    {
                                        //Get the url of the current website
                                        string weburl = web.Url;
                                        //Gets the URL of the current item
                                        string dispurl = item.ContentType.DisplayFormUrl;
                                        dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

                                        //Joins together the full URL for the current item into a single variable
                                        dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
                                        //Create a new in the datatable as an instance of row
                                        row = dt.Rows.Add();

                                        //Put the correct information and links into the correct column
                                        row["Title"] = "" + item["Title"].ToString() + "";
                                        row["Created"] = item["Created"].ToString();
                                        row["List"] = "" + list.Title + "";
                                    }
                                }
                            }
                    }
                }
                //Return the completed DataTable
                return dt;
            }

            //Exception to catch any errors
            catch (Exception s)
            {
                return dt;
            }
        }
    }
}

Thanks

Body:
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace Test.TestWebPart
{
    public partial class TestWebPartUserControl : UserControl
    {
        //Global variable call
        private SPSite thisSite = SPContext.Current.Site;
        //private SPWebCollection thisWeb;//
        private SPWeb thisWeb = SPContext.Current.Web;
        private DataTable dt;
        private SPListCollection siteLists;
        private DataTableWrapper myDataTable;

        //Occurs when the page loads
        protected void Page_Load(object sender, EventArgs e)
        {
            //Pulls all the websites in the site into a webcollection
            //thisWeb = thisSite.AllWebs.;//

            //If the page is not postback call BindToGrid()
            if (!Page.IsPostBack)
            {
                BindToGrid();
            }
        }

        private void BindToGrid()
        {
            //Create a new DataTable along with the columns and headers
            dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Created");
            dt.Columns.Add("List");

            //Call to populate the DataTable
            dt = SelectData();

            //Populate DataTableWrapper class and get the type
            myDataTable = new DataTableWrapper(dt);
            Type t = myDataTable.GetType();

            //Create a ObjectDataSource to hold data and bind to spgridview
            ObjectDataSource ds = new ObjectDataSource();
            ds.ID = "myDataSource";
            ds.TypeName = t.AssemblyQualifiedName;
            ds.SelectMethod = "GetTable";
            ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
            this.Controls.Add(ds);

            grid.ID = "gridID";

            //Sorting, Filtering & paging does not work so has been commented out for now
            //this.grid.AllowSorting = true;

            //Bind the three columns to the SPGridView
            //HtmlEncode must be false for the links to appear as true html
            BoundField column = new BoundField();
            column.DataField = "Title";
            column.HtmlEncode = false;
            //column.SortExpression = "Title";
            column.HeaderText = "Title";
            grid.Columns.Add(column);

            BoundField column1 = new BoundField();
            column1.DataField = "Created";
            column1.HtmlEncode = true;
            //column1.SortExpression = "Created";
            column1.HeaderText = "Created";
            grid.Columns.Add(column1);

            BoundField column2 = new BoundField();
            column2.DataField = "List";
            column2.HtmlEncode = false;
            //column2.SortExpression = "List";
            column2.HeaderText = "List";
            grid.Columns.Add(column2);

            //Has been commented out due to these sections not working
            //grid.AllowFiltering = true;

            //grid.FilterDataFields = "Title";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //grid.FilterDataFields = "Created";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //grid.FilterDataFields = "ListName";
            //grid.FilteredDataSourcePropertyName = "FilterExpression";
            //grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";

            //Provide the SPGridview with the DataSource
            grid.DataSourceID = "myDataSource";
            this.Controls.Add(grid);

            //grid.PageSize =10;
            //grid.AllowPaging = true;

            //Default Pagination - commented out due to not working
            //grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
            //grid.PagerTemplate = null;

            //Bind the data to the grid
            grid.DataBind();

        }

        //private void GenerateColumns()
        //{

        //}

        //Used to deal with the PageIndexChange event
        void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            grid.DataBind();
        }

        //Used to deal with the ObjectCreated event
        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            myDataTable = new DataTableWrapper(dt);
            e.ObjectInstance = myDataTable;
        }

        //Pulls the data from lists which will be displayed
        public DataTable SelectData()
        {
            try
            {
                //Create a new instance of type DataRow
                DataRow row;

                //Loop through each website in the webcollection

                {
                    //Pull the lists from the site into a list collection
                    siteLists = thisWeb.Lists;
                    //Display only lists the current user has access to
                    siteLists.ListsForCurrentUser = true;

                    SPBasePermissions perms = SPBasePermissions.ViewListItems;

                    //Loop through each list within the list collection
                    foreach (SPList list in siteLists)
                    {
                        if (list.DoesUserHavePermissions(perms))
                        {
                            //If the list is an announcement list continue otherwise skip
                            if (list.BaseTemplate.ToString() == "Announcements")
                            {
                                //Exclude the lists stated from those whose data will be collected
                                if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
                                {
                                }
                                else
                                {
                                    //Create a item collection for each item within the current list
                                    SPListItemCollection listItem = list.Items;

                                    //Loop through each item within the item collection
                                    foreach (SPListItem item in listItem)
                                    {
                                        //Get the url of the current website
                                        string weburl = thisWeb.Url;
                                        //Gets the URL of the current item
                                        string dispurl = item.ContentType.DisplayFormUrl;
                                        dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

                                        //Joins together the full URL for the current item into a single variable
                                        dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
                                        //Create a new in the datatable as an instance of row
                                        row = dt.Rows.Add();

                                        //Put the correct information and links into the correct column
                                        row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
                                        row["Created"] = item["Created"].ToString();
                                        row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
                                    }
                                }
                            }
                        }
                    }
                }
                //Return the completed DataTable
                return dt;
            }

            //Exception to catch any errors
            catch (Exception s)
            {
                return dt;
            }
        }
    }
}