问:
Why i receive HttpClientErrorException 406 if mediaType is set?
Collegues, i have the method which should send post request into web service

```<code>public void postPmnt(Document doc) throws TransformerException, HttpServerErrorException {

        RestTemplate rt = new RestTemplate();

        String uri = new String(environment.getProperty("rest.server.endpoint") + environment.getProperty("rest.server.resource"));

        String body = pmonCommons.xmlDocToString(doc);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_XML);
            stringHttpMessageConverter.setSupportedMediaTypes(mediaTypes);

        messageConverters.add(stringHttpMessageConverter);
        rt.setMessageConverters(messageConverters);

        rt.getInterceptors().add(new BasicAuthorizationInterceptor(environment.getProperty("rest.server.user"), environment.getProperty("rest.server.pass")));

//        rt.getInterceptors().add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_XML_VALUE));
//        rt.getInterceptors().add(new HeaderRequestInterceptor("Content-Type", MediaType.APPLICATION_XML_VALUE));

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_XML);
//        headers.setAccept(mediaTypes);

        HttpEntity<String> request = new HttpEntity<>(body);

         log.info("Call rt");
        // ResponseEntity<String> response = rt.postForEntity(uri, request, String.class);
         ResponseEntity<String> response = rt.exchange(uri, HttpMethod.POST, request, String.class);

        }
}
</code>```

As you see i'am trying to use some difference variant of code but the result is the same.

The stacttrace looks like:

```<code>10:59:55.645 DEBUG [main] o.s.c.e.PropertySourcesPropertyResolver - Found key 'rest.server.pass' in [class path resource [pmon-dev.properties]] with type [String]
10:59:55.647 INFO  [main] com.pivotal.pmon.rest.Client - Call rt
10:59:55.667 DEBUG [main] o.s.web.client.RestTemplate - Created POST request for "https://uat.pivotal.com/API/Pay"
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Setting request Accept header to [application/xml]
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Writing [<?xml version="1.0" encoding="UTF-8"?><Document>....
data...
</Document>
] using [org.springframework.http.converter.StringHttpMessageConverter@5012c571]
10:59:56.992 DEBUG [main] o.s.web.client.RestTemplate - POST request for "https://uat.pivotal.com/API/Pay" resulted in 406 (null); invoking error handler
10:59:56.997 TRACE [main] o.s.test.context.TestContextManager - afterTestMethod(): instance [com.pivotal.pmon.rest.ClientTest@69b794e2], method [public void com.pivotal.pmon.rest.ClientTest.postPmnt() throws java.lang.Exception], exception [org.springframework.web.client.HttpClientErrorException: 406 null]
10:59:56.998 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = com.pivotal.pmon.rest.ClientTest@69b794e2, testMethod = postPmnt@ClientTest, testException = org.springframework.web.client.HttpClientErrorException: 406 null, mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].

org.springframework.web.client.HttpClientErrorException: 406 null

    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.pivotal.pmon.rest.Client.postPmnt(Client.java:84)
    at com.pivotal.pmon.rest.ClientTest.postPmnt(ClientTest.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

10:59:57.009 TRACE [main] o.s.test.context.TestContextManager - afterTestClass(): class [com.pivotal.pmon.rest.ClientTest]
10:59:57.009 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
10:59:57.012 INFO  [Thread-1] o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support......
Process finished with exit code -1
</code>```

Why i receive 406 error?
Is it because client can't parse the response?
How to avoid this error and read (print) response?

P.s. If I send the request from SoapUI than it works fine. In request header's Content-Type: application/xml;charset=UTF-8. Method: Post
Raw response looks like:

```<code>HTTP/1.1 400
Server: nginx/1.6.2
Date: Tue, 04 Jul 2017 06:56:15 GMT
Content-Type: application/xml
Content-Length: 734
Connection: keep-alive
X-Application-Context: pus.app.AuthProxy:test,db-vfactdb:8080
X-Frame-Options: DENY
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-Content-Type-Options: nosniff
Expires: 0
Pragma: no-cache
X-Application-Context: currency-pay:default:8080
X-XSS-Protection: 1; mode=block

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Document>...</Document>
</code>```

Thank you for any help.

答:
I think that the web service that you are using not only accepts XML and also return XML.
You can define a POJO corresponding to the XML that the web service returns. I think that you have already created this POJO and is the class Document.

Thus, the call to the web service should be

```<code>ResponseEntity<Document> response = rt.exchange(uri, HttpMethod.POST, request, Document.class);
</code>```

Let me know if this fixed your problem.

Body:
Collegues, i have the method which should send post request into web service

public void postPmnt(Document doc) throws TransformerException, HttpServerErrorException {

        RestTemplate rt = new RestTemplate();

        String uri = new String(environment.getProperty("rest.server.endpoint") + environment.getProperty("rest.server.resource"));

        String body = pmonCommons.xmlDocToString(doc);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_XML);
            stringHttpMessageConverter.setSupportedMediaTypes(mediaTypes);

        messageConverters.add(stringHttpMessageConverter);
        rt.setMessageConverters(messageConverters);

        rt.getInterceptors().add(new BasicAuthorizationInterceptor(environment.getProperty("rest.server.user"), environment.getProperty("rest.server.pass")));

//        rt.getInterceptors().add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_XML_VALUE));
//        rt.getInterceptors().add(new HeaderRequestInterceptor("Content-Type", MediaType.APPLICATION_XML_VALUE));

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_XML);
//        headers.setAccept(mediaTypes);

        HttpEntity<String> request = new HttpEntity<>(body);

         log.info("Call rt");
        // ResponseEntity<String> response = rt.postForEntity(uri, request, String.class);
         ResponseEntity<String> response = rt.exchange(uri, HttpMethod.POST, request, String.class);

        }
}

As you see i'am trying to use some difference variant of code but the result is the same.

The stacttrace looks like:

10:59:55.645 DEBUG [main] o.s.c.e.PropertySourcesPropertyResolver - Found key 'rest.server.pass' in [class path resource [pmon-dev.properties]] with type [String]
10:59:55.647 INFO  [main] com.pivotal.pmon.rest.Client - Call rt
10:59:55.667 DEBUG [main] o.s.web.client.RestTemplate - Created POST request for "https://uat.pivotal.com/API/Pay"
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Setting request Accept header to [application/xml]
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Writing [<?xml version="1.0" encoding="UTF-8"?><Document>....
data...
</Document>
] using [org.springframework.http.converter.StringHttpMessageConverter@5012c571]
10:59:56.992 DEBUG [main] o.s.web.client.RestTemplate - POST request for "https://uat.pivotal.com/API/Pay" resulted in 406 (null); invoking error handler
10:59:56.997 TRACE [main] o.s.test.context.TestContextManager - afterTestMethod(): instance [com.pivotal.pmon.rest.ClientTest@69b794e2], method [public void com.pivotal.pmon.rest.ClientTest.postPmnt() throws java.lang.Exception], exception [org.springframework.web.client.HttpClientErrorException: 406 null]
10:59:56.998 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = com.pivotal.pmon.rest.ClientTest@69b794e2, testMethod = postPmnt@ClientTest, testException = org.springframework.web.client.HttpClientErrorException: 406 null, mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].

