问:
Upgrade MVC 2 to MVC 3 issues with views
I'm attempting to upgrade my existing ASP.net MVC 2 web application to MVC 3 so I can use the goodness that is the Razor Viewengine and other said improvements.

After using the converter to convert my app from mvc2 to mvc3 I'm having issues with my strongly typed views.  As an example here we have a view user control that is strongly typed to the class Profile

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Profile>" %>
</code>```

During compilation I'm getting

```<code>Compiler Error Message: CS1061: 'object' does not contain a definition for 'folio' and no extension method 'folio' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
</code>```

which corresponds to this line in my view

So it's like the views are no longer accepting a type.  This is happening w/ user controls as well as full on views.

I've checked both web.config and views/web.config and both seem to be referencing System.Web.Mvc version 3.0.0.0

Any help would be appreciated!

See below for screen captures of web.configs

答:
I simply replaced the web.config in my 'Views' folder (with one from a newly created mvc3 project) as the migration suggested and it worked for me. I wasn't prepared to move all the declarations to the bottom as my project was just too big.

Hope it helps although this is probably too late for you. Maybe it helps others...

Body:
I'm attempting to upgrade my existing ASP.net MVC 2 web application to MVC 3 so I can use the goodness that is the Razor Viewengine and other said improvements.

After using the converter to convert my app from mvc2 to mvc3 I'm having issues with my strongly typed views.  As an example here we have a view user control that is strongly typed to the class Profile

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Profile>" %>

During compilation I'm getting

Compiler Error Message: CS1061: 'object' does not contain a definition for 'folio' and no extension method 'folio' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

which corresponds to this line in my view

So it's like the views are no longer accepting a type.  This is happening w/ user controls as well as full on views.

I've checked both web.config and views/web.config and both seem to be referencing System.Web.Mvc version 3.0.0.0

Any help would be appreciated!

See below for screen captures of web.configs


来源: stackexchange

问:
Which is More Important in iOS: Memory or CPU?
I have been testing several different extensions for viewing animated GIFs in iOS.  Here are my (non-scientific) results:

```<code>Extension           CPU    Memory
Animated-Gif-iOS    6%     26.3 MB  (caches downloaded data)
FLAnimatedImage     5%     32.3 MB
Gifu                0%     174.8 MB
SwiftGif            0%     174.4 MB
YLGIFImage          6%     32.2 MB
iOSDevCenters+GIF   0%     173.7 MB
</code>```

What is the preference for trading memory usage for CPU usage?  Should this decision change if I plan on showing multiple animated GIFs on the screen at the same time?

答: Higher RAM will let you run more multiple things together. Higher processing will give you faster results. Yes it would change to run multiple GIFs. The problem is GIFs need both. Its mostly your choice for want you want. Hope I helped!</p>

ContentLicense: CC BY-SA 3.0

Body:
I have been testing several different extensions for viewing animated GIFs in iOS.  Here are my (non-scientific) results:

Extension           CPU    Memory
Animated-Gif-iOS    6%     26.3 MB  (caches downloaded data)
FLAnimatedImage     5%     32.3 MB
Gifu                0%     174.8 MB
SwiftGif            0%     174.4 MB
YLGIFImage          6%     32.2 MB
iOSDevCenters+GIF   0%     173.7 MB

What is the preference for trading memory usage for CPU usage?  Should this decision change if I plan on showing multiple animated GIFs on the screen at the same time?


问:
How to clear screen on python 3.6 IDLE?
All I wanted to ask that if i want to clear screen in IDLE what method I can use to clear it without closing it.
For e.g.
I print this statement using:-

```<code>print("Prabal Tiwari")
</code>```

after getting output of this I want to clear the console without closing it.
Just like we use "clear" on ubuntu terminal.

答:
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:

```<code>print "\n" * 100
</code>```

Though you could put this in a function:

```<code>def cls(): print "\n" * 100
</code>```

And then call it when needed as cls()

source: Any way to clear python's IDLE window?

Title: How to clear screen on python 3.6 IDLE?

Body:
All I wanted to ask that if i want to clear screen in IDLE what method I can use to clear it without closing it.
For e.g.
I print this statement using:-

print("Prabal Tiwari")

after getting output of this I want to clear the console without closing it.
Just like we use "clear" on ubuntu terminal.

Body:
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:

print "\n" * 100

Though you could put this in a function:

def cls(): print "\n" * 100

And then call it when needed as cls()

source: Any way to clear python's IDLE window?


问:
How to customize searchBar scope
So I have been searching everywhere, but can't come to an answer on this. I have a UISearchBar searchBar setup that filters my data. I came across scope functionality, but created my own scope buttons. So my question is, how do I link those buttons I made so that they can perform the same thing as UISearchBar scopes?</p>

答:
The scope buttons are more a convenience than anything else. They don't automatically change the scope of the search. That is something you have to do in response to the user changing the scope.

Normally, you don't make the buttons yourself. You set the titles for the buttons in the scopeButtonTitles property of the search bar, e.g.:

```<code>self.searchController.searchBar.scopeButtonTitles = ["Scope 1", "Scope 2"]
</code>```

and then in the UISearchBarDelegate delegate implement

```<code>func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int)
</code>```

to act upon the user's choice.

But if there's a great reason to make your own buttons, you just do it all yourself.

Title: How to customize searchBar scope

Body:
The scope buttons are more a convenience than anything else. They don't automatically change the scope of the search. That is something you have to do in response to the user changing the scope.

Normally, you don't make the buttons yourself. You set the titles for the buttons in the scopeButtonTitles property of the search bar, e.g.:

self.searchController.searchBar.scopeButtonTitles = ["Scope 1", "Scope 2"]

and then in the UISearchBarDelegate delegate implement

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int)

to act upon the user's choice.

But if there's a great reason to make your own buttons, you just do it all yourself.


问:
How do I call a class from another class(not inheritance) in Java?
I can't remember what it's called when another class's method in java for example in a main class you call the scanner class to scan in user input?</p>

答:
Your question is not clear.

but maybe the following example will help:

```<code>class Scanner{
  public void scan(){}
}

