问:
Window handles with new Window URL
How does Windows handles in selenium  paste a URL from 2nd window to a new window

When I submit all information in this form(https://equallevel.com/punchout/cxml-punchout-tester#advanced) it opens a new window.In new window it redirects to another site where I need to do some user interactions.Here at this point I have Iframe in last redirected site.So I want to get that URL from here and put it in another tab to perform user actions
How do I grab the URL(from 2nd window) to a new window from getWindowHandles()

答:
Refer the below code snippet, It will return the URL to a String variable.

```<code>public void switchWindow(String name){
        String URL = null;
        wait.waitForWindowToBeActiveAndSwitchToIt(2);
   System.out.println(driver.getWindowHandles().size());

          for (String current : driver.getWindowHandles()) {
              if(driver.getTitle().equals(name)){
              System.out.println("Switched to window titled =>" +driver.getTitle());
              URL = driver.getCurrentUrl();
              break;
              }

              System.out.println("Switching to window handle:"+ current + "\n title: "+ driver.getTitle());
              driver.switchTo().window(current);
              }
    }
</code>```

To open this URL in new tab , do this :

```<code>driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().To(URL);
</code>```

Title: Window handles with new Window URL

Body:
Refer the below code snippet, It will return the URL to a String variable.

public void switchWindow(String name){
        String URL = null;
        wait.waitForWindowToBeActiveAndSwitchToIt(2);
   System.out.println(driver.getWindowHandles().size());

          for (String current : driver.getWindowHandles()) {
              if(driver.getTitle().equals(name)){
              System.out.println("Switched to window titled =>" +driver.getTitle());
              URL = driver.getCurrentUrl();
              break;
              }

              System.out.println("Switching to window handle:"+ current + "\n title: "+ driver.getTitle());
              driver.switchTo().window(current);
              }
    }

To open this URL in new tab , do this :

driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().To(URL);


来源: stackexchange

问:
ERROR TypeError: Cannot read property 'unread' of undefined
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

```<code>ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
</code>```

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

```<code>    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>
</code>```

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

答:
Check whether thread exist for the user before trying to access unthread property. Please let me know if you still face that issue</p>

```<code>if (thread[this.userId] && thread[this.userId].unread) {
              this.unread = true;
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

Body:
Check whether thread exist for the user before trying to access unthread property. Please let me know if you still face that issue

if (thread[this.userId] && thread[this.userId].unread) {
              this.unread = true;
            }


问:
How do I set start year and end year of jquery date picker?
When I initialize a jquery date picker like

```<code>$( "#datepicker" ).datepicker({
    changeMonth: true,
    changeYear: true
});
</code>```

The showing the date picker from year 2000 to year 2020.

EDIT:

When i go to year 2000, the next time it shows from 1990, but any way I want to customize it.

How do I set the from year and to year that will fit for my requirements.

Thanks in advance.

答:
start date must be limit at most 2 year selection

```<code> $(document).on('change', '#startdate', function () {
        var current=$(this).val();
        var currentYear = current.split("-");
        var compareYear=(new Date().getFullYear()-1);
            if(compareYear > currentYear[0]){
                $('#limitMsg').text('this year must at most one year from current date');
                $('#submit').prop('disabled', true);
            }else{
                $('#limitMsg').text('');
                $('#submit').prop('disabled', false);
            }
  });
</code>```

Body:
When I initialize a jquery date picker like

$( "#datepicker" ).datepicker({
    changeMonth: true,
    changeYear: true
});

The showing the date picker from year 2000 to year 2020.

EDIT:

When i go to year 2000, the next time it shows from 1990, but any way I want to customize it.

How do I set the from year and to year that will fit for my requirements.

Thanks in advance.

Body:
start date must be limit at most 2 year selection

 $(document).on('change', '#startdate', function () {
        var current=$(this).val();
        var currentYear = current.split("-");
        var compareYear=(new Date().getFullYear()-1);
            if(compareYear > currentYear[0]){
                $('#limitMsg').text('this year must at most one year from current date');
                $('#submit').prop('disabled', true);
            }else{
                $('#limitMsg').text('');
                $('#submit').prop('disabled', false);
            }
  });


问:
Passing 3 textbox values to a javascript function from ASPX
I want to pass three textbox values to a javascript function. However its not working.Any help is really appreciated.This is what I have tried.</p>

```<code><asp:ImageButton ID="ibut_cheque2" runat="server" target="_blank"
OnClientClick='<%# string.Format("window.open(\"Product.aspx?pid=\" +
document.getElementById(\"{0}\").value & chdate=\" +
document.getElementById(\"{1}\").value & pname=\" +
document.getElementById(\"{2}\").value,
null,\"scrollbars=yes,top=10,left=10\", \"true\");",
Form.FindControl("txt_voucher").ClientID,
Form.FindControl("txtbox_chqdate").ClientID,
Form.FindControl("txtbox_chprovider").ClientID)%>'
AlternateText="Print" CssClass="btn5" ForeColor="White" ToolTip="Print Cheque" />
</code>```

答:
On first Page Button click code

```<code><script>
var value1="value1";
var value2="value2";
var queryString = "?para1=" + value1 + "&para2=" + value2;
window.location.href = "page2.html" + queryString;
</script>
</code>```

On Second Page

```<code><script>

var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
for (var i = 0; i < queries.length; i++)
{
  document.write(queries[i] + "<br>");
}

</script>
</code>```

Hope this will help you

Body:
I want to pass three textbox values to a javascript function. However its not working.Any help is really appreciated.This is what I have tried.

<asp:ImageButton ID="ibut_cheque2" runat="server" target="_blank"
OnClientClick='<%# string.Format("window.open(\"Product.aspx?pid=\" +
document.getElementById(\"{0}\").value & chdate=\" +
document.getElementById(\"{1}\").value & pname=\" +
document.getElementById(\"{2}\").value,
null,\"scrollbars=yes,top=10,left=10\", \"true\");",
Form.FindControl("txt_voucher").ClientID,
Form.FindControl("txtbox_chqdate").ClientID,
Form.FindControl("txtbox_chprovider").ClientID)%>'
AlternateText="Print" CssClass="btn5" ForeColor="White" ToolTip="Print Cheque" />

Body:
On first Page Button click code

<script>
var value1="value1";
var value2="value2";
var queryString = "?para1=" + value1 + "&para2=" + value2;
window.location.href = "page2.html" + queryString;
</script>

On Second Page

<script>

var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
for (var i = 0; i < queries.length; i++)
{
  document.write(queries[i] + "<br>");
}

</script>

Hope this will help you


问:
converting a Haskell function into java "function"
I have this function in Haskell, and I am wondering how it can be converted to Java, especially using streams:</p>

```<code>build = [(w,m,n,g) | w <- [240..1280], m <- [2,4..20], n <- [2..100], g <- [240..1280], ((w - 2*m - n*g) `mod` (n+1) == 0), n*g+2*m <= w, n*g <= w]
</code>```

答:
(I'm not a Haskell expert, but I know enough to be dangerous.)

The example code given has several Haskell constructs that map reasonably
well into Java constructs:

A Haskell list is lazy, so it corresponds to a Java Stream.

The ranges used are of integers, so they correspond to IntStream.
For example, [240..1280] corresponds to IntStream.rangeClosed(240, 1280).

A range with a step has no direct correspondence in Java, but it can easily
be computed; you just have to do a bit of arithmetic and then map the values
from the sequential range to the one with steps. For example, [2, 4..20]
can be written as

```<code>IntStream.rangeClosed(1, 10).map(i -> 2 * i)
</code>```

A condition on a list comprehension corresponds to filtering a stream through
a predicate.

A comprehension with multiple generators corresponds to flatmapping
of nested streams.

There is no general way to represent tuples in Java. Various third party
libraries provide tuple implementations with varying tradeoffs regarding
generics and boxing. Or, you can just write your own class with the fields
you want. (This can be quite tedious if you use lots of different kinds of
tuples, though.) In this case, the tuple is simply four ints, so it's easily
represented using an int array with four elements.

Putting it all together, we get the following.

```<code>static Stream<int[]> build() {
    return IntStream.rangeClosed(240, 1280).boxed()
               .flatMap(w -> IntStream.rangeClosed(1, 10).map(m -> 2 * m).boxed()
                   .flatMap(m -> IntStream.rangeClosed(2, 100).boxed()
                       .flatMap(n -> IntStream.rangeClosed(240, 1280)
                                              .filter(g -> ((w - 2*m - n*g) % (n+1) == 0))
                                              .filter(g -> n*g+2*m <= w)
                                              .filter(g -> n*g <= w)
                                              .mapToObj(g -> new int[] { w, m, n, g }))));
}
</code>```

This is clearly quite verbose compared to the original Haskell, but you can easily see where the Haskell constructs have ended up in the Java code. I believe this is correct, as it seems to generate the same output as the Haskell code.

Note that we are generating values using IntStream but we want the flatmap to give a stream of arrays (which are objects), whereas IntStream.flatMap returns an IntStream. Perhaps ideally there would be a flatMapToObj operation, but there isn't, so we must box the int value into an Integer object and then call Stream.flatMap it.

One could assign the stream pipeline to a variable of type Stream, but this wouldn't be very convenient, as Java streams can be used at most once. Since constructing such a stream is cheap (compared to evaluating it) it's reasonable to write a function build() that returns a freshly created stream, ready to be evaluated by the caller.

When the following Java code is run,

```<code>    System.out.println(build().count());
    System.out.println(build().findFirst().map(Arrays::toString).orElse("not found"));
    System.out.println(build().reduce((a, b) -> b).map(Arrays::toString).orElse("not found"));
</code>```

the result is:

```<code>654559
[484, 2, 2, 240]
[1280, 20, 5, 248]
</code>```

Running the following Haskell code (the definition of build is copied from the question)

```<code>build = [(w,m,n,g) | w <- [240..1280], m <- [2,4..20], n <- [2..100], g <- [240..1280],
                     ((w - 2*m - n*g) `mod` (n+1) == 0), n*g+2*m <= w, n*g <= w]

main = do
    print (length build)
    print (head build)
    print (last build)
</code>```

gives the following output:

```<code>654559
(484,2,2,240)
(1280,20,5,248)
</code>```

So the transliteration appears correct to my eye.

Times for the head (in Java, findFirst) and last (in Java, reduce((a, b) -> b)) operations were as follows: (updated using GHC 7.6.3 -O2)

```<code>       head     last
GHC      8s      36s
JDK      3s       9s
</code>```

This at least shows that both systems provide laziness, as the computation is short-circuited after the first element is found, whereas finding the last element requires all to be computed.

Interestingly, in Haskell, calling all three of length, head, and last doesn't take any more time than just calling last (around 36s) presumably because of memoization. There's no memoization in Java, but of course you could explicitly store the results in an array or List and process that multiple times.

Overall, though, I was startled at how much faster the Java implementation is. I don't really understand Haskell performance, so I'll leave it to Haskell experts to comment on that. It's quite possible I've done something wrong, though mostly I just copied the function from the question into a file and compiled it using GHC.

My environment:

JDK 9, GHC 7.6.3 -O2, MacBook Pro mid 2014 2-core 3GHz Intel Core i7

Body:
I have this function in Haskell, and I am wondering how it can be converted to Java, especially using streams:

build = [(w,m,n,g) | w <- [240..1280], m <- [2,4..20], n <- [2..100], g <- [240..1280], ((w - 2*m - n*g) `mod` (n+1) == 0), n*g+2*m <= w, n*g <= w]

Body:
(I'm not a Haskell expert, but I know enough to be dangerous.)

The example code given has several Haskell constructs that map reasonably
well into Java constructs:

A Haskell list is lazy, so it corresponds to a Java Stream.

The ranges used are of integers, so they correspond to IntStream.
For example, [240..1280] corresponds to IntStream.rangeClosed(240, 1280).

A range with a step has no direct correspondence in Java, but it can easily
be computed; you just have to do a bit of arithmetic and then map the values
from the sequential range to the one with steps. For example, [2, 4..20]
can be written as

IntStream.rangeClosed(1, 10).map(i -> 2 * i)

A condition on a list comprehension corresponds to filtering a stream through
a predicate.

A comprehension with multiple generators corresponds to flatmapping
of nested streams.

There is no general way to represent tuples in Java. Various third party
libraries provide tuple implementations with varying tradeoffs regarding
generics and boxing. Or, you can just write your own class with the fields
you want. (This can be quite tedious if you use lots of different kinds of
tuples, though.) In this case, the tuple is simply four ints, so it's easily
represented using an int array with four elements.

Putting it all together, we get the following.

static Stream<int[]> build() {
    return IntStream.rangeClosed(240, 1280).boxed()
               .flatMap(w -> IntStream.rangeClosed(1, 10).map(m -> 2 * m).boxed()
                   .flatMap(m -> IntStream.rangeClosed(2, 100).boxed()
                       .flatMap(n -> IntStream.rangeClosed(240, 1280)
                                              .filter(g -> ((w - 2*m - n*g) % (n+1) == 0))
                                              .filter(g -> n*g+2*m <= w)
                                              .filter(g -> n*g <= w)
                                              .mapToObj(g -> new int[] { w, m, n, g }))));
}

This is clearly quite verbose compared to the original Haskell, but you can easily see where the Haskell constructs have ended up in the Java code. I believe this is correct, as it seems to generate the same output as the Haskell code.

Note that we are generating values using IntStream but we want the flatmap to give a stream of arrays (which are objects), whereas IntStream.flatMap returns an IntStream. Perhaps ideally there would be a flatMapToObj operation, but there isn't, so we must box the int value into an Integer object and then call Stream.flatMap it.

One could assign the stream pipeline to a variable of type Stream, but this wouldn't be very convenient, as Java streams can be used at most once. Since constructing such a stream is cheap (compared to evaluating it) it's reasonable to write a function build() that returns a freshly created stream, ready to be evaluated by the caller.

When the following Java code is run,

    System.out.println(build().count());
    System.out.println(build().findFirst().map(Arrays::toString).orElse("not found"));
    System.out.println(build().reduce((a, b) -> b).map(Arrays::toString).orElse("not found"));

the result is:

654559
[484, 2, 2, 240]
[1280, 20, 5, 248]

Running the following Haskell code (the definition of build is copied from the question)

build = [(w,m,n,g) | w <- [240..1280], m <- [2,4..20], n <- [2..100], g <- [240..1280],
                     ((w - 2*m - n*g) `mod` (n+1) == 0), n*g+2*m <= w, n*g <= w]

main = do
    print (length build)
    print (head build)
    print (last build)

gives the following output:

654559
(484,2,2,240)
(1280,20,5,248)

So the transliteration appears correct to my eye.

Times for the head (in Java, findFirst) and last (in Java, reduce((a, b) -> b)) operations were as follows: (updated using GHC 7.6.3 -O2)

       head     last
GHC      8s      36s
JDK      3s       9s

This at least shows that both systems provide laziness, as the computation is short-circuited after the first element is found, whereas finding the last element requires all to be computed.

Interestingly, in Haskell, calling all three of length, head, and last doesn't take any more time than just calling last (around 36s) presumably because of memoization. There's no memoization in Java, but of course you could explicitly store the results in an array or List and process that multiple times.

Overall, though, I was startled at how much faster the Java implementation is. I don't really understand Haskell performance, so I'll leave it to Haskell experts to comment on that. It's quite possible I've done something wrong, though mostly I just copied the function from the question into a file and compiled it using GHC.

My environment:

JDK 9, GHC 7.6.3 -O2, MacBook Pro mid 2014 2-core 3GHz Intel Core i7


问:
How should I handle a shared database that needs to be referenced by multiple applications?
In my SOA, I have 2 services - a users service and products service.  Both users and products can be "tagged" with 2 objects - countries and industries.  This means that both services will have a join table and future services will need that as well. I would like the database of countries and industries to be standard and managed from one place if possible.  There are a few options I can think of:

Keep the countries, industries, and
other shared databases on it's own
server and allow external read only
connections while manipulating the
data would have to be done by one
app whose sole purpose is to manage
that data.

Keep copies of those tables in a
database local to the service, and
have them act as slave tables.  The
master tables will be maintained by
an app that manages that data and
pushes out updates to those slave
tables.

Am I missing any good options?  Out of those 2 or any other proposed, which would you go with and why?

答:
Replication and data caching is one of those things that is really interesting to talk about but rarely the right choice. Databases are designed to deal with shared data and most are quite good at it. You should only keep multiple copies of the data if it addresses a specific requirement such as:

Service instances deployed to multiple locations with poor or unreliable connectivity between the sites.

Performance under very high loads (this can usually be addressed by simply buying the right hardware).

If you don’t have a special requirement, listen to Kdansky. Keep it simple. Spend as much of your development time providing your users with features... not writing data integrity monitors.

ContentLicense: CC BY-SA 2.5


答:
Since a is Dataframe and not a Series, if you try to do indexing, you will get NaNs.

Consider this Series

```<code>s = pd.Series(np.random.randint(0,10, 20), index = pd.date_range(start = '01/01/2017', periods = 20))
</code>```

If you slice it, zeros are dropped

```<code>s[s!=0]
</code>```

But for the dataframe, the same code will introduce the NaNs.

```<code>df = pd.DataFrame(np.random.randint(0,10, 20), index = pd.date_range(start = '01/01/2017', periods = 20))
</code>```

You can handle this by specifying the column name while indexing

```<code>df[df[0] != 0] #df[0] being the column
</code>```

Title: median of a rolling window, excluding zeros

Body:
when i try to find the rolling median of the following series, i get a list of NaNs.

I used:

b = a[a!=0].rolling(100).median()

a = actual data series (dataframe).  Has a bunch of zeros in it that i want to exclude when finding the median

b = rolling median

a[a!=0] gives me the following series.

2017-10-05       NaN
2017-10-06 -0.001074
2017-10-09 -0.001804
2017-10-10       NaN
2017-10-11       NaN
2017-10-12 -0.001687
2017-10-13       NaN
2017-10-16       NaN
2017-10-17       NaN
2017-10-18       NaN
2017-10-19       NaN
2017-10-20       NaN
2017-10-23 -0.003972
2017-10-24       NaN
2017-10-25 -0.004663
2017-10-26       NaN
2017-10-27       NaN
2017-10-30 -0.003192
2017-10-31       NaN
2017-11-01       NaN
2017-11-02       NaN
2017-11-03       NaN
t2017-11-06       NaN
2017-11-07 -0.000189
2017-11-08       NaN
2017-11-09 -0.003762
2017-11-10 -0.000898
2017-11-13       NaN
2017-11-14 -0.002310

the output is just a list of NaNs.

what am i doing wrong?
thank you!

Body:
Since a is Dataframe and not a Series, if you try to do indexing, you will get NaNs.

Consider this Series

s = pd.Series(np.random.randint(0,10, 20), index = pd.date_range(start = '01/01/2017', periods = 20))

If you slice it, zeros are dropped

s[s!=0]

But for the dataframe, the same code will introduce the NaNs.

df = pd.DataFrame(np.random.randint(0,10, 20), index = pd.date_range(start = '01/01/2017', periods = 20))

You can handle this by specifying the column name while indexing

df[df[0] != 0] #df[0] being the column


问:
How do I reference an object if it is only declared inside of an if statement?
I am trying to call an object, yet I can't because I am using an if statement to declare the object. Help?

I am trying to make two robots fight, and it was easiest for me to display the robots using objects and a toString() method. After doing this though, it was difficult to make the two robots fight because I couldn't determine which robots I was using, the only way I could figure out was to make two new robot objects but in order to determine the correct robot stats, I needed to use a new object.

Here is my code:

```<code>import javax.swing.JOptionPane;

public class RobotDriver
{                                              //armor health regen damage critical missile

public static void main(String[] args)
{
Robot Annihilator = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20,    .5);
Robot Gladiator = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
Robot Deadshot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
Robot Tank = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);

String robot1 = "";
String robot2 = "";

String Robot1 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose First Robot: ");

String Robot2 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose Second Robot: ");

System.out.println("Robot #1: " + Robot1 + "\n\nRobot #2: " + Robot2);

if(Robot1.equals(Annihilator.getName()))
{
Robot firstRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot1.equals(Gladiator.getName()))
{
Robot firstRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot1.equals(Deadshot.getName()))
{
Robot firstRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot1.equals(Tank.getName()))
{
Robot firstRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}

if(Robot2.equals(Annihilator.getName()))
{
Robot secondRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot2.equals(Gladiator.getName()))
{
Robot secondRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot2.equals(Deadshot.getName()))
{
Robot secondRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot2.equals(Tank.getName()))
{
Robot secondRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}

boolean fight = true;

while(fight)
{
   //this is where the error occurs because the objects aren't declared
   fight(firstRobot, secondRobot);

}
</code>```

答:
Declare the variables outside the conditional statements, then update the value in the conditional statements

```<code>import javax.swing.JOptionPane;

public class RobotDriver
{                                              //armor health regen damage critical missile

public static void main(String[] args)
{
Robot Annihilator = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20,    .5);
Robot Gladiator = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
Robot Deadshot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
Robot Tank = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);

String robot1 = "";
String robot2 = "";

String Robot1 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose First Robot: ");

String Robot2 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose Second Robot: ");

System.out.println("Robot #1: " + Robot1 + "\n\nRobot #2: " + Robot2);

firstRobot = new Robot()
if(Robot1.equals(Annihilator.getName()))
{
firstRobot.setRobot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot1.equals(Gladiator.getName()))
{
firstRobot.setRobot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot1.equals(Deadshot.getName()))
{
firstRobot.setRobot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot1.equals(Tank.getName()))
{
firstRobot.setRobot("Tank", 45, 1300, 0, 24.9, .2, 0);
}
</code>```

Have a setRobot method in the Robot class

Body:
I am trying to call an object, yet I can't because I am using an if statement to declare the object. Help?

I am trying to make two robots fight, and it was easiest for me to display the robots using objects and a toString() method. After doing this though, it was difficult to make the two robots fight because I couldn't determine which robots I was using, the only way I could figure out was to make two new robot objects but in order to determine the correct robot stats, I needed to use a new object.

Here is my code:

import javax.swing.JOptionPane;

public class RobotDriver
{                                              //armor health regen damage critical missile

public static void main(String[] args)
{
Robot Annihilator = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20,    .5);
Robot Gladiator = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
Robot Deadshot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
Robot Tank = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);

String robot1 = "";
String robot2 = "";

String Robot1 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose First Robot: ");

String Robot2 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose Second Robot: ");

System.out.println("Robot #1: " + Robot1 + "\n\nRobot #2: " + Robot2);

if(Robot1.equals(Annihilator.getName()))
{
Robot firstRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot1.equals(Gladiator.getName()))
{
Robot firstRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot1.equals(Deadshot.getName()))
{
Robot firstRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot1.equals(Tank.getName()))
{
Robot firstRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}

if(Robot2.equals(Annihilator.getName()))
{
Robot secondRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot2.equals(Gladiator.getName()))
{
Robot secondRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot2.equals(Deadshot.getName()))
{
Robot secondRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot2.equals(Tank.getName()))
{
Robot secondRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}

boolean fight = true;

while(fight)
{
   //this is where the error occurs because the objects aren't declared
   fight(firstRobot, secondRobot);

}

Body:
Declare the variables outside the conditional statements, then update the value in the conditional statements

import javax.swing.JOptionPane;

public class RobotDriver
{                                              //armor health regen damage critical missile

public static void main(String[] args)
{
Robot Annihilator = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20,    .5);
Robot Gladiator = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
Robot Deadshot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
Robot Tank = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);

String robot1 = "";
String robot2 = "";

String Robot1 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose First Robot: ");

String Robot2 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose Second Robot: ");

System.out.println("Robot #1: " + Robot1 + "\n\nRobot #2: " + Robot2);

firstRobot = new Robot()
if(Robot1.equals(Annihilator.getName()))
{
firstRobot.setRobot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot1.equals(Gladiator.getName()))
{
firstRobot.setRobot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot1.equals(Deadshot.getName()))
{
firstRobot.setRobot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot1.equals(Tank.getName()))
{
firstRobot.setRobot("Tank", 45, 1300, 0, 24.9, .2, 0);
}

Have a setRobot method in the Robot class


问:
What's wrong if compiler optimization is turned on in debug build?
Why is it necessary/recommended to turn off all compiler optimizations when debugging application?

Background

I'm working in an 8-bit micro controller (OKI 411) which has 15K usable code memory space for interrupt service routines + ROM region/window (const global variables) + code. We nearly eat up ~13K so it is very tempting to turn on maximum possible optimization during even debugging.

答:
It's fine to turn it on.  It's usually off because it makes compiles go faster, which for large projects can be a real concern.  It's actually better to turn it on if you can, so that you don't run into any nasty problems due to the optimization at the last minute.

In your case I'd certainly turn it on.

This may cause problems with certain forms of debugging, but you should be able to flip it off in those cases.


问:
Correctly loading a model to resume training (meta graph, ckpts)
I'm having trouble loading a model to resume training.
I'm using a simple two-layered-NN (Fully connected) on a cifar data set for practice.

NN Setup:

```<code>#full_connected_layers

import tensorflow as tf
import numpy as np

#input _-> hidden ->

def inference(data_samples, image_pixels, hidden_units, classes, reg_constant):

        with tf.variable_scope('Layer1'):
        # Define the variables
                weights = tf.get_variable(
                  name='weights',
                  shape=[image_pixels, hidden_units],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(image_pixels))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant)
                )

                biases = tf.Variable(tf.zeros([hidden_units]), name='biases')

                # Define the layer's output
                hidden = tf.nn.relu(tf.matmul(data_samples, weights) + biases)

        with tf.variable_scope('Layer2'):
        # Define variables
                weights = tf.get_variable('weights', [hidden_units, classes],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(hidden_units))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant))

                biases = tf.Variable(tf.zeros([classes]), name='biases')

        # Define the layer's output
                logits = tf.matmul(hidden, weights) + biases

        # Define summery-operation for 'logits'-variable
        tf.summary.histogram('logits', logits)

        return logits