org.springframework.web.client.HttpClientErrorException: 406 null

    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.pivotal.pmon.rest.Client.postPmnt(Client.java:84)
    at com.pivotal.pmon.rest.ClientTest.postPmnt(ClientTest.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

10:59:57.009 TRACE [main] o.s.test.context.TestContextManager - afterTestClass(): class [com.pivotal.pmon.rest.ClientTest]
10:59:57.009 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
10:59:57.012 INFO  [Thread-1] o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support......
Process finished with exit code -1

Why i receive 406 error?
Is it because client can't parse the response?
How to avoid this error and read (print) response?

P.s. If I send the request from SoapUI than it works fine. In request header's Content-Type: application/xml;charset=UTF-8. Method: Post
Raw response looks like:

HTTP/1.1 400
Server: nginx/1.6.2
Date: Tue, 04 Jul 2017 06:56:15 GMT
Content-Type: application/xml
Content-Length: 734
Connection: keep-alive
X-Application-Context: pus.app.AuthProxy:test,db-vfactdb:8080
X-Frame-Options: DENY
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-Content-Type-Options: nosniff
Expires: 0
Pragma: no-cache
X-Application-Context: currency-pay:default:8080
X-XSS-Protection: 1; mode=block

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Document>...</Document>

Thank you for any help.

Body:
I think that the web service that you are using not only accepts XML and also return XML.
You can define a POJO corresponding to the XML that the web service returns. I think that you have already created this POJO and is the class Document.

Thus, the call to the web service should be

ResponseEntity<Document> response = rt.exchange(uri, HttpMethod.POST, request, Document.class);

Let me know if this fixed your problem.


来源: stackexchange

问:
How to access Scope value outside the method in angularjs
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

```<code>app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});
</code>```

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?

答:
```<code>app.controller('MyController', function($scope, $http, $rootScope)
{
$scope.x = '';
$scope.y = '';
$http.get('javaAngularJS')
.then(function (response)
{
    var data = response.data;
    $scope.smsresult = data;
    //need to print following x and y values in below alert message
    $scope.x = $scope.smsresult.failure;
    $scope.y = $scope.smsresult.success;
});
alert($scope.x+"   "+$scope.y);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?


问:
Use variable from a different class for sorting a list: Android
I have a class as,

```<code>public class ACompanyForSearchResult {
String companyName;
int likes;
}
</code>```

And a list of it:

```<code> ArrayList<ACompanyForSearchResult> List = new ArrayList<ACompanyForSearchResult>();
</code>```

Here I am sorting it by name as,

```<code>/*To get the sorted value by name*/
private void sortName() {
Collections.sort(List, new Comparator<ACompanyForSearchResult>() {
     @Override
    public int compare(ACompanyForSearchResult aCompanyForSearchResult, ACompanyForSearchResult t1) {
            return (aCompanyForSearchResult.companyName).compareToIgnoreCase(t1.companyName);
        }
    });
  }
}
</code>```

Now I want the data to be sorted with respect to the city name which is in a different class BranchDetails as,

```<code>public class BranchDetails {
  String cityName;
}
</code>```

I want to use this cityName to sort the same above "List". But I am unable to access the cityName into the previous class. I am pretty new to android so please bear with me.

答:
Implement a Comparator:  </p>

```<code>   MyComparator extend  Comparator{
   Map<String ,String>  mMap=new HashMap();  key is  city, value is company

 public int  compare(BranchDetails  a , BranchDetails   b){
     if( mMap.get(a.cityName).compareto(mMap.get(b.cityName))==0){
     return a .cityName.compareto(b.cityName);
}else {
     return mMap.get(a.cityName).compareto(mMap.get(b.cityName));
}

}
</code>```

Body:
I have a class as,

public class ACompanyForSearchResult {
String companyName;
int likes;
}

And a list of it:

 ArrayList<ACompanyForSearchResult> List = new ArrayList<ACompanyForSearchResult>();

Here I am sorting it by name as,

/*To get the sorted value by name*/
private void sortName() {
Collections.sort(List, new Comparator<ACompanyForSearchResult>() {
     @Override
    public int compare(ACompanyForSearchResult aCompanyForSearchResult, ACompanyForSearchResult t1) {
            return (aCompanyForSearchResult.companyName).compareToIgnoreCase(t1.companyName);
        }
    });
  }
}

Now I want the data to be sorted with respect to the city name which is in a different class BranchDetails as,

public class BranchDetails {
  String cityName;
}

I want to use this cityName to sort the same above "List". But I am unable to access the cityName into the previous class. I am pretty new to android so please bear with me.

Body:
Implement a Comparator:

   MyComparator extend  Comparator{
   Map<String ,String>  mMap=new HashMap();  key is  city, value is company

 public int  compare(BranchDetails  a , BranchDetails   b){
     if( mMap.get(a.cityName).compareto(mMap.get(b.cityName))==0){
     return a .cityName.compareto(b.cityName);
}else {
     return mMap.get(a.cityName).compareto(mMap.get(b.cityName));
}

}


问:
Stored procedure query for selecting values
I have a Test table

```<code>CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,
</code>```

and Questions table as

```<code>CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,
</code>```

Questions table stores all the questions for each test with Tid as foreign key.

I want to write a stored procedure to fetch TestName, TestId and number of questions in each test in a single stored procedure. But I am unable to get this.

答:
Try this (table create, insert, proc creation and execution included);</p>

```<code>CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL)
go
CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL
)
go

 insert into [dbo].[Test]
 values('test #1',1,0)
 go
 insert into [dbo].[Questions]
 values(1,1,'what is life',0)
 go
 create proc dbo.MyInfo

 as

select
    t.TestName,
    t.TestId,
    [No Questions]=COUNT(q.Qid)
from
    [dbo].[Test] t
inner join
    [dbo].[Questions] q on t.TestId=q.Qid
group by
    t.TestName,
    t.TestId
go
exec dbo.MyInfo
go
</code>```

Body:
I have a Test table

CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,

and Questions table as

CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,

Questions table stores all the questions for each test with Tid as foreign key.

I want to write a stored procedure to fetch TestName, TestId and number of questions in each test in a single stored procedure. But I am unable to get this.

Body:
Try this (table create, insert, proc creation and execution included);

CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL)
go
CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL
)
go

 insert into [dbo].[Test]
 values('test #1',1,0)
 go
 insert into [dbo].[Questions]
 values(1,1,'what is life',0)
 go
 create proc dbo.MyInfo

 as

select
    t.TestName,
    t.TestId,
    [No Questions]=COUNT(q.Qid)
from
    [dbo].[Test] t
inner join
    [dbo].[Questions] q on t.TestId=q.Qid
group by
    t.TestName,
    t.TestId
go
exec dbo.MyInfo
go


问:
Destroy and unset session on certain pages only
Newbie question here but is it possible to unset session which was set. What I mean is I have file connection.php which make connection to database and it is included on each page/file.

There is one page search.php which I want to be accessible without user to be forced to log in. So what I have in the file is

```<code><?php
include 'connection.php';

      // some code which perform search here

?>
<html>
<head></head>
<body>
       search form here
</body>
</html>
</code>```

When I open the page is getting me to sign in page because I'm not logged. What I've tried is to put session destroy right after include of connection

```<code><?php
include 'connection.php';
session_destroy();
      // some code which perform search here