//use inheritance
class SubScanner extends Scanner{
  public void scan(){}       //overriding
  public void scan(int i){}  //overloading
}

//use aggreagation
class MainClass{
  private final Scanner scanner;
  MainClass(Scanner scanner){
    this.scanner = scanner;
  }
  public void scan(){
    scanner.scan();         //delegation call
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Your question is not clear.

but maybe the following example will help:

class Scanner{
  public void scan(){}
}

//use inheritance
class SubScanner extends Scanner{
  public void scan(){}       //overriding
  public void scan(int i){}  //overloading
}

//use aggreagation
class MainClass{
  private final Scanner scanner;
  MainClass(Scanner scanner){
    this.scanner = scanner;
  }
  public void scan(){
    scanner.scan();         //delegation call
  }
}


问:
Scrollable content elements with Angular Material dynamic-height tabs
This question has come up several times during the evolution of Angular Material, but I'm not able to make any of the suggestions work for v1.0.5. The entire page (or flex container) scrolls, moving the tabs out of view.

How can I achieve scrollable, full-height content elements?

```<code><div flex>
    <md-tabs md-dynamic-height md-border-bottom>
        <md-tab label="one">
            <md-content class="md-padding">
</code>```

Demo fiddle

Bonus Karma for incorporating custom scrollbars.

答:
Try this:</p>

```<code>md-tabs-wrapper {
    position : fixed;
    width: 100%;
    z-index: 1;
    box-shadow: 0 2px 4px -1px rgba(0,0,0,.2), 0 4px 5px 0 rgba(0,0,0,.14), 0 1px 10px 0 rgba(0,0,0,.12);
}

md-tabs-content-wrapper {
    margin-top: 48px;
}
</code>```

Body:
This question has come up several times during the evolution of Angular Material, but I'm not able to make any of the suggestions work for v1.0.5. The entire page (or flex container) scrolls, moving the tabs out of view.

How can I achieve scrollable, full-height content elements?

    <md-tabs md-dynamic-height md-border-bottom>
        <md-tab label="one">
            <md-content class="md-padding">

Demo fiddle

Bonus Karma for incorporating custom scrollbars.

Body:
Try this:

md-tabs-wrapper {
    position : fixed;
    width: 100%;
    z-index: 1;
    box-shadow: 0 2px 4px -1px rgba(0,0,0,.2), 0 4px 5px 0 rgba(0,0,0,.14), 0 1px 10px 0 rgba(0,0,0,.12);
}

md-tabs-content-wrapper {
    margin-top: 48px;
}


问:
AWS S3 Android SDK: Get path of uploaded file
I'm following the steps here for uploading a file to AWS S3
http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/s3transferutility.html

Is there any way through the SDK to get the path of the file I just uploaded?

答:
You can obtain the URL by yourself, using the bucket and the file name you used in the upload request.

I mean for example if your bucket is AMAZON_S3_BUCKET and your file is named myfile:

```<code>https://s3.amazonaws.com/AMAZON_S3_BUCKET/myfile
</code>```

or

```<code>https://AMAZON_S3_BUCKET.s3.amazonaws.com/myfile
</code>```

Or if you are using some region like Regions.US_WEST_2 then The URL will be different depending on which region your bucket is in

```<code>https://AMAZON_S3_BUCKET.YOUR_BUCKET_REGION.amazonaws.com/myfile
</code>```

Body:
You can obtain the URL by yourself, using the bucket and the file name you used in the upload request.

I mean for example if your bucket is AMAZON_S3_BUCKET and your file is named myfile:

https://s3.amazonaws.com/AMAZON_S3_BUCKET/myfile

or

https://AMAZON_S3_BUCKET.s3.amazonaws.com/myfile

Or if you are using some region like Regions.US_WEST_2 then The URL will be different depending on which region your bucket is in

https://AMAZON_S3_BUCKET.YOUR_BUCKET_REGION.amazonaws.com/myfile


问:
intellij feature (...) not supported at this language level. I can't compile
IntelliJ is showing me this error

I just built my new computer and none of my java stuff is working... My regular Intellij was working when I first tried it, but my android studio would't install because it couldn't find the path to the jdk. Here is the question that I asked about that. Since that wasn't working, I had to reinstall java multiple times, and now my IntelliJ isn't working. Here is a picture of the error (I am getting an error that is telling me the for-each loops aren't supported at this language level).

I have tried to install the JDK on my D: drive and that didn't work. I am currently trying to use java 1.8u71 (have tried u65 and 1.7u47) except none of those have worked.

答: Another issue I had that caused this error in a Gradle project was the sourceCompatibility setting in the build.gradle file.  This must also match the value you are expecting to need.  The default value that I have seen IntelliJ use when creating a new Gradle project is 1.5.  If you are using lambdas, for instance, this will cause the build to fail.


问:
Click to create tag / label random but start from label-default
When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning

As shown on image below it not starting off at label-default

Question each time I click on the button to create label how can I
  make sure it does not double up and starts from label-default

DEMO

CODEPEN DEMO

SCRIPT

```<code>$(document).on('click', '#category_button', function(e){

    e.preventDefault();

    //if ($("#label-" + category_name).length  == 0) {

        var rand = Math.floor((Math.random() * 5) + 1);

        switch(rand){
          case 1:
            element = 'label-default';
            break;
          case 2:
            element = 'label-primary';
            break;
          case 3:
            element = 'label-success';
            break;
          case 4:
            element = 'label-info';
            break;
          case 5:
            element = 'label-warning';
            break;
        }

        html = '';
        html += '<li id="">';
        html += '<span class="label ' + element + '">';
        html += 'Hello';
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);
    //}
});
</code>```

答:
You can use an array, Array.prototype.slice(), Array.prototype.splice() to create a copy of original array. If copied array has .length equal to 0 remove first element from array, set the element as element value, else get, set random element from copied array as element value, repeat procedure.

var arr = ["default", "primary", "success", "info", "warning"];
var label = "label-";
var copy = [];

$(document).on("click", "#category_button", function(e) {

  e.preventDefault();

  var element, rand;

  if (!copy.length) {
    copy = arr.slice(0);
    element = copy.splice(0, 1);
  } else {
    rand = Math.floor(Math.random() * copy.length);
    element = copy.splice(rand, 1);
  }

  var html = $("
", {
    "id":"",
    "html":$("", {
             "class": label.slice(0, -1).concat(" ", label, element),
             "html": label + element
           })
  });

  $(".categories ul").append(html);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button id="category_button">click</button>
<div class="categories">
  <ul>
  </ul>
</div></code>```

codepen http://codepen.io/anon/pen/PpXryW

Body:
When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning

As shown on image below it not starting off at label-default

Question each time I click on the button to create label how can I
  make sure it does not double up and starts from label-default

DEMO

CODEPEN DEMO

SCRIPT

$(document).on('click', '#category_button', function(e){

    e.preventDefault();

    //if ($("#label-" + category_name).length  == 0) {

        var rand = Math.floor((Math.random() * 5) + 1);

        switch(rand){
          case 1:
            element = 'label-default';
            break;
          case 2:
            element = 'label-primary';
            break;
          case 3:
            element = 'label-success';
            break;
          case 4:
            element = 'label-info';
            break;
          case 5:
            element = 'label-warning';
            break;
        }

        html = '';
        html += '
';
        html += '';
        html += 'Hello';
        html += '';
        html += '
';

        $('.categories ul').append(html);
    //}
});

Body:
You can use an array, Array.prototype.slice(), Array.prototype.splice() to create a copy of original array. If copied array has .length equal to 0 remove first element from array, set the element as element value, else get, set random element from copied array as element value, repeat procedure.

var arr = ["default", "primary", "success", "info", "warning"];
var label = "label-";
var copy = [];

$(document).on("click", "#category_button", function(e) {

  e.preventDefault();

  var element, rand;

  if (!copy.length) {
    copy = arr.slice(0);
    element = copy.splice(0, 1);
  } else {
    rand = Math.floor(Math.random() * copy.length);
    element = copy.splice(rand, 1);
  }

  var html = $("<li>", {
    "id":"",
    "html":$("<span>", {
             "class": label.slice(0, -1).concat(" ", label, element),
             "html": label + element
           })
  });

  $(".categories ul").append(html);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button id="category_button">click</button>
<div class="categories">
  <ul>
  </ul>
</div>

codepen http://codepen.io/anon/pen/PpXryW


问:
How do I create a constant in Python?
How do I declare a constant in Python?

In Java, we do:

public static final String CONST_NAME = "Name";
```

答:
You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.

```<code>import numpy as np

# declare a constant
CONSTANT = 'hello'

# put constant in numpy and make read only
CONSTANT = np.array([CONSTANT])
CONSTANT.flags.writeable = False
# alternatively: CONSTANT.setflags(write=0)

# call our constant using 0 index
print 'CONSTANT %s' % CONSTANT[0]

# attempt to modify our constant with try/except
new_value = 'goodbye'
try:
    CONSTANT[0] = new_value
except:
    print "cannot change CONSTANT to '%s' it's value '%s' is immutable" % (
        new_value, CONSTANT[0])

# attempt to modify our constant producing ValueError
CONSTANT[0] = new_value

>>>
CONSTANT hello
cannot change CONSTANT to 'goodbye' it's value 'hello' is immutable
Traceback (most recent call last):
  File "shuffle_test.py", line 15, in <module>
    CONSTANT[0] = new_value
ValueError: assignment destination is read-only
</code>```

of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:

```<code>CONSTANT = 'foo'
</code>```

and CONSTANT would change, however that would quickly throw an TypeError the first time CONSTANT[0] is later called in the script.

although... I suppose if you at some point changed it to

```<code>CONSTANT = [1,2,3]
</code>```

now you wouldn't get the TypeError anymore.  hmmmm....

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html

ContentLicense: CC BY-SA 4.0

Title: How do I create a constant in Python?

Body:
You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.

import numpy as np

# declare a constant
CONSTANT = 'hello'

# put constant in numpy and make read only
CONSTANT = np.array([CONSTANT])
CONSTANT.flags.writeable = False
# alternatively: CONSTANT.setflags(write=0)

# call our constant using 0 index
print 'CONSTANT %s' % CONSTANT[0]

# attempt to modify our constant with try/except
new_value = 'goodbye'
try:
    CONSTANT[0] = new_value
except:
    print "cannot change CONSTANT to '%s' it's value '%s' is immutable" % (
        new_value, CONSTANT[0])

# attempt to modify our constant producing ValueError
CONSTANT[0] = new_value

>>>
CONSTANT hello
cannot change CONSTANT to 'goodbye' it's value 'hello' is immutable
Traceback (most recent call last):
  File "shuffle_test.py", line 15, in <module>
    CONSTANT[0] = new_value
ValueError: assignment destination is read-only

of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:

CONSTANT = 'foo'

and CONSTANT would change, however that would quickly throw an TypeError the first time CONSTANT[0] is later called in the script.

although... I suppose if you at some point changed it to

CONSTANT = [1,2,3]

now you wouldn't get the TypeError anymore.  hmmmm....

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html


问:
Not able to create ChromeDriver object
My Selenium code is failing.When I run the code a blank chrome browser is opening but after that the error is throwing, Can anyone please help me..

The same code was running fine before 1 months.

Code using to create ChromeDriver

```<code>System.setProperty("webdriver.chrome.driver", "C:\\Windows\\chromedriver.exe");
    driver1 = new ChromeDriver(); //throwing the error here
    driver1.manage().window().maximize();
    driver1.manage().timeouts().pageLoadTimeout(60 * 5, TimeUnit.SECONDS);
</code>```

Console

```<code>Starting ChromeDriver 2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) on port 46687
Only local connections are allowed.
Apr 01, 2017 8:33:16 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Exception in thread "main" org.openqa.selenium.WebDriverException: java.net.SocketException: Connection reset
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'XXX', ip: 'XXX.XXX.X.XXX', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:241)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:128)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:141)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:174)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:163)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:120)
    at com.led.scrapper.main.Starter.main(Starter.java:36)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:209)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:261)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:165)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:272)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:142)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:88)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:108)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:64)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    ... 8 more
</code>```

Maven Dependency

```<code><dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.0.1</version>
</dependency>
</code>```

Chrome Driver Version

```<code>2.21
</code>```

答:
After looking into your error message,I understand you are using old version of chrome driver.

If you are using latest chrome browser versions, you need to get latest chrome driver from below mentioned url.

https://chromedriver.storage.googleapis.com/index.html

In my machine chrome driver 2.27 working fine with chrome browser version 56.

Let me know if you have any queries

Title: Not able to create ChromeDriver object

Body:
My Selenium code is failing.When I run the code a blank chrome browser is opening but after that the error is throwing, Can anyone please help me..

The same code was running fine before 1 months.

Code using to create ChromeDriver

System.setProperty("webdriver.chrome.driver", "C:\\Windows\\chromedriver.exe");
    driver1 = new ChromeDriver(); //throwing the error here
    driver1.manage().window().maximize();
    driver1.manage().timeouts().pageLoadTimeout(60 * 5, TimeUnit.SECONDS);

Console

Starting ChromeDriver 2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) on port 46687
Only local connections are allowed.
Apr 01, 2017 8:33:16 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Exception in thread "main" org.openqa.selenium.WebDriverException: java.net.SocketException: Connection reset
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'XXX', ip: 'XXX.XXX.X.XXX', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:241)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:128)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:141)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:174)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:163)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:120)
    at com.led.scrapper.main.Starter.main(Starter.java:36)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:209)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:261)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:165)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:272)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:142)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:88)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:108)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:64)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    ... 8 more