def loss(logits, labels):
  '''Calculates the loss from logits and labels.

  Args:
    logits: Logits tensor, float - [batch size, number of classes].
    labels: Labels tensor, int64 - [batch size].

  Returns:
    loss: Loss tensor of type float.
  '''

  with tf.name_scope('Loss'):
    # Operation to determine the cross entropy between logits and labels
    cross_entropy = tf.reduce_mean(
      tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=labels, name='cross_entropy'))

    # Operation for the loss function
    loss = cross_entropy + tf.add_n(tf.get_collection(
      tf.GraphKeys.REGULARIZATION_LOSSES))

    # Add a scalar summary for the loss
    tf.summary.scalar('loss', loss)

  return loss

def training(loss, learning_rate):

  # Create a variable to track the global step
  global_step = tf.Variable(0, name='global_step', trainable=False)

  train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss, global_step=global_step)

  #train_step = tf.train.AdamOptimizer(learning_rate, beta1, beta2, epsilon).minimize(
    #loss, global_step=global_step)

  return train_step

def evaluation(logits, labels):

  with tf.name_scope('Accuracy'):
    # Operation comparing prediction with true label
    correct_prediction = tf.equal(tf.argmax(logits,1), labels)

    # Operation calculating the accuracy of the predictions
    accuracy =  tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # Summary operation for the accuracy
    tf.summary.scalar('train_accuracy', accuracy)

  return accuracy