?>
</code>```

This doesn't help and still redirecting me to sign in page. Is there any chance I can work around this?

Update: I this is where I check and save the session

```<code><?php
$request = $_REQUEST;
if(!empty($request)) {
    $_SESSION['login'] = false;
    if (!empty($_REQUEST['email']) && !empty($_REQUEST['password']) ) {

        $password = md5($_REQUEST['password']);

        $sql = "select users query";

        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if ($row['type'] == 'admin' || $row['type'] == $_REQUEST['type'] ) {
                $_SESSION['user']=[
                    'id' => $row['id'],
                    'fname' => $row['fname'],
                    'email' => $row['email'],
                ];
                $_SESSION['login'] = true;
                if($_SESSION['user']['type'] == 'admin'){
                    header('Location: Approval.php');die;
                }
            }else {
                    header('Location: signup.php');die;
            }
        } else { $error = "Wrong Email and/or Password or Account not acitvated. Please try again."; }
    }
}
</code>```

答:
In your connection.php file you can have an array with file names you want to exclude like (add it before or after the line $request = $_REQUEST;):

```<code>$file_excludes = array("search.php", "anotherfile.php");
</code>```

Then get the current file being run and split the path (add it before the line if(!empty($request)) {):

```<code>$current_file = explode("/", __FILE__);
</code>```

Then modify the line:

```<code>if(!empty($request)) {
</code>```

To:

```<code>if(!empty($request) && !in_array($current_file[count($current_file) - 1], $file_excludes)) {
</code>```

Okay here is another proposed solution now that I have more info:

<?php
$current_file = explode("/", __FILE__);
include 'connection.php';

      // some code which perform search here

?>

       search form here

```

And leave the modified IF statement where it is. So you just initialize the $current_file within the search.php file. Does this make sense?

Body:
Newbie question here but is it possible to unset session which was set. What I mean is I have file connection.php which make connection to database and it is included on each page/file.

There is one page search.php which I want to be accessible without user to be forced to log in. So what I have in the file is

<?php
include 'connection.php';

      // some code which perform search here

?>

       search form here

When I open the page is getting me to sign in page because I'm not logged. What I've tried is to put session destroy right after include of connection

<?php
include 'connection.php';
session_destroy();
      // some code which perform search here

?>

This doesn't help and still redirecting me to sign in page. Is there any chance I can work around this?

Update: I this is where I check and save the session

<?php
$request = $_REQUEST;
if(!empty($request)) {
    $_SESSION['login'] = false;
    if (!empty($_REQUEST['email']) && !empty($_REQUEST['password']) ) {

        $password = md5($_REQUEST['password']);

        $sql = "select users query";

        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if ($row['type'] == 'admin' || $row['type'] == $_REQUEST['type'] ) {
                $_SESSION['user']=[
                    'id' => $row['id'],
                    'fname' => $row['fname'],
                    'email' => $row['email'],
                ];
                $_SESSION['login'] = true;
                if($_SESSION['user']['type'] == 'admin'){
                    header('Location: Approval.php');die;
                }
            }else {
                    header('Location: signup.php');die;
            }
        } else { $error = "Wrong Email and/or Password or Account not acitvated. Please try again."; }
    }
}

Body:
In your connection.php file you can have an array with file names you want to exclude like (add it before or after the line $request = $_REQUEST;):

$file_excludes = array("search.php", "anotherfile.php");

Then get the current file being run and split the path (add it before the line if(!empty($request)) {):

$current_file = explode("/", __FILE__);

Then modify the line:

if(!empty($request)) {

To:

if(!empty($request) && !in_array($current_file[count($current_file) - 1], $file_excludes)) {

Okay here is another proposed solution now that I have more info:

<?php
$current_file = explode("/", __FILE__);
include 'connection.php';

      // some code which perform search here

?>
<html>
<head></head>
<body>
       search form here
</body>
</html>

And leave the modified IF statement where it is. So you just initialize the $current_file within the search.php file. Does this make sense?


问:
Refresh table onclick with jquery in mvc
I have a table in my View. I've added a datepicker in my View, which posts the two selected dates into my Controller (dateFrom and dateTo). I then compare the dates of my objects and pass them back to the View. The data passing is all good but I'm having trouble refreshing the table and showing the new data.

I've tried a few different things, but this is basically it looks like. This function is ran onclick of the datepicker button:

```<code>function Search() {
    $(".myTable").empty();
    var dateFrom = $("#dateFrom").val();
    var dateTo = $("#dateTo").val();

    $.ajax({
        url: "/myDirectory/myController",
        method: "POST",
        data: {
            dateFrom: dateFrom,
            dateTo: dateTo
        },
        success: function (asd123) {
            $(".myTable").show();
        }
    })
}
</code>```

This function, though, just empties the data and doesn't show the new one. What should I be looking at here?

答:
You need to create separate Partial View for table content so that you can refresh that content through Ajax call follow below process for that :

Your main view Ajax Call should be :

```<code>function Search() {
$(".myTable").empty();
    var dateFrom = $("#dateFrom").val();
    var dateTo = $("#dateTo").val();
$.ajax({
   url: "/myController/PartialViewAction",
   type: "POST",
   dataType: "html",
   data: {
            dateFrom: dateFrom,
            dateTo: dateTo
        },
   success: function (data) {
       $(".myTable").html(data);
       $(".myTable").show();

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

Main View : Remove Table Content Div and add on partial view and add below instead of that

//Here is the code for call Partial view on main view

```<code><div id="TableContent" Class="myTable">
    @Html.Partial("_PartialViewForTable", Model)
</div>
</code>```

Create Partial View With name of "_PartialViewForTable" and add Table Content of mail view
//Do not call Layout Page on partial view

```<code>@model Application.Model.YourModel
<div id="TableData">
//Your Table Data
</div>
</code>```

And Your Controller Action should be :

//Action is returning partial view instead of main view

```<code>[HttpPost]
public ActionResult PartialViewAction(DateTime? dateFrom = null, DateTime? dateTo= null)
{
 YourModel objYourModel = new YourModel();
 //Bind data in objYourModel and retun to your view
 return PartialView("_PartialViewForTable", objYourModel);
}
</code>```

Body:
I have a table in my View. I've added a datepicker in my View, which posts the two selected dates into my Controller (dateFrom and dateTo). I then compare the dates of my objects and pass them back to the View. The data passing is all good but I'm having trouble refreshing the table and showing the new data.

I've tried a few different things, but this is basically it looks like. This function is ran onclick of the datepicker button:

function Search() {
    $(".myTable").empty();
    var dateFrom = $("#dateFrom").val();
    var dateTo = $("#dateTo").val();

    $.ajax({
        url: "/myDirectory/myController",
        method: "POST",
        data: {
            dateFrom: dateFrom,
            dateTo: dateTo
        },
        success: function (asd123) {
            $(".myTable").show();
        }
    })
}

This function, though, just empties the data and doesn't show the new one. What should I be looking at here?

Body:
You need to create separate Partial View for table content so that you can refresh that content through Ajax call follow below process for that :

Your main view Ajax Call should be :

function Search() {
$(".myTable").empty();
    var dateFrom = $("#dateFrom").val();
    var dateTo = $("#dateTo").val();
$.ajax({
   url: "/myController/PartialViewAction",
   type: "POST",
   dataType: "html",
   data: {
            dateFrom: dateFrom,
            dateTo: dateTo
        },
   success: function (data) {
       $(".myTable").html(data);
       $(".myTable").show();

   }
});
}

Main View : Remove Table Content Div and add on partial view and add below instead of that

//Here is the code for call Partial view on main view

<div id="TableContent" Class="myTable">
    @Html.Partial("_PartialViewForTable", Model)
</div>

Create Partial View With name of "_PartialViewForTable" and add Table Content of mail view
//Do not call Layout Page on partial view

@model Application.Model.YourModel
<div id="TableData">
//Your Table Data
</div>

And Your Controller Action should be :

//Action is returning partial view instead of main view

[HttpPost]
public ActionResult PartialViewAction(DateTime? dateFrom = null, DateTime? dateTo= null)
{
 YourModel objYourModel = new YourModel();
 //Bind data in objYourModel and retun to your view
 return PartialView("_PartialViewForTable", objYourModel);
}

ContentLicense: CC BY-SA 4.0


问:
Hooking in .Net
I want to hook some function in .Net is there a way to do it?
I don’t mean windows hooking, I want to hook CLR function like when DataAdapter.Fill is called
Thanks,</p>

答:
The profiling API has what you want.

http://msdn.microsoft.com/en-us/magazine/cc301725.aspx

But I've never used it, so good luck!

ContentLicense: CC BY-SA 2.5

Title: Hooking in .Net


问:
How to retrieve float_val from a PredictResponse object?
I am running a prediction on a tensorflow-serving model, and I get back this PredictResponse object as output:

Result:

```<code>outputs {
  key: "outputs"
  value {
    dtype: DT_FLOAT
    tensor_shape {
      dim {
        size: 1
      }
      dim {
        size: 20
      }
    }
    float_val: 0.000343723397236
    float_val: 0.999655127525
    float_val: 3.96821117632e-11
    float_val: 1.20521548297e-09
    float_val: 2.09611101809e-08
    float_val: 1.46216549979e-09
    float_val: 3.87274603497e-08
    float_val: 1.83520256769e-08
    float_val: 1.47733780764e-08
    float_val: 8.00914179422e-08
    float_val: 2.29388191997e-07
    float_val: 6.27798826258e-08
    float_val: 1.08802950649e-07
    float_val: 4.39628813353e-08
    float_val: 7.87182985462e-10
    float_val: 1.31638898893e-07
    float_val: 1.42612295306e-08
    float_val: 3.0768305237e-07
    float_val: 1.12661648899e-08
    float_val: 1.68554503688e-08
  }
}
</code>```

I would like to get the out the float vals as a list. Or, alternatively, return the value/index of the argmax float_val!

This is generated by:

stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
  result = stub.Predict(request, 200.0)

Thanks for your help in advance.

答:
The answer is:</p>

```<code>floats = result.outputs['outputs'].float_val
</code>```

Body:
I am running a prediction on a tensorflow-serving model, and I get back this PredictResponse object as output:

Result:

outputs {
  key: "outputs"
  value {
    dtype: DT_FLOAT
    tensor_shape {
      dim {
        size: 1
      }
      dim {
        size: 20
      }
    }
    float_val: 0.000343723397236
    float_val: 0.999655127525
    float_val: 3.96821117632e-11
    float_val: 1.20521548297e-09
    float_val: 2.09611101809e-08
    float_val: 1.46216549979e-09
    float_val: 3.87274603497e-08
    float_val: 1.83520256769e-08
    float_val: 1.47733780764e-08
    float_val: 8.00914179422e-08
    float_val: 2.29388191997e-07
    float_val: 6.27798826258e-08
    float_val: 1.08802950649e-07
    float_val: 4.39628813353e-08
    float_val: 7.87182985462e-10
    float_val: 1.31638898893e-07
    float_val: 1.42612295306e-08
    float_val: 3.0768305237e-07
    float_val: 1.12661648899e-08
    float_val: 1.68554503688e-08
  }
}

I would like to get the out the float vals as a list. Or, alternatively, return the value/index of the argmax float_val!

This is generated by:

stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
  result = stub.Predict(request, 200.0)

Thanks for your help in advance.

Body:
The answer is:

floats = result.outputs['outputs'].float_val


问:
Deadlocks and nolock issues in SQL Server
We have a stored procedure which inserts and updates bulk data; we are using nolock hints on the selects. Now we are facing 601 error when the load is really high. Can we use row versioning?

If yes which one can be used as we have simultaneously running multiple transactions. And one more thing we had to afford is delays due to always on, we multiple database servers in sync to handle database fail over.

We are using it as it can prevent reads being deadlocked by other operations. Our application high transaction rates, and one more thing in our concern is we are using always on with availability group of 5 servers so we stand a delay in commit as it only commit after committing in all servers. So should we go with row versioning? if so how to choose which one? or can we go for snapshot isolation? what costs to be afford apart from tempdb memory usage, is go for it?

with (UPDLOCK, ROWLOCK) on worked for small batches but when batch is as high as 2000 it got deadlocked.

this  is the piece of code that executes the SP; the same code is being hosted on 10 servers and so this is expected to run simultaneously. GetRSExecutionLogLatestID is where SP is being called internally.

```<code>ExecutionLogData execLog = this.fileShareDeliveryWrapper.GetRSExecutionLogLatestID(rptPath, notification.Owner, sharePointSubscriptiondata.RASSubscriptionID, this.configRSConnectionString);
                        if (execLog != null)
                        {
                            sharePointSubscriptiondata.RSExecutionLogId = execLog.RSExecutionLogId;
                            sharePointSubscriptiondata.RSSubscriptionId = execLog.RSSubscriptionId;
                        }
</code>```

this is the SP:

```<code>    ALTER Procedure [dbo].[RAS_USP_GetLatestExecutionLogId]
@ReportURLPath NVARCHAR(MAX),
@UserID NVARCHAR(200),
@RASSubscriptionID NVARCHAR(100)
AS
BEGIN

SET NOCOUNT ON;
print @userId
DECLARE @SubscriptionId UNIQUEIDENTIFIER,@OwnerUserId UNIQUEIDENTIFIER, @LogEntryId BIGINT

DECLARE @Subscriptions AS TABLE(SubscriptionID uniqueIdentifier NOT NULL,
                                NotificationID uniqueidentifier NULL,
                                ReportID uniqueIdentifier NULL,
                                ExtensionSettings XML NOT NULL
                                )
INSERT INTO @Subscriptions
SELECT n.SubscriptionID,n.NotificationID,n.ReportID,n.ExtensionSettings
FROM dbo.Notifications AS n WITH (UPDLOCK, ROWLOCK) INNER JOIN
        Subscriptions AS s WITH (UPDLOCK, ROWLOCK) ON n.SubscriptionID = s.SubscriptionID INNER JOIN
        Catalog AS c WITH (UPDLOCK, ROWLOCK) ON c.ItemID = n.ReportID INNER JOIN
        Users AS um WITH (UPDLOCK, ROWLOCK) ON um.UserID = s.OwnerID
WHERE c.[Path] = @ReportURLPath --AND um.UserName=@UserID

SELECT @SubscriptionID = SubScriptionID FROM

(SELECT SubscriptionID,
        NotificationID,
        ReportID,
        pValues.pValue.value('Name[1]', 'VARCHAR(50)') AS ParamName,
        pValues.pValue.value('Value[1]', 'VARCHAR(150)') AS ParamValue
    FROM
       @Subscriptions CROSS APPLY
       ExtensionSettings.nodes('/ParameterValues/ParameterValue') pValues(pValue)
)  AS Result

where ParamName like '%RASSubscriptionID%' AND ParamValue = CAST(@RASSubscriptionID AS VARCHAR(100))

SELECT @OwnerUserId = UserID FROM Users WHERE UserName = @UserID

SELECT @LogEntryId = LogEntryId FROM (
SELECT top 1 LogEntryId
FROM ExecutionLogStorage a WITH (UPDLOCK, ROWLOCK)
INNER JOIN [CATALOG] b WITH (UPDLOCK, ROWLOCK) ON a.reportid = b.itemid
INNER JOIN [Notifications] n WITH (UPDLOCK, ROWLOCK) ON n.ReportID = a.ReportID AND n.SubscriptionID = @SubscriptionId
INNER JOIN dbo.Subscriptions s WITH (UPDLOCK, ROWLOCK) ON s.SubscriptionID = n.SubscriptionID
WHERE [Path] = @ReportURLPath AND n.SubscriptionOwnerID=@OwnerUserId
ORDER BY TimeEnd desc) ss

SELECT @LogEntryId AS LogEntryId, @SubscriptionId AS SubscriptionID

END
</code>```

答:
SNAPSHOT ISOLATION is pretty much the way to go to prevent blocking while updating, when you have control over the queries and you need consistency between statements.  READ_COMMITTED_SNAPSHOT is another possibility but affects all queries, plus it doesn't guarantee "consistency" within a given transaction (just as READ COMMITTED vs SERIALIZABLE can give different results).  NOLOCK is pretty much never the way to go, 99% of the time.

You can think of SNAPSHOT ISOLATION as a viable "read-only" serializable*.  There are of course several costs -- note that you will pay many of them even if no snapshot transaction is active, because of course if one becomes active, the tracking data will have needed to be in place.

Increased activity on tempdb, as you mentioned

Rows will take up more space (14 bytes per row)

Somewhat more activity on most operations, so depending on the workload there may be a performance hit

Other considerations:

It's best not to update data from a snapshot transaction as you may get unexpected results

Certain operations still cannot be done (rebuilding indexes, for example -- reorganizing is okay, but at least in SQL 2012, if a query is reading from an index in snapshot isolation while it is being rebuilt somewhere else, the read query will fail)

For whatever asinine reason, if you use connection pooling, the isolation level doesn't get reset when a connection is reused, which can lead to unexpected results (this applies to all transaction levels though, not just SNAPSHOT)

This article has a good overview of the situation:
https://technet.microsoft.com/en-us/library/ms188277(v=sql.105).aspx

But ultimately, your only real choices if you need to avoid blocking are row versioning and NOLOCK, which isn't a choice.  Otherwise you may need to design things differently.  Other possibilities would be to use things like UPDLOCK to avoid deadlocks, to insert/update small batches of data at a time so that the "blocking periods" are short/unnoticeable, etc.

(*) I say this because:

If you open a SNAPSHOT ISOLATION transaction and only read from it, you will get the same read results as you would if you were to use SERIALIZABLE, except that you won't block writers and you won't cause deadlocks

I say "viable" because most of the time, introducing SERIALIZABLE causes too much blocking and too many deadlocks.

I say "read-only" because although you can write within a snapshot transaction, it is a much more complicated endeavour.  If you only read from within a snapshot transaction, it's unlikely you'll run into data correctness issues -- indeed, since it's similar to SERIALIZABLE, you may even improve the consistency of your results.  The only issues you're likely to run into are performance related.  So overall, the stakes are fairly low in terms of it being a breaking change to introduce this to such a query.  If you start writing, though:

If you try to save changes, and the same data was changed in another transaction, the update will fail with error 3960:

Snapshot isolation transaction aborted due to update conflict. You
  cannot use snapshot isolation to access table 'XYZ' directly
  or indirectly in database 'ABC' to update, delete, or insert
  the row that has been modified or deleted by another transaction.
  Retry the transaction or change the isolation level for the
  update/delete statement.

which is a new situation you'll have to handle, which is more difficult than just blocking (though I suppose it's of similar difficulty to dealing with deadlocks).

Even if you update different data, you can still get unusual results.  An example from https://blogs.msdn.microsoft.com/craigfr/2007/05/16/serializable-vs-snapshot-isolation-level/:

Imagine that we have a bag containing a mixture of white and black marbles.  Suppose that we want to run two transactions.  One
  transaction turns each of the white marbles into black marbles.  The
  second transaction turns each of the black marbles into white marbles.
  If we run these transactions under serializable isolation, we must run
  them one at a time.  The first transaction will leave a bag with
  marbles of only one color.  After that, the second transaction will
  change all of these marbles to the other color.  There are only two
  possible outcomes:  a bag with only white marbles or a bag with only
  black marbles.

If we run these transactions under snapshot isolation, there is a
  third outcome that is not possible under serializable isolation.  Each
  transaction can simultaneously take a snapshot of the bag of marbles
  as it exists before we make any changes.  Now one transaction finds
  the white marbles and turns them into black marbles.  At the same
  time, the other transactions finds the black marbles – but only those
  marbles that where black when we took the snapshot – not those marbles
  that the first transaction changed to black – and turns them into
  white marbles.  In the end, we still have a mixed bag of marbles with
  some white and some black.  In fact, we have precisely switched each
  marble.

In other words, if you stick to only reading from SNAPSHOT transactions, it's much less complicated, so in that sense, I say you can think of it as a viable "read-only" serializable -- if you just stop there, it is a useful tool pretty much anyone can use to get consistent, non-blocking results, without using NOLOCK, as long as they can afford the performance hit. Of course, it is more than that, but to go further, you need to deal with a lot more complexity.

Body:
We have a stored procedure which inserts and updates bulk data; we are using nolock hints on the selects. Now we are facing 601 error when the load is really high. Can we use row versioning?

If yes which one can be used as we have simultaneously running multiple transactions. And one more thing we had to afford is delays due to always on, we multiple database servers in sync to handle database fail over.

We are using it as it can prevent reads being deadlocked by other operations. Our application high transaction rates, and one more thing in our concern is we are using always on with availability group of 5 servers so we stand a delay in commit as it only commit after committing in all servers. So should we go with row versioning? if so how to choose which one? or can we go for snapshot isolation? what costs to be afford apart from tempdb memory usage, is go for it?

with (UPDLOCK, ROWLOCK) on worked for small batches but when batch is as high as 2000 it got deadlocked.

this  is the piece of code that executes the SP; the same code is being hosted on 10 servers and so this is expected to run simultaneously. GetRSExecutionLogLatestID is where SP is being called internally.

ExecutionLogData execLog = this.fileShareDeliveryWrapper.GetRSExecutionLogLatestID(rptPath, notification.Owner, sharePointSubscriptiondata.RASSubscriptionID, this.configRSConnectionString);
                        if (execLog != null)
                        {
                            sharePointSubscriptiondata.RSExecutionLogId = execLog.RSExecutionLogId;
                            sharePointSubscriptiondata.RSSubscriptionId = execLog.RSSubscriptionId;
                        }

this is the SP:

    ALTER Procedure [dbo].[RAS_USP_GetLatestExecutionLogId]
@ReportURLPath NVARCHAR(MAX),
@UserID NVARCHAR(200),
@RASSubscriptionID NVARCHAR(100)
AS
BEGIN

SET NOCOUNT ON;
print @userId
DECLARE @SubscriptionId UNIQUEIDENTIFIER,@OwnerUserId UNIQUEIDENTIFIER, @LogEntryId BIGINT

DECLARE @Subscriptions AS TABLE(SubscriptionID uniqueIdentifier NOT NULL,
                                NotificationID uniqueidentifier NULL,
                                ReportID uniqueIdentifier NULL,
                                ExtensionSettings XML NOT NULL
                                )
INSERT INTO @Subscriptions
SELECT n.SubscriptionID,n.NotificationID,n.ReportID,n.ExtensionSettings
FROM dbo.Notifications AS n WITH (UPDLOCK, ROWLOCK) INNER JOIN
        Subscriptions AS s WITH (UPDLOCK, ROWLOCK) ON n.SubscriptionID = s.SubscriptionID INNER JOIN
        Catalog AS c WITH (UPDLOCK, ROWLOCK) ON c.ItemID = n.ReportID INNER JOIN
        Users AS um WITH (UPDLOCK, ROWLOCK) ON um.UserID = s.OwnerID
WHERE c.[Path] = @ReportURLPath --AND um.UserName=@UserID

SELECT @SubscriptionID = SubScriptionID FROM

(SELECT SubscriptionID,
        NotificationID,
        ReportID,
        pValues.pValue.value('Name[1]', 'VARCHAR(50)') AS ParamName,
        pValues.pValue.value('Value[1]', 'VARCHAR(150)') AS ParamValue
    FROM
       @Subscriptions CROSS APPLY
       ExtensionSettings.nodes('/ParameterValues/ParameterValue') pValues(pValue)
)  AS Result

where ParamName like '%RASSubscriptionID%' AND ParamValue = CAST(@RASSubscriptionID AS VARCHAR(100))

SELECT @OwnerUserId = UserID FROM Users WHERE UserName = @UserID

SELECT @LogEntryId = LogEntryId FROM (
SELECT top 1 LogEntryId
FROM ExecutionLogStorage a WITH (UPDLOCK, ROWLOCK)
INNER JOIN [CATALOG] b WITH (UPDLOCK, ROWLOCK) ON a.reportid = b.itemid
INNER JOIN [Notifications] n WITH (UPDLOCK, ROWLOCK) ON n.ReportID = a.ReportID AND n.SubscriptionID = @SubscriptionId
INNER JOIN dbo.Subscriptions s WITH (UPDLOCK, ROWLOCK) ON s.SubscriptionID = n.SubscriptionID
WHERE [Path] = @ReportURLPath AND n.SubscriptionOwnerID=@OwnerUserId
ORDER BY TimeEnd desc) ss

SELECT @LogEntryId AS LogEntryId, @SubscriptionId AS SubscriptionID

END


问:
Show files with no unit tests in python nosetests coverage report
Consider following python project structure.

```<code>Car.py
test_car.py
Van.py
__main__.py
</code>```

When I run code coverage with nose It only consider files which unit tests are written (i.e. Car.py has a unit tests test_car.py). I used following command to generate the report.

```<code>nosetests --with-coverage --cover-erase --cover-html
</code>```

It generate following coverage report.

```<code>.
Name     Stmts   Miss  Cover
----------------------------
Car.py      11      3    73%
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK
</code>```

But my project have more files (Van.py). But coverage report doesn't contain those files and final coverage percentage doesn't include those. If that report consider all the files, that final percentage will be less than 73%.

How do I generate coverage report by considering all the files. Files without unit test should show 0% code coverage in the report. My project is far more larger than this sample. How do I achive this requirement?

答:
It's pretty straight-forward. Damn I didn't RTM. There is a flag --cover-inclusive in order to do that. According to the documentation, "Include all python files under working directory in coverage report. Useful for discovering holes in test coverage if not all files are imported by the test suite. [NOSE_COVER_INCLUSIVE]"

Here how to use it.

```<code>nosetests --with-coverage --cover-erase --cover-inclusive --cover-html
</code>```

Body:
Consider following python project structure.

Car.py
test_car.py
Van.py
__main__.py

When I run code coverage with nose It only consider files which unit tests are written (i.e. Car.py has a unit tests test_car.py). I used following command to generate the report.

nosetests --with-coverage --cover-erase --cover-html

It generate following coverage report.

.
Name     Stmts   Miss  Cover
----------------------------
Car.py      11      3    73%
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK

But my project have more files (Van.py). But coverage report doesn't contain those files and final coverage percentage doesn't include those. If that report consider all the files, that final percentage will be less than 73%.

How do I generate coverage report by considering all the files. Files without unit test should show 0% code coverage in the report. My project is far more larger than this sample. How do I achive this requirement?

Body:
It's pretty straight-forward. Damn I didn't RTM. There is a flag --cover-inclusive in order to do that. According to the documentation, "Include all python files under working directory in coverage report. Useful for discovering holes in test coverage if not all files are imported by the test suite. [NOSE_COVER_INCLUSIVE]"

Here how to use it.

nosetests --with-coverage --cover-erase --cover-inclusive --cover-html


问:
Ways of managing the data in a database
I'm new to databases and web servers and that kind of thing. So I am looking for information so I can begin to figure out a starting point and options open to me.

I need to have a database that can be accessed by an iPhone app. So logically it will be hosted on a webserver somewhere.

To get/insert the data from/into the database the app would make a HTTP connection to a php file on the same server as the DB which would then insert/return the relevant data. To stop random hackers messing with the DB the app would have some validation code inside it to send to the php file to check that its not a hacker trying to mess with the database. This all making sense or will that not be secure enough.

Now the most confusing part to get my head around is :
I need check every minute has any data in the database become to old and remove it if so. So something needs to be running on the server constantly checking/manageing the database. What would this be? What is commonly used to do this kinda of thing? Is there somekey word for it that i can start searching and reading about to see what options there are?

Thanks for your advise,
-Code

答:
Sounds to me like you need a cron job. Cron is the standard scheduling task application for Unix type systems.

You would have some sort of script that connects to the database and performs a cleanup query, and you would schedule that script via cron.

http://en.wikipedia.org/wiki/Cron

Title: Ways of managing the data in a database


问:
Mysql import of laravel voyager database error - Specified key was too long; max key length is 767 bytes
Cant seem to upload a laravel database to a live server because of the specified key is too long. SQL ERROR example shows that the key constraint is too long, however it is not just on one table it is on many. Is there a way to update this or change my DB to be able to upload it? I followed the guide in the app service provider but i am not sure if I have to drop the DB, then migrate again with the key  constraint on the boot() method on the app service provider. Please help.</p>

答:
In fact the adding defaultStringLength to the boot method does work however because I was using vendor scripts, I could not rollback my migrations as the migrations were created by the BREAD Controller in Voyager. In order to get the MYSQL import to work, without losing data or rolling and changing the migrations I had to manually, with Sequel Pro or whatever you are using, and change manually each varchar('255') to varchar('191').

This saved me from deleting and having to rollback.

Adding:

```<code>use Illuminate\Support\Facades\Schema; // add this

Schema::defaultStringLength(191);
</code>```

to the AppServiceProvider.php will work from now on because any other migration I create with the BREAD controller will have the default 191 added to the string length.

For reference: https://laravel-news.com/laravel-5-4-key-too-long-error

Body:
In fact the adding defaultStringLength to the boot method does work however because I was using vendor scripts, I could not rollback my migrations as the migrations were created by the BREAD Controller in Voyager. In order to get the MYSQL import to work, without losing data or rolling and changing the migrations I had to manually, with Sequel Pro or whatever you are using, and change manually each varchar('255') to varchar('191').

This saved me from deleting and having to rollback.

Adding:

use Illuminate\Support\Facades\Schema; // add this

Schema::defaultStringLength(191);

to the AppServiceProvider.php will work from now on because any other migration I create with the BREAD controller will have the default 191 added to the string length.

For reference: https://laravel-news.com/laravel-5-4-key-too-long-error


问:
ConfigParser - Create file if it doesn't exist
So I am working on creating a program in Python that reads a .ini file to set up some boot variables for the main program.  My only thing is, I want the program on initialization, to check if the .ini file exists, and if it doesn't, create it with a set of default values.  Kind of a preemptive bug fix on if someone accidentally deletes the file.

I can't seem to find any examples anywhere of how to do this, and I'm not super experienced with Python (only been programming with it for about a week) so I'd appreciate any assistance :)

Edit: Upon further thought, I want to pursue this a bit further.

Let's assume the file does exist.  How do I check it to make sure it has the appropriate sections?  If it doesn't have the appropriate sections, how would I go about deleting the file or removing the contents and rewriting the contents of the file?

I'm trying to idiot proof this :P

答:
You can use ConfigParser and the OS library, here's a quick example:

```<code>#!usr/bin/python
import configparser, os

config = configparser.ConfigParser()

# Just a small function to write the file
def write_file():
    config.write(open('config.ini', 'w'))

if not os.path.exists('config.ini'):
    config['testing'] = {'test': '45', 'test2': 'yes'}

    write_file()
else:
    # Read File
    config.read('config.ini')

    # Get the list of sections
    print config.sections()

    # Print value at test2
    print config.get('testing', 'test2')

    # Check if file has section
    try:
        config.get('testing', 'test3')

    # If it doesn't i.e. An exception was raised
    except configparser.NoOptionError:
        print "NO OPTION CALLED TEST 3"

        # Delete this section, you can also use config.remove_option
        # config.remove_section('testing')
        config.remove_option('testing', 'test2')

        write_file()
</code>```

Output:

```<code>[DEFAULT]
test = 45
test2 = yes
</code>```

Linked above are the docs that are extremely useful to learn more about writing configuration files and other in-built modules.

Note: I'm kind of new to python, so if anyone knows a better approach let me know I'll edit my answer!

Body:
You can use ConfigParser and the OS library, here's a quick example:

#!usr/bin/python
import configparser, os

config = configparser.ConfigParser()

# Just a small function to write the file
def write_file():
    config.write(open('config.ini', 'w'))

if not os.path.exists('config.ini'):
    config['testing'] = {'test': '45', 'test2': 'yes'}

    write_file()
else:
    # Read File
    config.read('config.ini')

    # Get the list of sections
    print config.sections()

    # Print value at test2
    print config.get('testing', 'test2')

    # Check if file has section
    try:
        config.get('testing', 'test3')

    # If it doesn't i.e. An exception was raised
    except configparser.NoOptionError:
        print "NO OPTION CALLED TEST 3"

        # Delete this section, you can also use config.remove_option
        # config.remove_section('testing')
        config.remove_option('testing', 'test2')

        write_file()

Output:

[DEFAULT]
test = 45
test2 = yes

Linked above are the docs that are extremely useful to learn more about writing configuration files and other in-built modules.

Note: I'm kind of new to python, so if anyone knows a better approach let me know I'll edit my answer!


问:
Wrong position of rightBarButtonItem in iOS 10
I want to put the view of a UINavigationController into another view controller's view. The problem is that the right bar button is misplaced on iOS 10. On iOS 8 and 9 it looks good.

iOS 8 and 9:

iOS 10:

Here's the code how i add the navigation controller:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}
</code>```

In MyViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(
        barButtonSystemItem: .done,
        target: self,
        action: #selector(doneButtonPressed)
    )
}
</code>```

Also there are no clipped views (except the button itself). See snapshot of IB Debug View Hierachy:

Any ideas?

答:
This is happening because you're adding the subviews in the ViewDidLoad and not viewDidAppear, try changing this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}
</code>```

to this:

```<code>    let viewController = MyViewController()

    override func viewDidAppear() {
        super.viewDidAppear()
     if(self.childViewControllers.contains(viewController) != true){
        navController = UINavigationController(rootViewController: viewController)
        navController.willMove(toParentViewController: self)
        addChildViewController(navController)
        navController.view.frame = view.bounds
        view.addSubview(navController.view)
        navController.didMove(toParentViewController: self)

      }
 }
</code>```

Body:
I want to put the view of a UINavigationController into another view controller's view. The problem is that the right bar button is misplaced on iOS 10. On iOS 8 and 9 it looks good.

iOS 8 and 9:

iOS 10:

Here's the code how i add the navigation controller:

override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}

In MyViewController

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(
        barButtonSystemItem: .done,
        target: self,
        action: #selector(doneButtonPressed)
    )
}

Also there are no clipped views (except the button itself). See snapshot of IB Debug View Hierachy:

Any ideas?

Body:
This is happening because you're adding the subviews in the ViewDidLoad and not viewDidAppear, try changing this:

override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}