Maven Dependency

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.0.1</version>
</dependency>

Chrome Driver Version

2.21


问:
I can not publish an amendment to an application jsf
i've a problem with aplication developed in JSF, i fix the problem in development enviroment using netbeans, and everthing is OK.

The problem is when i try to publish the .class file, where the problem was, in apache tomcat 5.5.9 with de JVM 1.5.0_08, this file does work anymore.i dont know the validations that are done by tomcat, but i just change the name of the file that was being used for ".old".c ompilation was done on the same version of java tomcat

anyone know how to make this change??

Thank for any help

答:
You're redeploying an individual .class file in a web application?  I'm not surprised if that doesn't work; the class has probably already been loaded and JITted so replacing the bytecode on disk will have no effect.

Build a new version of the application's WAR (and the EAR that contains it, if there is one) and redeploy that.


问:
Can't Run WCF methods from a browser
I created a simple WCF service application, and try to change the WCF code, that it will also be able to be called from a client browser, but it only successfully runs from a WCF client.

running from browser, doesn't call the WCF service (but no error message in browser).

code:

Contract:

```<code>[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet]
    string Test();

    [OperationContract]
    [WebGet]
    string GetData(int value);
}
</code>```

Implementation:

```<code>public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public string Test()
    {
        return "test success";
    }
}
</code>```