</code>```

Saved model like this:

```<code>if (i + 1) % 500 == 0:
      saver.save(sess, MODEL_DIR, global_step=i)
      print('Saved checkpoint')
</code>```

Saved model files

Within this directory:
C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes

I have the following files as well as model.ckpt-499.index etc:

```<code>model.ckpt-999.meta
model.ckpt-999.index
model.ckpt-999.data-00000-of-00001
</code>```

My attempt at loading the model

```<code>import numpy as np
import tensorflow as tf
import time
from datetime import datetime
import os
import data_helpers
import full_connected_layers
import itertools

learning_rate = .0001
max_steps = 3000
batch_size = 400

checkpoint = r'C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes\model.ckpt-999'

with tf.Session() as sess:
    saver = tf.train.import_meta_graph(r'C:\Users\Moondra\Desktop\CIFAR - PROJECT' +
                                    '\\parameters_no_changes\model.ckpt-999.meta')
    saver.restore(sess, checkpoint)

data_sets = data_helpers.load_data()

images = tf.get_default_graph().get_tensor_by_name('images:0') #image placeholder
labels = tf.get_default_graph().get_tensor_by_name('image-labels:0') #placeholder
loss = tf.get_default_graph().get_tensor_by_name('Loss/add:0')
#global_step = tf.get_default_graph().get_tensor_by_name('global_step/initial_value_1:0')

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss)