to this:

    let viewController = MyViewController()

    override func viewDidAppear() {
        super.viewDidAppear()
     if(self.childViewControllers.contains(viewController) != true){
        navController = UINavigationController(rootViewController: viewController)
        navController.willMove(toParentViewController: self)
        addChildViewController(navController)
        navController.view.frame = view.bounds
        view.addSubview(navController.view)
        navController.didMove(toParentViewController: self)

      }
 }


问:
Google Sheets - Allow Users to run scripts on a protected range
I'm new to Apps Script and have been slowing teaching myself. I have searched Stack Over Flow and found similar questions and tried to work through the issue using the information found but thus far with no success. Hopefully someone here can give a newbie some guidance.

I have a spreadsheet that I am sharing with other users. There are a few ranges with formulas in them that I am trying to protect. I have written a script that can change the forumlas within the protected ranges. It runs perfectly under my account but the shared users are unable to run the script because they "don't have permission".

I have tried to write a bit of code that tries to grant temporary access to edit the protected ranges. My thought was to have three different functions. The first function removes the protections. The second function performs the changes to the now unprotected ranges. The third function then protects the ranges again. The code below works perfectly under my account. However when logged in as a shared user it causes an alert saying that "You do not have permission to perform.."

Can someone please tell me where I am going wrong and point me in the right direction?