Web.config:

```<code><?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="webHttpBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>
</code>```

Project URL:

```<code>http://localhost:1507/
</code>```

browser URL line - test method:

```<code>http://localhost:1507/Service1.svc/Test
</code>```

Thanks.

答:
at first you need to develop a restful service. please follow this config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="SoapBinding" />
      </basicHttpBinding>
      <mexHttpBinding>
        <binding name="MexBinding" />
      </mexHttpBinding>
      <webHttpBinding>
        <binding name="RestBinding" />
      </webHttpBinding>
    </bindings>

    <client />

    <services>
      <service behaviorConfiguration="ServiceBehavior" name="YourServiceName.Service1 ">
        <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="SoapBinding" name="Soap" contract="EyeMan.IService1 " />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Rest" contract="EyeMan.IService1 " />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="MexBinding" name="Mex" contract="IMetadataExchange" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>
</code>```

now you can create a EndPoint with GET method:

```<code>[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = @"/GetData?value={value}")]
public string GetData(int value)
{
    return string.Format("You entered: {0}", value);
}
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = @"/Test")]
public string Test()
{
    return "test success";
}
</code>```

now you are good to go. just call http://localhost:1507/Service1.svc/Test on your browser.

Title: Can't Run WCF methods from a browser

Body:
I created a simple WCF service application, and try to change the WCF code, that it will also be able to be called from a client browser, but it only successfully runs from a WCF client.

running from browser, doesn't call the WCF service (but no error message in browser).

code:

Contract:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet]
    string Test();

    [OperationContract]
    [WebGet]
    string GetData(int value);
}

Implementation:

public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public string Test()
    {
        return "test success";
    }
}

Web.config:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="webHttpBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Project URL:

http://localhost:1507/

browser URL line - test method:

http://localhost:1507/Service1.svc/Test

Thanks.

Body:
at first you need to develop a restful service. please follow this config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="SoapBinding" />
      </basicHttpBinding>
      <mexHttpBinding>
        <binding name="MexBinding" />
      </mexHttpBinding>
      <webHttpBinding>
        <binding name="RestBinding" />
      </webHttpBinding>
    </bindings>

    <client />

    <services>
      <service behaviorConfiguration="ServiceBehavior" name="YourServiceName.Service1 ">
        <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="SoapBinding" name="Soap" contract="EyeMan.IService1 " />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Rest" contract="EyeMan.IService1 " />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="MexBinding" name="Mex" contract="IMetadataExchange" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

now you can create a EndPoint with GET method:

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = @"/GetData?value={value}")]
public string GetData(int value)
{
    return string.Format("You entered: {0}", value);
}
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = @"/Test")]
public string Test()
{
    return "test success";
}

now you are good to go. just call http://localhost:1507/Service1.svc/Test on your browser.


问:
url path parameter with % sign
I am using rg.glassfish.jersey.server.ApplicationHandler
need to capture the url path

```<code>URL: video/Id19%2Fabc%3D/title?sub=CDA
</code>```

I have tried the following to capture but this doesn't capture % sign.

```<code>@Path("/video/{Id:.*}/title/")
</code>```

答:
I found a way to handle URL encoding request. It is handled on Application server level and in my case, it is apache tomcat. So all I need to do is set

org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in catalina.properties file.

Title: url path parameter with % sign

Body:
I am using rg.glassfish.jersey.server.ApplicationHandler
need to capture the url path

URL: video/Id19%2Fabc%3D/title?sub=CDA

I have tried the following to capture but this doesn't capture % sign.

@Path("/video/{Id:.*}/title/")


问:
How to Solve "Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created"
I am trying to make app widget for my app and show favoritebooks list into app widget. However, it shows error :

"Realm access from incorrect thread. Realm objects can only be
  accessed on the thread they were created."

```<code>FATAL EXCEPTION: Binder:3017_3
                                                                               Process: com.santossingh.capstoneproject, PID: 3017
                                                                               java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                                at io.realm.BaseRealm.checkIfValid(BaseRealm.java:353)
                                                                                at io.realm.RealmResults.isLoaded(RealmResults.java:88)
                                                                                at io.realm.OrderedRealmCollectionImpl.size(OrderedRealmCollectionImpl.java:303)
                                                                                at io.realm.RealmResults.size(RealmResults.java:53)
                                                                                at com.santossingh.capstoneproject.Widget.ListProvider.getCount(ListProvider.java:57)
                                                                                at android.widget.RemoteViewsService$RemoteViewsFactoryAdapter.getCount(RemoteViewsService.java:154)
                                                                                at com.android.internal.widget.IRemoteViewsFactory$Stub.onTransact(IRemoteViewsFactory.java:75)
                                                                                at android.os.Binder.execTransact(Binder.java:565)