accuracy = tf.get_default_graph().get_tensor_by_name('Accuracy/Mean:0')

with tf.Session() as sess:

  #sess.run(tf.global_variables_initializer())
  zipped_data = zip(data_sets['images_train'], data_sets['labels_train'])
  batches = data_helpers.gen_batch(list(zipped_data), batch_size,
    max_steps)

  for i in range(max_steps):

    # Get next input data batch
    batch = next(batches)
    images_batch, labels_batch = zip(*batch)
    feed_dict = {
      images: images_batch,
      labels: labels_batch

       }

    if i % 100 == 0:
      train_accuracy = sess.run(accuracy, feed_dict=feed_dict)
      print('Step {:d}, training accuracy {:g}'.format(i, train_accuracy))

    ts,loss_  =sess.run([train_step, loss], feed_dict=feed_dict)
</code>```

Errors and confusion

1) Should I be using this command latest_checkpoint to restore:
`

```<code>saver.restore(sess,tf.train.latest_checkpoint('./'))`
</code>```

I see some tutorials that just point to the folder holding the
.data, .index files.

2) Which brings me to the second question:  What should I be using as the second parameter of saver.restore.
Currently I'm just pointing to the folder/dir that holds those files

3) I'm not purposely initializing any variables as I was told, that would overwrite the stored weight and bias values. This seems to be leading to this error:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Layer1/weights
     [[Node: Layer1/weights/read = Identity[T=DT_FLOAT, _class=["loc:@Layer1/weights"], _device="/job:localhost/replica:0/task:0/cpu:0"](Layer1/weights)]]

4) However, If I do initialize all variables via this code:

sess.run(tf.global_variables_initializer())

My model seems to start training from scratch (and not resuming training)

Does that mean I'm supposed to load all weights and biases via
get_tensor explicitly? If so , how I deal with layers with 20 plus layers?

5) When I run this command

```<code>for i in tf.get_default_graph().get_operations():
    print(i.values)
</code>```

I see many global_steps tensors/operations,

```<code>'global_step/initial_value' type=Const>>
'global_step' type=VariableV2>>
<'global_step/Assign' type=Assign>>