```<code>function myFunction() {
  //add protections back
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Spray Template');
  var range = sheet.getRange('B15:E15');
  var range2 = sheet.getRange('G15:H15');
  var range3 = sheet.getRange('D16:E16');
  var ranges = [range,range2,range3];
  for (var j = 0; j<3; j++){
    ranges[j].protect().removeEditor('email_here@gmail.com');
  }
}

function myFunction2(){
//remove protections
var ss = SpreadsheetApp.getActive();
var ss2= ss.getSheetByName('Spray Template');
var protections = ss2.getProtections(SpreadsheetApp.ProtectionType.RANGE);
 f
 or (var i = 0; i < protections.length; i++) {
   var protection = protections[i];

protection.addEditor('email_here@gmail.com');
SpreadsheetApp.flush();
protection.remove();
 }
}

function test() {
  myFunction2();
  functionThatChangesRange();
  myFunction();
}
</code>```

答: I saw it suggested elsewhere to leave one cell unprotected and setup a script within the document that runs 'onedit'.  Whenever the user changes the value of that cell the script should run.</p>

Body:
I'm new to Apps Script and have been slowing teaching myself. I have searched Stack Over Flow and found similar questions and tried to work through the issue using the information found but thus far with no success. Hopefully someone here can give a newbie some guidance.