03-31 20:32:01.058 1298-1458/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
</code>```

If you know about it please give me a clear example about access data into other activity OR how to call particular Thread where realm database created.

1- ConfigActivity

```<code>public class ConfigActivity extends AppCompatActivity {

    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    Realm realm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build();
        realm=Realm.getInstance(config);
        assignAppWidgetId();
        startWidget();
    }

    /**
     * Widget configuration activity,always receives appwidget Id appWidget Id =
     * unique id that identifies your widget analogy : same as setting view id
     * via @+id/viewname on layout but appwidget id is assigned by the system
     * itself
     */
    private void assignAppWidgetId() {
        Bundle extras = getIntent().getExtras();
        if (extras != null)
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    /**
     * This method right now displays the widget and starts a Service to fetch
     * remote data from Server
     */
    private void startWidget() {

        // this intent is essential to show the widget
        // if this intent is not included,you can't show
        // widget on homescreen
        Intent intent = new Intent();
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        setResult(Activity.RESULT_OK, intent);

        // start your service
        // to fetch data from web
        Intent serviceIntent = new Intent(this, ListProvider.class);
        serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        startService(serviceIntent);

        // finish this activity
        this.finish();

    }
</code>```

2- ListProvider class

```<code>public class ListProvider implements RemoteViewsService.RemoteViewsFactory {
    private MyHandlerThread mHandlerThread=new MyHandlerThread();
    private Context context = null;
    private int appWidgetId;
    RealmResults<FavoriteBooks> booksList;
    RealmConfiguration config;

    public ListProvider(Context context, Intent intent) {
        this.context = context;
        appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        getDataFromRealm(context);
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDataSetChanged() {
        getDataFromRealm(context);
    }

    @Override
    public void onDestroy() {
    }

    @Override
    public int getCount() {
        return booksList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public RemoteViews getViewAt(final int position) {
        final Lock lock = new Lock();
        final RemoteViews[] result = {null};
        mHandlerThread.getHandler().post(new Runnable() {
            @Override
            public void run() {
                // You can safely access results here.
                result[0] = new RemoteViews(context.getPackageName(), R.layout.widget_item);
                if (booksList!=null) {
                    FavoriteBooks book = booksList.get(position);
                    result[0].setTextViewText(R.id.widgetText, book.getTitle());
                }
                lock.unlock();

            }
        });
        try {
            lock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result[0];
    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 0;
    }

    //------------
    public class Lock {
        private boolean isLocked;

        public synchronized void lock() throws InterruptedException {
            isLocked = true;
            while (isLocked) {
                wait();
            }
        }

        public synchronized void unlock() {
            isLocked = false;
            notify();
        }
    }

    public class MyHandlerThread extends HandlerThread {
        private Handler mHandler;

        public MyHandlerThread() {
            super("MY_HANDLER_THREAD");
            start();
            mHandler = new Handler(getLooper());
        }

        public Handler getHandler() {
            return mHandler;
        }
    }

    private void getDataFromRealm(final Context context) {
        final Lock lock = new Lock();
        mHandlerThread.getHandler().post(new Runnable() {
            @Override
            public void run() {
                Realm.init(context);
                config = new RealmConfiguration.Builder()
                        .name("favorite1.realm")
                        .schemaVersion(1)
                        .deleteRealmIfMigrationNeeded()
                        .build();
                Realm realm = Realm.getInstance(config);
                booksList = realm.where(FavoriteBooks.class).findAll();
                lock.unlock();
            }
        });
        try {
            lock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
</code>```

3- WidgetService class

```<code>public class WidgetService extends RemoteViewsService {
/*
* So pretty simple just defining the Adapter of the listview
* here Adapter is ListProvider
* */

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        int appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        // call and return listprovider class
        return (new ListProvider(this.getApplicationContext(), intent));
    }

}
</code>```

4- WidgetProvider class

```<code>public class WidgetProvider extends AppWidgetProvider {

    public final static String DATA_FETCHED="com.santossingh.capstoneproject.DATA_FETCHED";

    @Override
    public void onUpdate(Context context, AppWidgetManager
            appWidgetManager, int[] appWidgetIds) {

        final int N = appWidgetIds.length;
        for (int i = 0; i < N; ++i) {

            RemoteViews remoteViews = updateAppWidget(context,
                    appWidgetIds[i]);
            appWidgetManager.updateAppWidget(appWidgetIds[i],
                    remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private RemoteViews updateAppWidget(Context context, int appWidgetId) {

        //which layout to show on widget
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        //RemoteViews Service needed to provide adapter for ListView
        Intent svcIntent = new Intent(context, WidgetService.class);
        //passing app widget id to that RemoteViews Service
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        //setting a unique Uri to the intent
        //don't know its purpose to me right now
        svcIntent.setData(Uri.parse(
                svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
        //setting adapter to gridView of the widget
        remoteViews.setRemoteAdapter(appWidgetId, R.id.gridViewWidget,
                svcIntent);
        //setting an empty view in case of no data
        remoteViews.setEmptyView(R.id.gridViewWidget, R.id.emptyTextViewWidget);
        return remoteViews;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if (intent.getAction().equals(DATA_FETCHED)) {
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            RemoteViews remoteViews = updateAppWidget(context, appWidgetId);
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }
}
</code>```

5- RemoteFetchService class

```<code>public class RemoteFetchService extends Service {

    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * Retrieve appwidget id from intent it is needed to update widget later
     * initialize our AQuery class
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
            appWidgetId = intent.getIntExtra(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);

        populateWidget();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * Method which sends broadcast to WidgetProvider
     * so that widget is notified to do necessary action
     * and here action == WidgetProvider.DATA_FETCHED
     */
    private void populateWidget() {

        Intent widgetUpdateIntent = new Intent();
        widgetUpdateIntent.setAction(WidgetProvider.DATA_FETCHED);
        widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                appWidgetId);
        sendBroadcast(widgetUpdateIntent);

        this.stopSelf();
    }
</code>```

6- FavoriteBooks class extends RealmObject

```<code>public class FavoriteBooks extends RealmObject {

    @PrimaryKey
    private String id;
    private String title;
    private String author;
    private String buyLink;
    private String image;
    private String price;
    private String publishedDate;
    private String reviewLink;
    private String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getBuyLink() {
        return buyLink;
    }

    public void setBuyLink(String buyLink) {
        this.buyLink = buyLink;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(String publishedDate) {
        this.publishedDate = publishedDate;
    }

    public String getReviewLink() {
        return reviewLink;
    }

    public void setReviewLink(String reviewLink) {
        this.reviewLink = reviewLink;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}
</code>```

So Please help me... It would be great if you could correct my ListProvider.class where that error shows on

```<code>@Override
    public int getCount() {
        return booksList.size();
    }
</code>```

答: Concise answer: Realm results are lazy loaded, so I'd say you don't need to perform the query on another thread. Create a Realm for the RemoteView (or ListProvider), then use it to query as normal. The Realm object will only load data when accessed.</p>

Body:
I am trying to make app widget for my app and show favoritebooks list into app widget. However, it shows error :

"Realm access from incorrect thread. Realm objects can only be
  accessed on the thread they were created."

FATAL EXCEPTION: Binder:3017_3
                                                                               Process: com.santossingh.capstoneproject, PID: 3017
                                                                               java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                                at io.realm.BaseRealm.checkIfValid(BaseRealm.java:353)
                                                                                at io.realm.RealmResults.isLoaded(RealmResults.java:88)
                                                                                at io.realm.OrderedRealmCollectionImpl.size(OrderedRealmCollectionImpl.java:303)
                                                                                at io.realm.RealmResults.size(RealmResults.java:53)
                                                                                at com.santossingh.capstoneproject.Widget.ListProvider.getCount(ListProvider.java:57)
                                                                                at android.widget.RemoteViewsService$RemoteViewsFactoryAdapter.getCount(RemoteViewsService.java:154)
                                                                                at com.android.internal.widget.IRemoteViewsFactory$Stub.onTransact(IRemoteViewsFactory.java:75)
                                                                                at android.os.Binder.execTransact(Binder.java:565)
03-31 20:32:01.058 1298-1458/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property

If you know about it please give me a clear example about access data into other activity OR how to call particular Thread where realm database created.

1- ConfigActivity

public class ConfigActivity extends AppCompatActivity {

    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    Realm realm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build();
        realm=Realm.getInstance(config);
        assignAppWidgetId();
        startWidget();
    }

    /**
     * Widget configuration activity,always receives appwidget Id appWidget Id =
     * unique id that identifies your widget analogy : same as setting view id
     * via @+id/viewname on layout but appwidget id is assigned by the system
     * itself
     */
    private void assignAppWidgetId() {
        Bundle extras = getIntent().getExtras();
        if (extras != null)
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    /**
     * This method right now displays the widget and starts a Service to fetch
     * remote data from Server
     */
    private void startWidget() {

        // this intent is essential to show the widget
        // if this intent is not included,you can't show
        // widget on homescreen
        Intent intent = new Intent();
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        setResult(Activity.RESULT_OK, intent);

        // start your service
        // to fetch data from web
        Intent serviceIntent = new Intent(this, ListProvider.class);
        serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        startService(serviceIntent);

        // finish this activity
        this.finish();

    }

2- ListProvider class

public class ListProvider implements RemoteViewsService.RemoteViewsFactory {
    private MyHandlerThread mHandlerThread=new MyHandlerThread();
    private Context context = null;
    private int appWidgetId;
    RealmResults<FavoriteBooks> booksList;
    RealmConfiguration config;

    public ListProvider(Context context, Intent intent) {
        this.context = context;
        appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        getDataFromRealm(context);
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDataSetChanged() {
        getDataFromRealm(context);
    }

    @Override
    public void onDestroy() {
    }

    @Override
    public int getCount() {
        return booksList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public RemoteViews getViewAt(final int position) {
        final Lock lock = new Lock();
        final RemoteViews[] result = {null};
        mHandlerThread.getHandler().post(new Runnable() {
            @Override
            public void run() {
                // You can safely access results here.
                result[0] = new RemoteViews(context.getPackageName(), R.layout.widget_item);
                if (booksList!=null) {
                    FavoriteBooks book = booksList.get(position);
                    result[0].setTextViewText(R.id.widgetText, book.getTitle());
                }
                lock.unlock();

            }
        });
        try {
            lock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result[0];
    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 0;
    }

    //------------
    public class Lock {
        private boolean isLocked;

        public synchronized void lock() throws InterruptedException {
            isLocked = true;
            while (isLocked) {
                wait();
            }
        }

        public synchronized void unlock() {
            isLocked = false;
            notify();
        }
    }

    public class MyHandlerThread extends HandlerThread {
        private Handler mHandler;

        public MyHandlerThread() {
            super("MY_HANDLER_THREAD");
            start();
            mHandler = new Handler(getLooper());
        }

        public Handler getHandler() {
            return mHandler;
        }
    }

    private void getDataFromRealm(final Context context) {
        final Lock lock = new Lock();
        mHandlerThread.getHandler().post(new Runnable() {
            @Override
            public void run() {
                Realm.init(context);
                config = new RealmConfiguration.Builder()
                        .name("favorite1.realm")
                        .schemaVersion(1)
                        .deleteRealmIfMigrationNeeded()
                        .build();
                Realm realm = Realm.getInstance(config);
                booksList = realm.where(FavoriteBooks.class).findAll();
                lock.unlock();
            }
        });
        try {
            lock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

3- WidgetService class

public class WidgetService extends RemoteViewsService {
/*
* So pretty simple just defining the Adapter of the listview
* here Adapter is ListProvider
* */

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        int appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        // call and return listprovider class
        return (new ListProvider(this.getApplicationContext(), intent));
    }

}

4- WidgetProvider class

public class WidgetProvider extends AppWidgetProvider {

    public final static String DATA_FETCHED="com.santossingh.capstoneproject.DATA_FETCHED";

    @Override
    public void onUpdate(Context context, AppWidgetManager
            appWidgetManager, int[] appWidgetIds) {

        final int N = appWidgetIds.length;
        for (int i = 0; i < N; ++i) {

            RemoteViews remoteViews = updateAppWidget(context,
                    appWidgetIds[i]);
            appWidgetManager.updateAppWidget(appWidgetIds[i],
                    remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private RemoteViews updateAppWidget(Context context, int appWidgetId) {

        //which layout to show on widget
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        //RemoteViews Service needed to provide adapter for ListView
        Intent svcIntent = new Intent(context, WidgetService.class);
        //passing app widget id to that RemoteViews Service
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        //setting a unique Uri to the intent
        //don't know its purpose to me right now
        svcIntent.setData(Uri.parse(
                svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
        //setting adapter to gridView of the widget
        remoteViews.setRemoteAdapter(appWidgetId, R.id.gridViewWidget,
                svcIntent);
        //setting an empty view in case of no data
        remoteViews.setEmptyView(R.id.gridViewWidget, R.id.emptyTextViewWidget);
        return remoteViews;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if (intent.getAction().equals(DATA_FETCHED)) {
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            RemoteViews remoteViews = updateAppWidget(context, appWidgetId);
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }
}

5- RemoteFetchService class

public class RemoteFetchService extends Service {

    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * Retrieve appwidget id from intent it is needed to update widget later
     * initialize our AQuery class
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
            appWidgetId = intent.getIntExtra(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);

        populateWidget();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * Method which sends broadcast to WidgetProvider
     * so that widget is notified to do necessary action
     * and here action == WidgetProvider.DATA_FETCHED
     */
    private void populateWidget() {

        Intent widgetUpdateIntent = new Intent();
        widgetUpdateIntent.setAction(WidgetProvider.DATA_FETCHED);
        widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                appWidgetId);
        sendBroadcast(widgetUpdateIntent);

        this.stopSelf();
    }

6- FavoriteBooks class extends RealmObject

public class FavoriteBooks extends RealmObject {

    @PrimaryKey
    private String id;
    private String title;
    private String author;
    private String buyLink;
    private String image;
    private String price;
    private String publishedDate;
    private String reviewLink;
    private String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getBuyLink() {
        return buyLink;
    }

    public void setBuyLink(String buyLink) {
        this.buyLink = buyLink;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(String publishedDate) {
        this.publishedDate = publishedDate;
    }

    public String getReviewLink() {
        return reviewLink;
    }

    public void setReviewLink(String reviewLink) {
        this.reviewLink = reviewLink;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

So Please help me... It would be great if you could correct my ListProvider.class where that error shows on

@Override
    public int getCount() {
        return booksList.size();
    }


问:
Excel "Cannot Open PivotTable Source" error when opening directly to Excel from DL
I have a website that generates some Excel spreadsheets and provides a download link to the end-user.  One of these spreadsheets is a fairly convoluted one with multiple charts based on multiple pivot tables.

For a few of our users, when they choose to "Open" the file immediately (as opposed to "Save As" to put it in a known path), we are running into problems when trying to refresh the pivot tables:

Cannot open PivotTable source file: 'C:\Users\joeuser\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\Content.ie5\W9IZXYBM[excel_file_name.xlsm]PivotTableSourceSheetName'

If the user chooses "Save" instead of "Open", the refresh works fine, so our users have a workaround, but can anyone shed light on what might cause only a few users to have this problem with the "Open" scenario?   We haven't spotted anything glaringly different between machines that "Open" the file just fine and those that don't.  Same browser versions, same Office versions, etc.

答:
Cannot open PivotTable source file: 'C:\Users\joeuser\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\Content.ie5\W9IZXYBM[excel_file_name.xlsm]PivotTableSourceSheetName'

The file referenced in error is an xlsm (macro enabled xlsx). This may cause issue. "Open" opens file in IE cache folder treated as internet content, it should have sth to do with the restrictions MSO imposed on internet oriented content. "Save"ed file are local file, which don't suffer from those restrictions. Considering the difference. Maybe change to xlsx ? Besides that I don't think there is anything you can do to circumvent it.


问:
"Between" Statement in Left Join Returns null
OK, there's GOT to be an answer to this... likely a straightforward solution for one of the many experts here at Stack Overflow! :-)

Background:
I am trying to create a restaurant sales report by shift. I have 2 tables... one with RECEIPT details (restaurant, date, time, receipt#, amount, server, etc.) and another with SHIFT details (restaurant, shift start time, shift end time & shift name). There are Shift Numbers in both tables, but unfortunately the Shift Numbers in the Receipts table are not always accurate, so I am having to come up with a workaround based on which bucket of ShiftStart & ShiftEnd times the ReceiptTime falls into. This code for the join almost works:

```<code>LEFT OUTER JOIN: Receipts.Time BETWEEN ShiftDetails.ShiftStartTime AND ShiftsDetails.ShiftEndTime
</code>```

BUT... my challenge is that the Dinner ShiftEndTime is currently 02:00, which (of course) is less than the Dinner ShiftStartTime of 17:31, so any ReceiptTimes "between" these hours returns a null value. I would also like to keep the query dynamic by avoiding "hard coding" the Start/End times, instead using those in the Shift table, as they are likely to be revised in the future.

FWIW, my data source is SQL Server with Power BI as a front-end, so alternatively I could scrap the SQL code and perform magic with PowerQuery or DAX...

Many thanks in advance!
Danny

答:
You are missing a function that says if the shift end time is less than 4:00 AM than return the DateTime for the next day's date.

So it would be used in a join like:

```<code>WHERE ShiftEndDateTime <= dbo.EndShiftDateTime(@ShiftDate, @ShiftEndTime)
</code>```

This bumps it to the next day if the hour is less than 5:

```<code>CREATE FUNCTION dbo.EndShiftDateTime(@ShiftDate Date, @ShiftTime Time)
  RETURNS DateTime
AS
BEGIN

IF(DATEPART(HOUR, @ShiftTime) < 5)
    SET @ShiftDate =  dateadd(day, 1, @ShiftDate)

RETURN cast(@ShiftDate as datetime)  + cast(@ShiftTime as datetime)

END
</code>```

I don't like hard coding an hour like this, but it is unlikely to ever change. You could make the logic to be more flexible (if endtime < starttime) but I've seen that that just leads to hard to find bugs.

Body:
OK, there's GOT to be an answer to this... likely a straightforward solution for one of the many experts here at Stack Overflow! :-)

Background:
I am trying to create a restaurant sales report by shift. I have 2 tables... one with RECEIPT details (restaurant, date, time, receipt#, amount, server, etc.) and another with SHIFT details (restaurant, shift start time, shift end time & shift name). There are Shift Numbers in both tables, but unfortunately the Shift Numbers in the Receipts table are not always accurate, so I am having to come up with a workaround based on which bucket of ShiftStart & ShiftEnd times the ReceiptTime falls into. This code for the join almost works:

LEFT OUTER JOIN: Receipts.Time BETWEEN ShiftDetails.ShiftStartTime AND ShiftsDetails.ShiftEndTime

BUT... my challenge is that the Dinner ShiftEndTime is currently 02:00, which (of course) is less than the Dinner ShiftStartTime of 17:31, so any ReceiptTimes "between" these hours returns a null value. I would also like to keep the query dynamic by avoiding "hard coding" the Start/End times, instead using those in the Shift table, as they are likely to be revised in the future.

FWIW, my data source is SQL Server with Power BI as a front-end, so alternatively I could scrap the SQL code and perform magic with PowerQuery or DAX...

Many thanks in advance!
Danny

Body:
You are missing a function that says if the shift end time is less than 4:00 AM than return the DateTime for the next day's date.

So it would be used in a join like:

WHERE ShiftEndDateTime <= dbo.EndShiftDateTime(@ShiftDate, @ShiftEndTime)

This bumps it to the next day if the hour is less than 5:

CREATE FUNCTION dbo.EndShiftDateTime(@ShiftDate Date, @ShiftTime Time)
  RETURNS DateTime
AS
BEGIN

IF(DATEPART(HOUR, @ShiftTime) < 5)
    SET @ShiftDate =  dateadd(day, 1, @ShiftDate)

RETURN cast(@ShiftDate as datetime)  + cast(@ShiftTime as datetime)

END

I don't like hard coding an hour like this, but it is unlikely to ever change. You could make the logic to be more flexible (if endtime < starttime) but I've seen that that just leads to hard to find bugs.