global_step/read' type=Identity>>
</code>```

I was trying to load this variable into my current graph, but
didn't know which one I'm supposed to get using the command
get_tensor_by_name. Most of them were resulting in a does not exist error.

6) Same with loss which loss am I supposed to load into my graph with get_tensor

These are the options:

```<code><bound method Operation.values of <tf.Operation 'Loss/Const' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/Mean' type=Mean>>
<bound method Operation.values of <tf.Operation 'Loss/AddN' type=AddN>>
<bound method Operation.values of <tf.Operation 'Loss/add' type=Add>>
<bound method Operation.values of <tf.Operation 'Loss/loss/tags' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/loss' type=ScalarSummary>>
</code>```

6) Lastly, I see a lot of gradient operations when I look at all
the nodes of the graph but I don't see any nodes related to train_step (the
python variable I created that points to the Gradient Dsecent Optimizer). Does that mean I don't need to load it into this graph via get_tensor?

Thank  you.

答:
1/ In the folder where you save your checkpoint, there should be a file named 'checkpoint' which contains the name of your latest checkpoint.

I normally read this file to find latest checkpoint.

2/ I use checkpoint_directory/global_step.

With this, tf will create 4 files in the checkpoint_directory:

global_step.data-00000-of-00001

  global_step.index

  global_step.meta

  checkpoint

3/ 4/ I'm pretty sure you don't need to pre-initialize the graph before loading, at least I don't do it.

There is some difference: instead of import_meta_graph, I rebuild the whole graph every time I load, but I'm sure it's not an issue to load before you initialize.

5/ Be careful not to mis-take operations for tensors and you are good to go. Tensor name should be op_name:0, which mean this tensor is the output[0] of the operation op_name.

6/ 7/ Well, let me just tell you how I resume my checkpoint. This is probably not the correct way, but it really saves me from the burden of get_tensor_by_name. Seriously get_tensor_by_name can be a real pita sometimes.

Normally my loading process will go through: rebuild graph, load checkpoint, create some new tensors if needed, initialize tensors that is not in the checkpoint.

build_net()

  saver = tf.train.Saver()

  saver.restore(session, checkpoint_dir/global_step)

  add_loss_and_optimizer()

  initialize_all_uninitialized_tensor

checkpoint_dir/global_step is from the checkpoint file if you want the latest checkpoint, or you can use different global_step to get the specific checkpoint that you wanna load.

Body:
I'm having trouble loading a model to resume training.
I'm using a simple two-layered-NN (Fully connected) on a cifar data set for practice.

NN Setup:

#full_connected_layers

import tensorflow as tf
import numpy as np

#input _-> hidden ->

def inference(data_samples, image_pixels, hidden_units, classes, reg_constant):

        with tf.variable_scope('Layer1'):
        # Define the variables
                weights = tf.get_variable(
                  name='weights',
                  shape=[image_pixels, hidden_units],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(image_pixels))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant)
                )

                biases = tf.Variable(tf.zeros([hidden_units]), name='biases')

                # Define the layer's output
                hidden = tf.nn.relu(tf.matmul(data_samples, weights) + biases)

        with tf.variable_scope('Layer2'):
        # Define variables
                weights = tf.get_variable('weights', [hidden_units, classes],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(hidden_units))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant))

                biases = tf.Variable(tf.zeros([classes]), name='biases')

        # Define the layer's output
                logits = tf.matmul(hidden, weights) + biases

        # Define summery-operation for 'logits'-variable
        tf.summary.histogram('logits', logits)

        return logits

def loss(logits, labels):
  '''Calculates the loss from logits and labels.

  Args:
    logits: Logits tensor, float - [batch size, number of classes].
    labels: Labels tensor, int64 - [batch size].

  Returns:
    loss: Loss tensor of type float.
  '''

  with tf.name_scope('Loss'):
    # Operation to determine the cross entropy between logits and labels
    cross_entropy = tf.reduce_mean(
      tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=labels, name='cross_entropy'))

    # Operation for the loss function
    loss = cross_entropy + tf.add_n(tf.get_collection(
      tf.GraphKeys.REGULARIZATION_LOSSES))

    # Add a scalar summary for the loss
    tf.summary.scalar('loss', loss)

  return loss

def training(loss, learning_rate):

  # Create a variable to track the global step
  global_step = tf.Variable(0, name='global_step', trainable=False)

  train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss, global_step=global_step)

  #train_step = tf.train.AdamOptimizer(learning_rate, beta1, beta2, epsilon).minimize(
    #loss, global_step=global_step)

  return train_step

def evaluation(logits, labels):

  with tf.name_scope('Accuracy'):
    # Operation comparing prediction with true label
    correct_prediction = tf.equal(tf.argmax(logits,1), labels)

    # Operation calculating the accuracy of the predictions
    accuracy =  tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # Summary operation for the accuracy
    tf.summary.scalar('train_accuracy', accuracy)

  return accuracy

Saved model like this:

if (i + 1) % 500 == 0:
      saver.save(sess, MODEL_DIR, global_step=i)
      print('Saved checkpoint')

Saved model files

Within this directory:
C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes

I have the following files as well as model.ckpt-499.index etc:

model.ckpt-999.meta
model.ckpt-999.index
model.ckpt-999.data-00000-of-00001

My attempt at loading the model

import numpy as np
import tensorflow as tf
import time
from datetime import datetime
import os
import data_helpers
import full_connected_layers
import itertools

learning_rate = .0001
max_steps = 3000
batch_size = 400

checkpoint = r'C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes\model.ckpt-999'

with tf.Session() as sess:
    saver = tf.train.import_meta_graph(r'C:\Users\Moondra\Desktop\CIFAR - PROJECT' +
                                    '\\parameters_no_changes\model.ckpt-999.meta')
    saver.restore(sess, checkpoint)

data_sets = data_helpers.load_data()

images = tf.get_default_graph().get_tensor_by_name('images:0') #image placeholder
labels = tf.get_default_graph().get_tensor_by_name('image-labels:0') #placeholder
loss = tf.get_default_graph().get_tensor_by_name('Loss/add:0')
#global_step = tf.get_default_graph().get_tensor_by_name('global_step/initial_value_1:0')

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss)

accuracy = tf.get_default_graph().get_tensor_by_name('Accuracy/Mean:0')

with tf.Session() as sess:

  #sess.run(tf.global_variables_initializer())
  zipped_data = zip(data_sets['images_train'], data_sets['labels_train'])
  batches = data_helpers.gen_batch(list(zipped_data), batch_size,
    max_steps)

  for i in range(max_steps):

    # Get next input data batch
    batch = next(batches)
    images_batch, labels_batch = zip(*batch)
    feed_dict = {
      images: images_batch,
      labels: labels_batch

       }

    if i % 100 == 0:
      train_accuracy = sess.run(accuracy, feed_dict=feed_dict)
      print('Step {:d}, training accuracy {:g}'.format(i, train_accuracy))

    ts,loss_  =sess.run([train_step, loss], feed_dict=feed_dict)

Errors and confusion

1) Should I be using this command latest_checkpoint to restore:
`

saver.restore(sess,tf.train.latest_checkpoint('./'))`

I see some tutorials that just point to the folder holding the
.data, .index files.

2) Which brings me to the second question:  What should I be using as the second parameter of saver.restore.
Currently I'm just pointing to the folder/dir that holds those files

3) I'm not purposely initializing any variables as I was told, that would overwrite the stored weight and bias values. This seems to be leading to this error:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Layer1/weights
     [[Node: Layer1/weights/read = Identity[T=DT_FLOAT, _class=["loc:@Layer1/weights"], _device="/job:localhost/replica:0/task:0/cpu:0"](Layer1/weights)]]

4) However, If I do initialize all variables via this code:

sess.run(tf.global_variables_initializer())

My model seems to start training from scratch (and not resuming training)

Does that mean I'm supposed to load all weights and biases via
get_tensor explicitly? If so , how I deal with layers with 20 plus layers?

5) When I run this command

for i in tf.get_default_graph().get_operations():
    print(i.values)

I see many global_steps tensors/operations,

'global_step/initial_value' type=Const>>
'global_step' type=VariableV2>>
<'global_step/Assign' type=Assign>>

global_step/read' type=Identity>>

I was trying to load this variable into my current graph, but
didn't know which one I'm supposed to get using the command
get_tensor_by_name. Most of them were resulting in a does not exist error.

6) Same with loss which loss am I supposed to load into my graph with get_tensor

These are the options:

<bound method Operation.values of <tf.Operation 'Loss/Const' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/Mean' type=Mean>>
<bound method Operation.values of <tf.Operation 'Loss/AddN' type=AddN>>
<bound method Operation.values of <tf.Operation 'Loss/add' type=Add>>
<bound method Operation.values of <tf.Operation 'Loss/loss/tags' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/loss' type=ScalarSummary>>

6) Lastly, I see a lot of gradient operations when I look at all
the nodes of the graph but I don't see any nodes related to train_step (the
python variable I created that points to the Gradient Dsecent Optimizer). Does that mean I don't need to load it into this graph via get_tensor?

Thank  you.


问:
Find Maximum Strength given number of elements to be skipped on left and right.Please Tell me why my code gives wrong output for certain test cases?
Given an array "s" of "n" items, you have for each item an left value "L[i]" and right value "R[i]" and its strength "S[i]",if you pick an element you can not pick L[i] elements on immediate left of it and R[i] on immediate right of it, find the maximum strength possible.

Example input:

```<code>5            //n
1 3 7 3 7    //strength
0 0 2 2 2    //Left Value
3 0 1 0 0    //Right Value
</code>```

Output:

```<code>10
</code>```

Code:

```<code>#include < bits / stdc++.h >
using namespace std;