I have a spreadsheet that I am sharing with other users. There are a few ranges with formulas in them that I am trying to protect. I have written a script that can change the forumlas within the protected ranges. It runs perfectly under my account but the shared users are unable to run the script because they "don't have permission".

I have tried to write a bit of code that tries to grant temporary access to edit the protected ranges. My thought was to have three different functions. The first function removes the protections. The second function performs the changes to the now unprotected ranges. The third function then protects the ranges again. The code below works perfectly under my account. However when logged in as a shared user it causes an alert saying that "You do not have permission to perform.."

Can someone please tell me where I am going wrong and point me in the right direction?

function myFunction() {
  //add protections back
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Spray Template');
  var range = sheet.getRange('B15:E15');
  var range2 = sheet.getRange('G15:H15');
  var range3 = sheet.getRange('D16:E16');
  var ranges = [range,range2,range3];
  for (var j = 0; j<3; j++){
    ranges[j].protect().removeEditor('email_here@gmail.com');
  }
}

function myFunction2(){
//remove protections
var ss = SpreadsheetApp.getActive();
var ss2= ss.getSheetByName('Spray Template');
var protections = ss2.getProtections(SpreadsheetApp.ProtectionType.RANGE);
 f
 or (var i = 0; i < protections.length; i++) {
   var protection = protections[i];

protection.addEditor('email_here@gmail.com');
SpreadsheetApp.flush();
protection.remove();
 }
}

function test() {
  myFunction2();
  functionThatChangesRange();
  myFunction();
}


问:
Giving graphs a subtitle
I want to give my graph a title in big 18pt font, then a subtitle below it in smaller 10pt font. How can I do this in matplotlib? It appears the title() function only takes one single string with a single fontsize attribute. There has to be a way to do this, but how?

答: What I do is use the title() function for the subtitle and the suptitle()  for the main title (they can take different font size arguments).

Title: Giving graphs a subtitle


问:
delete my app from appstore & Upload it again from a different developer account. If yes, what changes are required to be made
I wanted to delete my app from my current developer account and re-upload it from a different developer account. Yes, i am aware of the fact that i have an option to TRANSFER the ownership of apps from one account to another.
But what if i wish to go this way :
DELETING FROM CURRENT ACCOUNT -> UPLOADING FROM DIFFERENT ACCOUNT

PLEASE REPLY ME FOR BOTH THE SCENARIOS -
A. TRANSFERRING THE APP & UPLOADING A NEW VERSION FROM THE NEW ACCOUNT
B. AS DELETING AND UPLOADING A NEW BUILD OF THE SAME APP FROM THIS NEW ACCOUNT WITH SAME CERTIFICATES

I read on some links available online that i am required to change the bundleId in this case.

答:
1.To transferring apps go-through this link

2.To deleting app there are few restrictions is there.

Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. But you can remove from sale.

But note it once you deleted or removed from sale.Then that deleted
app name,SKU ID & bundle id can't be restored with in the same
organization. So it clearly states you can't use same certificates too ofcourse you need to give new bundle id..etc.

For more go to iTunes Connect Developer Guide


问:
Ocp-Apim-Subscription-Key in header of AJAX Bing web search API requests
We're working to switch from Google CSE to Bing's Web Search API.
The Ocp-Apim-Subscription-Key is visible in a request header (called with an AJAX request).

How do we protect it from use by a third party?

(Note: We don't have any experience with Azure tools.)

答:
You should not be embedding the subscription key into a client-side query.  Your search queries should go from the client-> your server -> Bing server and then back the same way.

This information, although on the Image Search page, applies to all Bing Searches:

All requests must be made from a server. You may not make calls from a client.

Although there are some cases where client-side calls are acceptable, such as internal-use cases, client-side is strongly not recommended.


答:
When you do :

```<code>for i in l
</code>```

i is already your element and not your index. (Also, you don't need parentheses around the string or around i.)

So simply do

```<code>for i in l:
    print ("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);" % i)
</code>```

Title: Python3 print, IndexError: list index out of range

Body:
My code

for i in l:
    print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))

My list

l=[1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]

What I got in Jupyter
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-11-6f78605f79c5> in <module>()
      1 for i in l:
----> 2     print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))

IndexError: list index out of range

Body:
When you do :

for i in l