unsigned long int getMax(int n, int * s, int * l, int * r) {

    unsigned long int dyn[n + 1] = {};
    dyn[1] = s[1];
    for (int i = 2; i <= n; i++) {
        dyn[i] = dyn[i - 1];
        unsigned long int onInc = s[i];
        int left = i - l[i] - 1;

        if (left >= 1) {
            unsigned int k = left;
            while ((k > 0) && ((r[k] + k) >= i)) {
                k--;
            }
            if (k != 0) {
                if ((dyn[k] + s[i]) > dyn[i]) {
                    onInc = dyn[k] + s[i];
                }
            }
        }

        dyn[i] = (dyn[i] > onInc) ? dyn[i] : onInc;
    }
    return dyn[n];
}

int main() {

    int n;
    cin >> n;
    int s[n + 1] = {}, l[n + 1] = {}, r[n + 1] = {};
    for (int i = 1; i <= n; i++) {
        cin >> s[i];
    }
    for (int i = 1; i <= n; i++) {
        cin >> l[i];
    }
    for (int i = 1; i <= n; i++) {
        cin >> r[i];
    }

    cout << getMax(n, s, l, r) << endl;

    return 0;
}
</code>```

答:
Problem in your approach:

In your DP table, the information you are storing is about maximum possible so far. The information regarding whether the ith index has been considered is lost. You can consider taking strength at current index to extend previous indices only if any of the previously seen indices is either not in range or it is in range and has not been considered.

Solution:

Reconfigure your DP recurrence. Let DP[i] denote the maximum answer if ith index was considered. Now you will only need to extend those that satisfy range condition. The answer would be maximum value of all DP indices.

Code:

```<code>vector<long> DP(n,0);

DP[0]=strength[0]; // base condition

    for(int i = 1; i < n ; i++){

        DP[i] = strength[i];

        for(int j = 0; j < i ; j++){

            if(j >= (i-l[i]) || i <= (j+r[j])){ // can't extend

            }
            else{

                DP[i]=max(DP[i],strength[i]+DP[j]); // extend to maximize result

            }
        }
    }

long ans=*max_element(DP.begin(),DP.end());
</code>```

Time Complexity: O(n^2)

Possible Optimizations:

There are better ways to calculate maximum values which you might want to look into. You can start by looking into Segment tree and Binary Indexed Trees.

Body:
Given an array "s" of "n" items, you have for each item an left value "L[i]" and right value "R[i]" and its strength "S[i]",if you pick an element you can not pick L[i] elements on immediate left of it and R[i] on immediate right of it, find the maximum strength possible.

Example input:

5            //n
1 3 7 3 7    //strength
0 0 2 2 2    //Left Value
3 0 1 0 0    //Right Value

Output:

10

Code:

#include < bits / stdc++.h >
using namespace std;

unsigned long int getMax(int n, int * s, int * l, int * r) {

    unsigned long int dyn[n + 1] = {};
    dyn[1] = s[1];
    for (int i = 2; i <= n; i++) {
        dyn[i] = dyn[i - 1];
        unsigned long int onInc = s[i];
        int left = i - l[i] - 1;

        if (left >= 1) {
            unsigned int k = left;
            while ((k > 0) && ((r[k] + k) >= i)) {
                k--;
            }
            if (k != 0) {
                if ((dyn[k] + s[i]) > dyn[i]) {
                    onInc = dyn[k] + s[i];
                }
            }
        }

        dyn[i] = (dyn[i] > onInc) ? dyn[i] : onInc;
    }
    return dyn[n];
}

int main() {

    int n;
    cin >> n;
    int s[n + 1] = {}, l[n + 1] = {}, r[n + 1] = {};
    for (int i = 1; i <= n; i++) {
        cin >> s[i];
    }
    for (int i = 1; i <= n; i++) {
        cin >> l[i];
    }
    for (int i = 1; i <= n; i++) {
        cin >> r[i];
    }

    cout << getMax(n, s, l, r) << endl;

    return 0;
}

Body:
Problem in your approach:

In your DP table, the information you are storing is about maximum possible so far. The information regarding whether the ith index has been considered is lost. You can consider taking strength at current index to extend previous indices only if any of the previously seen indices is either not in range or it is in range and has not been considered.

Solution:

Reconfigure your DP recurrence. Let DP[i] denote the maximum answer if ith index was considered. Now you will only need to extend those that satisfy range condition. The answer would be maximum value of all DP indices.

Code:

vector<long> DP(n,0);

DP[0]=strength[0]; // base condition

    for(int i = 1; i < n ; i++){

        DP[i] = strength[i];

        for(int j = 0; j < i ; j++){

            if(j >= (i-l[i]) || i <= (j+r[j])){ // can't extend

            }
            else{

                DP[i]=max(DP[i],strength[i]+DP[j]); // extend to maximize result

            }
        }
    }

long ans=*max_element(DP.begin(),DP.end());

Time Complexity: O(n^2)

Possible Optimizations:

There are better ways to calculate maximum values which you might want to look into. You can start by looking into Segment tree and Binary Indexed Trees.


Title: Sorting a list of dates in ascending order, without concerning the other element

Body:
This is the list:

[['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]]

This has to be the output:

[['2017-11-09', 21], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]

How do I do this in Python?

Body:
Here,

>>> l
[['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37], ['2017-11-09', 100], ['2017-11-09', 1]]

Using sorted sorts string and not date and also considers all items of sublist

>>> sorted(l)
[['2017-11-09', 1], ['2017-11-09', 21], ['2017-11-09', 100], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]

But we need to consider only the first item(dateobject)

>>> sorted(l,key=lambda x:datetime.strptime(x[0],'%Y-%m-%d'))
[['2017-11-09', 21], ['2017-11-09', 100], ['2017-11-09', 1], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]

Or even simpler,

>>> from operator import itemgetter
>>> sorted(l,key=itemgetter(0))
[['2017-11-09', 21], ['2017-11-09', 100], ['2017-11-09', 1], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]


问:
MVC3 Plugin architecture recommendations
I am trying to find some more information on approaches to creating a plugin architecture.

I've seen some good articles on MEF and MVC2 and Phil Haack mentioned some new extensibilty hooks available in MVC3 (http://haacked.com/archive/2010/05/16/three-hidden-extensibility-gems-in-asp-net-4.aspx)

Has anyone seen some good references on creating a plugin architecture for a MVC3 project?

I'd prefer to use technologies specific to MVC3, not to just hack a MVC2 solution in to the MVC2 framework.

Any ideas and suggestions would be greatly appreciated!

答:
MVC 3 is the same basic architecture as MVC 2 and MVC 1 before it.  Each new version of MVC merely adds a few new features, or makes a slight change to previous component.

If you find a solution for an earlier version of MVC, it will likely work quite well in whatever the latest version happens to be at the time, or with very minor changes.


问:
get value of [object HTMLDivElement]
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

```<code>     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });
</code>```

getNext.php

```<code>    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "<div class='result'>".$row['word'] ."</div>";
    }
</code>```

On the index.php I can display $row['word'] one by one on submit with

```<code>    <div id='results'></div>
</code>```

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

```<code>    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);
</code>```

答:
I wirte a php test file of your case:

the html file:

```<code><html>
<head>
        <script src=".../jquery/jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
        <button onclick="a()" name="getdata">getdata</button>
        <div id="results"></div>
        <script type="text/javascript">
                function a(){
                        $.ajax({
                       type: "POST",
                       url: "getdata.php",
                       success: function(results){
                         $('#results').append(results);
                       }
                     });
                }
        </script>