i is already your element and not your index. (Also, you don't need parentheses around the string or around i.)

So simply do

for i in l:
    print ("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);" % i)


问:
Using jQuery with Angular-CLI Project
I am using "@angular/cli": "1.0.2" and angular version 4.

For some reason I had to use jquery based plugin for select area because I couldn't found equivalent plugin in angular.

This is how my component looks like

```<code>declare var $ : any;
//adding only necessary code
export class SelectComponent implements OnInit {

    constructor(private _ngZone: NgZone) {}

    public rowData: any = [];

    ngOnInit() {
        $('img#example').selectAreas({
            minSize: [10, 10],
            onChanged: this.debugQtyAreas,
            width: 500,
            areas: [{
                x: 10,
                y: 20,
                width: 60,
                height: 100,
            }]
        });
    }
    debugQtyAreas(event, id, areas) {
        this.rowData = areas.map(function(obj) {
            return {
                left: obj.x,
                top: obj.y,
                id: obj.id
            };
        });
    };
}
</code>```

Some how this way my jquery thing is working I am able to select areas on a Image.

But the value I am pushing / assigning to array rowData are not updating in the view

I tried searching on internet and found this solution working for everyone but not for me

```<code>this._ngZone.run(() => {
      //running code inside this
})
</code>```

But I am getting error here as

Cannot read property 'run' of undefined

Same thing happening with rowData, when I tried to push data instead of assigning it from map like following

```<code>for(var i = 0; i < areas.length; i++){
    this.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}
</code>```

It says Cannot read property 'push' of undefined

答:
You need to use bind when you pass a function by reference if you want to persist the this reference.

```<code>onChanged: this.debugQtyAreas.bind(this)
</code>```

When you're writting inline functions with TypeScript don't use the function prefix. If you use the => notation the this reference will persist by default.

```<code>    this.rowData = areas.map((obj) => {
        return {
            left: obj.x,
            top: obj.y,
            id: obj.id
        };
    });
</code>```

Title: Using jQuery with Angular-CLI Project

Body:
I am using "@angular/cli": "1.0.2" and angular version 4.

For some reason I had to use jquery based plugin for select area because I couldn't found equivalent plugin in angular.

This is how my component looks like

declare var $ : any;
//adding only necessary code
export class SelectComponent implements OnInit {

    constructor(private _ngZone: NgZone) {}

    public rowData: any = [];

    ngOnInit() {
        $('img#example').selectAreas({
            minSize: [10, 10],
            onChanged: this.debugQtyAreas,
            width: 500,
            areas: [{
                x: 10,
                y: 20,
                width: 60,
                height: 100,
            }]
        });
    }
    debugQtyAreas(event, id, areas) {
        this.rowData = areas.map(function(obj) {
            return {
                left: obj.x,
                top: obj.y,
                id: obj.id
            };
        });
    };
}

Some how this way my jquery thing is working I am able to select areas on a Image.

But the value I am pushing / assigning to array rowData are not updating in the view

I tried searching on internet and found this solution working for everyone but not for me

this._ngZone.run(() => {
      //running code inside this
})

But I am getting error here as

Cannot read property 'run' of undefined

Same thing happening with rowData, when I tried to push data instead of assigning it from map like following

for(var i = 0; i < areas.length; i++){
    this.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}

It says Cannot read property 'push' of undefined

Body:
You need to use bind when you pass a function by reference if you want to persist the this reference.

onChanged: this.debugQtyAreas.bind(this)

When you're writting inline functions with TypeScript don't use the function prefix. If you use the => notation the this reference will persist by default.

    this.rowData = areas.map((obj) => {
        return {
            left: obj.x,
            top: obj.y,
            id: obj.id
        };
    });


问:
Imported packages do not work with my package in R for some functions?
I built my own package. I imported the most important package that I need them in my package. In these packages there are some functions are not exported by the package (I did not find them in the namespace of the package). I need these functions. When I call them, I get an error that those funciton are not found. So, How I can solve this problem. Also, how does these packages uses this functions inside their packages without using @export!! any help please?

based on the answer:

I understand I do it like this inside my R code: I need the following function:

```<code>args <- preproc(c(as.list(environment()), call = match.call()),
               check_matrix,
                check_fammat,
                check_parmat,
                check_par2mat)
           list2env(args, environment())
</code>```

Then I must do like this:

```<code>VineCopula:::preproc()
</code>```

Then how to call args?

答:
You can call non exported functions with

```<code>packagename:::functionname()
</code>```

It is however not recommended to do that since those functions might not be supported in future versions of packages.

If you want to use a non exported function from your own library inside your own library, you can just use functionname() altough some package developers still prefer packagename:::functionname().

Body:
I built my own package. I imported the most important package that I need them in my package. In these packages there are some functions are not exported by the package (I did not find them in the namespace of the package). I need these functions. When I call them, I get an error that those funciton are not found. So, How I can solve this problem. Also, how does these packages uses this functions inside their packages without using @export!! any help please?

based on the answer:

I understand I do it like this inside my R code: I need the following function:

args <- preproc(c(as.list(environment()), call = match.call()),
               check_matrix,
                check_fammat,
                check_parmat,
                check_par2mat)
           list2env(args, environment())

Then I must do like this:

VineCopula:::preproc()

Then how to call args?

Body:
You can call non exported functions with

packagename:::functionname()

It is however not recommended to do that since those functions might not be supported in future versions of packages.

If you want to use a non exported function from your own library inside your own library, you can just use functionname() altough some package developers still prefer packagename:::functionname().


问:
xslt transformation to copy from xml to xml specific nodes omly
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

```<code><?xml version="1.0"?>
<root>
  <a id="A">
    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>
  </a>
  <a id="B">
    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>
  </a>
</root>
</code>```

desired output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
   <a id="A">
      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>
   </a>
   <a id="B">
      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>
   </a>
</root>
</code>```

Currently I use follwonf xslt:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

But I would like to have shorter list something like that:

```<code> root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()
</code>```

So how to create xslt transformation for that short list?

答:
Well, in XSLT 2.0 you could use a variable with those nodes, compute the ancestors in another variable and then use those variables as follows:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:variable name="copy"
        select="
        root/a/@id
        |root/a/bb/node()
        |root/a/cc/bbb/node()"/>

    <xsl:variable name="subtrees" select="$copy/ancestor-or-self::node()"/>

    <xsl:template match="*[. intersect $subtrees]">
        <xsl:copy>
            <xsl:copy-of select="@*[. intersect $copy]"/>
            <xsl:apply-templates select="node()[. intersect $subtrees]"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

In XSLT 3.0 using a static parameter and a shadow attribute you could even parameterize it further:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:param name="paths" static="yes" as="xs:string"
        select="'root/a/@id | root/a/bb/node() | root/a/cc/bbb/node()'"/>

    <xsl:output indent="yes"/>

    <xsl:variable name="copy" _select="{$paths}"/>

    <xsl:variable name="subtrees" select="$copy/ancestor-or-self::node()"/>

    <xsl:template match="*[. intersect $subtrees]">
        <xsl:copy>
            <xsl:copy-of select="@*[. intersect $copy]"/>
            <xsl:apply-templates select="node()[. intersect $subtrees]"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

<?xml version="1.0"?>
<root>

    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>

    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>

</root>

desired output:

<?xml version="1.0" encoding="UTF-8"?>
<root>

      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>

      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>

</root>

Currently I use follwonf xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

But I would like to have shorter list something like that:

 root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()

So how to create xslt transformation for that short list?

Body:
Well, in XSLT 2.0 you could use a variable with those nodes, compute the ancestors in another variable and then use those variables as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:variable name="copy"
        select="
        root/a/@id
        |root/a/bb/node()
        |root/a/cc/bbb/node()"/>

    <xsl:variable name="subtrees" select="$copy/ancestor-or-self::node()"/>

    <xsl:template match="*[. intersect $subtrees]">
        <xsl:copy>
            <xsl:copy-of select="@*[. intersect $copy]"/>
            <xsl:apply-templates select="node()[. intersect $subtrees]"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

In XSLT 3.0 using a static parameter and a shadow attribute you could even parameterize it further:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:param name="paths" static="yes" as="xs:string"
        select="'root/a/@id | root/a/bb/node() | root/a/cc/bbb/node()'"/>

    <xsl:output indent="yes"/>

    <xsl:variable name="copy" _select="{$paths}"/>

    <xsl:variable name="subtrees" select="$copy/ancestor-or-self::node()"/>

    <xsl:template match="*[. intersect $subtrees]">
        <xsl:copy>
            <xsl:copy-of select="@*[. intersect $copy]"/>
            <xsl:apply-templates select="node()[. intersect $subtrees]"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


问:
Laravel group routing with parameter
I have this group in my route:
}

```<code>Route::group(['prefix' => 'v1/en'], function() {}
</code>```

is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:

```<code>Route::group(['prefix' => 'v1/{lang}'], function() {}
</code>```

答:
Yes you can, $lang will be available if you define your route group like this:

```<code>Route::group(['prefix' => 'v1/{lang}'], function() {
    // ...
});
</code>```

or with new syntax:

```<code>Route::prefix('v1/{lang}')->group(function() {
    // ...
});
</code>```

You can access it anywhere with:

```<code>request()->route()->parameter('lang');
</code>```

You might want to checkout packages like this: Localization for Laravel

They basically do the same, and have nice middleware implementations to set locales etc.

Title: Laravel group routing with parameter

Body:
I have this group in my route:
}

Route::group(['prefix' => 'v1/en'], function() {}

is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:

Route::group(['prefix' => 'v1/{lang}'], function() {}

Body:
Yes you can, $lang will be available if you define your route group like this:

Route::group(['prefix' => 'v1/{lang}'], function() {
    // ...
});

or with new syntax:

Route::prefix('v1/{lang}')->group(function() {
    // ...
});

You can access it anywhere with:

request()->route()->parameter('lang');

You might want to checkout packages like this: Localization for Laravel

They basically do the same, and have nice middleware implementations to set locales etc.


问:
Vuejs extending a parent component from child
I'm trying to put HTML from a child component in a parent component.

ChildComponent.vue

```<code><template>
  <parent>
    <h3>test</h3>
  </parent>
</template>
</code>```

Much like Laravel's @yield and @section

In my scenario, I have the menubars for my app in the parent <template> and want to fill the space beneath it via the child component.

Does anyone know whether and/or how it's possible to do this?

答:
I fixed my issue by putting <router-view></router-view> inside my parent component in the place where I want the child component.

And I put the child component in the children in the router.

```<code>{
  path: '/parent',
  name: 'Parent',
  component: Parent,
  children: [
    {
      path: '/parent/child',
      name: 'Child',
      component: Child
    }
  ]
}
</code>```

Body:
I'm trying to put HTML from a child component in a parent component.

ChildComponent.vue

<template>
  <parent>

test

  </parent>
</template>

Much like Laravel's @yield and @section

In my scenario, I have the menubars for my app in the parent <template> and want to fill the space beneath it via the child component.

Does anyone know whether and/or how it's possible to do this?

Body:
I fixed my issue by putting <router-view></router-view> inside my parent component in the place where I want the child component.

And I put the child component in the children in the router.

{
  path: '/parent',
  name: 'Parent',
  component: Parent,
  children: [
    {
      path: '/parent/child',
      name: 'Child',
      component: Child
    }
  ]
}


问:
Using {} in React
What is the difference between using {} and not when passing in properties?

Ie

```<code>TodoApp = ({props}) => {
    console.log(props)
}
</code>```

and

```<code>TodoAp = (props) => {
    console.log(props)
}
</code>```

答:
This is ES6 syntax and not react.

as written in MDN:

The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.

To the specific example,
In the first example you will unpack the object and take the "props" property out of it, where in the second example you will get the whole object and in order to get the property called "props" you will have to write props.props

Title: Using {} in React

Body:
What is the difference between using {} and not when passing in properties?

Ie

TodoApp = ({props}) => {
    console.log(props)
}

and

TodoAp = (props) => {
    console.log(props)
}


问:
Hooking in .Net
I want to hook some function in .Net is there a way to do it?
I don’t mean windows hooking, I want to hook CLR function like when DataAdapter.Fill is called
Thanks,</p>

答:
This is not possible in general.

For diagnostics purposes, you can use Moles, but I wouldn't recommend it for production use,

In specific cases, you can make an inherited class that overrides a virtual function.

Title: Hooking in .Net


答:
when you do

```<code>for i in l:
    print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))
</code>```

The i represents each element in the list. So the first element would be 1995 and your trying to do a l[1995] which is clearly is out or bounds.

Use

```<code>for i in range(len(l)):
</code>```

or

```<code>for i, element in enumerate(l):
</code>```

or just access the element i directly :

```<code>for i in l:
    print(i)
</code>```

Body:
when you do

for i in l:
    print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))

The i represents each element in the list. So the first element would be 1995 and your trying to do a l[1995] which is clearly is out or bounds.

Use

for i in range(len(l)):

or

for i, element in enumerate(l):

or just access the element i directly :

for i in l:
    print(i)


问:
How to set charset="utf-8" in the javascript file itself
I am trying to set charset="utf-8" inside the javascript file itself, not in the script tag,
I know that I can do this:

```<code><script type="text/javascript" charset="UTF-8" src="xyz.js"></script>
</code>```

But unfortunately, this solution needs me to do the same step with hundreds of websites which are using the same script. so I am trying to set the charset in the javascript file itself.
Is this possible?

thanks

答:
I found another way, so instead of declaring charset="UTF-8" for the script tag like this:

```<code><script type="text/javascript" charset="UTF-8" src="xyz.js"></script>
</code>```

I can declare the charset for the web page itself using meta tag, so I can append <meta charset="UTF-8"> to the DOM dynamically, and end up with something like:

```<code><head>
...
  <meta charset="UTF-8">
...
</head>
</code>```

Body:
I am trying to set charset="utf-8" inside the javascript file itself, not in the script tag,
I know that I can do this:

But unfortunately, this solution needs me to do the same step with hundreds of websites which are using the same script. so I am trying to set the charset in the javascript file itself.
Is this possible?

thanks

Body:
I found another way, so instead of declaring charset="UTF-8" for the script tag like this:

<script type="text/javascript" charset="UTF-8" src="xyz.js"></script>

I can declare the charset for the web page itself using meta tag, so I can append <meta charset="UTF-8"> to the DOM dynamically, and end up with something like:

<head>
...
  <meta charset="UTF-8">
...
</head>


问:
assign Json data to HTML cells
I have a Jquery function which returns Json format string and I would like to assign the Json data to HTML cells. How do I proceed with doing this please? I tried using Json2HTML library but doesn't seem to work for me.

```<code>var jsonData: [{"PlayerName": xxx, "Site": yyy, "Score":zzz},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"}]
</code>```

Default.aspx:

```<code><div style="position: relative; top: 25px; height: 720px">
        <div style="position: relative; height: 720px; width: 710px;">
            <div class="TopScore" style="position: relative; left: 50px">
                <table class="table">
                    <tr>
                        <td class="RankColumn">1</td>
                        <td class="PlayernameColumn"></td>
                        <td class="Site"></td>
                        <td class="Score"></td>
                    </tr>
                </table>
            </div>
            <div class="ScoreBlueBackground" style="position: relative; top: 5px; left: 100px">
                <table class="table">
                    <tr>
                        <td class="rankColumn">2</td>
                        <td class="playername"></td>
                        <td class="siteName"></td>
                        <td class="score"></td>
                    </tr>
                </table>
            </div>
.
.
.
.
.
.
.
            <div class="ScoreBlueBackground" style="position: relative; top: 5px; left: 100px">
                <table class="table">
                    <tr>
                        <td class="rankColumn">20</td>
                        <td class="playername"></td>
                        <td class="siteName"></td>
                        <td class="score"></td>
                    </tr>
                </table>
            </div>
</code>```

答: JSON2HTML doesn't work all the way you wanted you just loop through your json and create a table by using JavaScript for loops and other necessary table creating and append functions</p>

Title: assign Json data to HTML cells

Body:
I have a Jquery function which returns Json format string and I would like to assign the Json data to HTML cells. How do I proceed with doing this please? I tried using Json2HTML library but doesn't seem to work for me.

var jsonData: [{"PlayerName": xxx, "Site": yyy, "Score":zzz},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"}]

Default.aspx:

                        1

                        2

.
.
.
.
.
.
.

                        20