</body>
</html>
</code>```

the getdata.php file:

```<code><?php
echo 1111;
</code>```

So ,I think you problem is at the data formate that your php file returned. You can just return json data, and make the html element in your html file.

Title: get value of [object HTMLDivElement]

Body:
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });

getNext.php

    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "
".$row['word'] ."
";
    }

On the index.php I can display $row['word'] one by one on submit with

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);

Body:
I wirte a php test file of your case:

the html file:

<html>
<head>
        <script src=".../jquery/jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
        <button onclick="a()" name="getdata">getdata</button>
        <div id="results"></div>
        <script type="text/javascript">
                function a(){
                        $.ajax({
                       type: "POST",
                       url: "getdata.php",
                       success: function(results){
                         $('#results').append(results);
                       }
                     });
                }
        </script>
</body>
</html>

the getdata.php file:

<?php
echo 1111;

So ,I think you problem is at the data formate that your php file returned. You can just return json data, and make the html element in your html file.


问:
Components going under the navbar
My container elements like paragraphs, header and buttons are going under my navbar. The navbar has the property of fixed-top. I have used previous suggestions from other stackoverflow posts like this (twitter bootstrap navbar fixed top overlapping site). But nothing seems to work for me.Here is my navbar code.

```<code><nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
        <div class="container">
            <a class="navbar-brand text-white" href="#"> Bacon Bacon</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarsExampleDefault">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active">
                        <a class="nav-link text-white" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">About Us</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Services</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Products</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Contact</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</code>```

My container code

```<code> <div class="container-fluid bg-overlay">
    <div class="row text-center">
        <h1>Loren Inpsum</h1>
        <h4>Loren Inpsum Loren Inpsum Loren Inpsum Loren Inpsum </h4>
        <button type="button" class="btn btn-primary btn-lg">Get Started</button>
    </div>
</div>
</code>```

My CSS

```<code> @media (max-width: 979px) {
            body {
              padding-top: 70px;
            }
}

          .navbar {
            margin-bottom:0px;
            background: #FFFFFF;
            border-color: #FFFFFF;
            padding-bottom:0px;
          }

          .bg-overlay {
            background: linear-gradient(rgba(0,0,0,.7), rgba(0,0,0,.7)), url("https://unsplash.imgix.net/photo-1416339442236-8ceb164046f8?q=75&fm=jpg&s=8eb83df8a744544977722717b1ea4d09");
            background-repeat: no-repeat;
            text-align:center;
            background-size: cover;
            background-position: center center;
            color: #fff;
            height: 450px;
            padding-top: 0px;
  }

            div.container-fluid bg-overlay{
              margin-bottom:30px;

            }
</code>```

答:
The only thing you need to addpadding-top outside of MQ.

body {
  padding-top: 60px;
}
 @media (max-width: 979px) {
            body {
              padding-top: 70px;
            }
}

          .navbar {
            margin-bottom:0px;
            background: #FFFFFF;
            border-color: #FFFFFF;
            padding-bottom:0px;
          }

          .bg-overlay {
            background: linear-gradient(rgba(0,0,0,.7), rgba(0,0,0,.7)), url("https://unsplash.imgix.net/photo-1416339442236-8ceb164046f8?q=75&fm=jpg&s=8eb83df8a744544977722717b1ea4d09");
            background-repeat: no-repeat;
            text-align:center;
            background-size: cover;
            background-position: center center;
            color: #fff;
            height: 450px;
            padding-top: 0px;
  }

            div.container-fluid bg-overlay{
              margin-bottom:30px;

            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
        <div class="container">
             Bacon Bacon
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarsExampleDefault">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active">
                        Home
                    </li>
                    <li class="nav-item">
                        About Us
                    </li>
                    <li class="nav-item">
                        Services
                    </li>
                    <li class="nav-item">
                        Products
                    </li>
                    <li class="nav-item">
                        Contact
                    </li>
                </ul>
            </div>
        </div>
    </nav>

 <div class="container-fluid bg-overlay">
    <div class="row text-center">
        <h1>Loren Inpsum</h1>
        <h4>Loren Inpsum Loren Inpsum Loren Inpsum Loren Inpsum </h4>
        <button type="button" class="btn btn-primary btn-lg">Get Started</button>
    </div>
</div></code>```

Title: Components going under the navbar

Body:
My container elements like paragraphs, header and buttons are going under my navbar. The navbar has the property of fixed-top. I have used previous suggestions from other stackoverflow posts like this (twitter bootstrap navbar fixed top overlapping site). But nothing seems to work for me.Here is my navbar code.

             Bacon Bacon
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        Home

                        About Us

                        Services

                        Products

                        Contact

My container code

Loren Inpsum

Loren Inpsum Loren Inpsum Loren Inpsum Loren Inpsum

        <button type="button" class="btn btn-primary btn-lg">Get Started</button>

My CSS

 @media (max-width: 979px) {
            body {
              padding-top: 70px;
            }
}

          .navbar {
            margin-bottom:0px;
            background: #FFFFFF;
            border-color: #FFFFFF;
            padding-bottom:0px;
          }

          .bg-overlay {
            background: linear-gradient(rgba(0,0,0,.7), rgba(0,0,0,.7)), url("https://unsplash.imgix.net/photo-1416339442236-8ceb164046f8?q=75&fm=jpg&s=8eb83df8a744544977722717b1ea4d09");
            background-repeat: no-repeat;
            text-align:center;
            background-size: cover;
            background-position: center center;
            color: #fff;
            height: 450px;
            padding-top: 0px;
  }

            div.container-fluid bg-overlay{
              margin-bottom:30px;

            }

Body:
The only thing you need to addpadding-top outside of MQ.

body {
  padding-top: 60px;
}
 @media (max-width: 979px) {
            body {
              padding-top: 70px;
            }
}

          .navbar {
            margin-bottom:0px;
            background: #FFFFFF;
            border-color: #FFFFFF;
            padding-bottom:0px;
          }

          .bg-overlay {
            background: linear-gradient(rgba(0,0,0,.7), rgba(0,0,0,.7)), url("https://unsplash.imgix.net/photo-1416339442236-8ceb164046f8?q=75&fm=jpg&s=8eb83df8a744544977722717b1ea4d09");
            background-repeat: no-repeat;
            text-align:center;
            background-size: cover;
            background-position: center center;
            color: #fff;
            height: 450px;
            padding-top: 0px;
  }

            div.container-fluid bg-overlay{
              margin-bottom:30px;

            }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
        <div class="container">
            <a class="navbar-brand text-white" href="#"> Bacon Bacon</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarsExampleDefault">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active">
                        <a class="nav-link text-white" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">About Us</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Services</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Products</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">Contact</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

 <div class="container-fluid bg-overlay">
    <div class="row text-center">
        <h1>Loren Inpsum</h1>
        <h4>Loren Inpsum Loren Inpsum Loren Inpsum Loren Inpsum </h4>
        <button type="button" class="btn btn-primary btn-lg">Get Started</button>
    </div>
</div>


问:
How do we make keyboard appear below textView in swift?
I have done keyboard appearing below textfield using

on View did Load adding a observer()

```<code>    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
</code>```

And then updating the frame

```<code>weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}
</code>```

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

答:
One of the easy and no code of line solution is to use the following pods in your app.

IQKeyboardManger

Later you need to just import that in App Delegate and add this two lines of code in didfinishLaunching method:

```<code>  IQKeyboardManager.sharedManager().enable = true
</code>```

Your problem will be solved for whole app.

For Swift 5:

```<code>IQKeyboardManager.shared.enable = true
</code>```

Body:
I have done keyboard appearing below textfield using

on View did Load adding a observer()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

And then updating the frame

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

Body:
One of the easy and no code of line solution is to use the following pods in your app.

IQKeyboardManger

Later you need to just import that in App Delegate and add this two lines of code in didfinishLaunching method:

  IQKeyboardManager.sharedManager().enable = true

Your problem will be solved for whole app.

For Swift 5:

IQKeyboardManager.shared.enable = true

ContentLicense: CC BY-SA 4.0


问:
How can I keep responsive image in container when resizing screen
I have an image inside a container, I have to use bottom in negative in order to keep the part of the image that I want, the problem is that when I resize the screen into a smaller one, the image just disappears, how can I fix this?

HTML:

```<code></section>
<section id="img">
   <div class="container-fluid">
   <div class="row content">
      <div id="imgcont">
        <img class="img-responsive" src="http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg" />
         <div id="header">
            <div class="title">
               <h1>Title in image centered</h1>
            </div>
         </div>
      </div>
   </div>
   <div class="row content text-center">
      <h1>More content, same section </h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.</p>
   </div>
</section>
</code>```

CSS:

```<code>#imgcont {
       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
          display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: -500px;
    }

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}
</code>```

Full code:

https://codepen.io/elunap/pen/Ebwwjv

Or is there another way around this? this is really bothering me, when I finnaly think I made it work, something new happens.

答:
You just need to comment below css from your code, for the responsive banner image.

#imgcont .img-responsive {
       display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: -500px;
    }```

Body:
I have an image inside a container, I have to use bottom in negative in order to keep the part of the image that I want, the problem is that when I resize the screen into a smaller one, the image just disappears, how can I fix this?

HTML:

Title in image centered

More content, same section

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.

CSS:

#imgcont {
       overflow: hidden;
       height: 400px;
       max-height: 400px;
       position: relative;
}

#imgcont .img-responsive {
          display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: -500px;
    }

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}

Full code:

https://codepen.io/elunap/pen/Ebwwjv

Or is there another way around this? this is really bothering me, when I finnaly think I made it work, something new happens.


问:
Android Studio: Google Maps Activity works on device from desktop but not from laptop
I have been working on a project with a Google Maps fragment on my desktop. When I run the app on my Google Pixel XL from my desktop, it works fine. However, I cloned the repository onto my laptop, and when I try to run the app on my phone from my laptop, the Google Maps fragment is just blank. I have downloaded the Google Play services SDK on both my desktop and laptop, and the API key is the same on both. Any suggestions?</p>

答:
You need to add your laptop SHA1 key to google developer account then download json file and put it inside app folder.

And if you change your device again you need to add another SHA1 of that device again. to google developer account.

Below is the link :-
https://console.cloud.google.com/apis/credentials


问:
Define callback functions to make values available outside function
Here is my current jQuery onclick function for making an AJAX request to an external API, then displaying the results in a div. How would I implement a callback function that would allow the response.vehicle values to be available to another function that populates a separate div onclick further down the page?

```<code>$("#get-rego").click(function(e) {
  e.preventDefault();

  ajaxLoader.style.display = "block";
  plate = document.getElementById("input_2_6").value;

  var requestData = $.post({
    url: "/wp-admin/admin-ajax.php",
    data: {
      "action": "get_vehicle",
      "plate": plate,
    },
    "dataType": "json"
  });

  requestData.done(function(obj) {
    var response = obj.idh;
    var vehicleMake,
        vehicleModel,
        vehicleYear,
        vehicleColour,
        vehicleSubModel,
        vehicleBodyStyle;

    ajaxLoader.style.display = "none";
    vehicleDetails.style.display = "block";
    vehicleMake = response.vehicle.make;
    vehicleModel = response.vehicle.model;
    vehicleYear = response.vehicle.year_of_manufacture;
    vehicleColour = response.vehicle.main_colour;
    vehicleSubModel = response.vehicle.submodel;
    vehicleBodyStyle = response.vehicle.body_style;

    vehicleDataSummaryOutput = "<div class=\"summary\">" +
      "<ul>" +
      "<li><span class=\"label\">Make:</span> " + vehicleMake + "</li>" +
      "<li><span class=\"label\">Model:</span> " + vehicleModel + "</li>" +
      "<li><span class=\"label\">Year:</span> " + vehicleYear + "</li>" +
      "<li><span class=\"label\">Colour:</span> " + vehicleColour + "</li>" +
      "<li><span class=\"label\">Submodel:</span> " + vehicleSubModel + "</li>" +
      "<li><span class=\"label\">Body Style:</span> " + vehicleBodyStyle + "</li>" +
      "</ul>" +
      "</div>";

    vehicleDataSummary.innerHTML = vehicleDataSummaryOutput;
  });

  requestData.fail(function( jqXHR, textStatus ) {
    alert( "Request failed: " + textStatus );
  });
});
</code>```

答:
You can use code below:</p>

```<code>$.ajax({
    url: '/wp-admin/admin-ajax.php',
    dataType: 'json',
    success: function (response) {
        // Parse responseText
        var obj = JSON.parse(response.responseText);

        // Pass object to function
        doSomeThing(obj.vehicle);
    }
});

function doSomeThing(vehicle)
{
 // Do some work ...
}
</code>```

Body:
Here is my current jQuery onclick function for making an AJAX request to an external API, then displaying the results in a div. How would I implement a callback function that would allow the response.vehicle values to be available to another function that populates a separate div onclick further down the page?

$("#get-rego").click(function(e) {
  e.preventDefault();

  ajaxLoader.style.display = "block";
  plate = document.getElementById("input_2_6").value;

  var requestData = $.post({
    url: "/wp-admin/admin-ajax.php",
    data: {
      "action": "get_vehicle",
      "plate": plate,
    },
    "dataType": "json"
  });

  requestData.done(function(obj) {
    var response = obj.idh;
    var vehicleMake,
        vehicleModel,
        vehicleYear,
        vehicleColour,
        vehicleSubModel,
        vehicleBodyStyle;

    ajaxLoader.style.display = "none";
    vehicleDetails.style.display = "block";
    vehicleMake = response.vehicle.make;
    vehicleModel = response.vehicle.model;
    vehicleYear = response.vehicle.year_of_manufacture;
    vehicleColour = response.vehicle.main_colour;
    vehicleSubModel = response.vehicle.submodel;
    vehicleBodyStyle = response.vehicle.body_style;

    vehicleDataSummaryOutput = "
" +
      "
" +
      "
Make: " + vehicleMake + "
" +
      "
Model: " + vehicleModel + "
" +
      "
Year: " + vehicleYear + "
" +
      "
Colour: " + vehicleColour + "
" +
      "
Submodel: " + vehicleSubModel + "
" +
      "
Body Style: " + vehicleBodyStyle + "
" +
      "
" +
      "
";

    vehicleDataSummary.innerHTML = vehicleDataSummaryOutput;
  });

  requestData.fail(function( jqXHR, textStatus ) {
    alert( "Request failed: " + textStatus );
  });
});

Body:
You can use code below:

$.ajax({
    url: '/wp-admin/admin-ajax.php',
    dataType: 'json',
    success: function (response) {
        // Parse responseText
        var obj = JSON.parse(response.responseText);

        // Pass object to function
        doSomeThing(obj.vehicle);
    }
});

function doSomeThing(vehicle)
{
 // Do some work ...
}


问:
Is the SQL Server IsShutdown property useful to determine whether a database is in a good state?
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

```<code>SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)
</code>```

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.

答:
IsShutDown, which is set if SQL Server is unable to open a database's files during startup

So this would be a good issue to know if you rebooted your server and somebody had moved your database files or they didn't open because of a disk I/O problem.

Body:
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.


问:
How to add a source code library to IntelliJ (For example from Github)?
I want to add this library from Github to a new Java project. https://github.com/jmdns/jmdns

I have searched and found only methods to add jars and not source code of libraries.

How do I add source code of libraries and import from them in my project in Intelli.

It'd be cool if the library above was specified as an example.

答:
I found an answer on my own using two other QnAs on SO.

1) First you need to create a separate project containing the source of the library and compile it as jar.

If it's from Github you can just select File-> New-> Project from version control-> Git and create a new project from the github source.

Then you need to compile it as jar or artifact in Intellij

Look at this question for that:

How to build jars from IntelliJ properly?

2) Then you need to open your project from which you want to import the jar or library and add it to the project and add it or register it as library.

Look here for that:
Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

After doing these two steps I was successfully able to import the library.