问:
Tomcat 9 manager console not working
I am facing issue with my Host Manager and Manager App. Currently i am not able to open my host-manager/html and manager/html. I am getting 403 error code with the status Forbidden. I google also but came with the same solution that is modification of the tomcat user but still the issue persists.I have done the same thing in my past with tomcat 6 which worked fine for me. Please let me know is anything more need to be done to fix this issue.

I have updated my tomcat-users file but still getting the same error.My tomcat user file is below.

```<code><?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jax"/>
  <role rolename="manager-status"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
</tomcat-users>
</code>```

I have checked the tomcat logs nothing is there. Can anything please explain what needs to done for the same

```<code><?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jax"/>
  <role rolename="manager-status"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
</tomcat-users>
</code>```

答:
If you wan to login to the host manager, you should add "admin-gui" role:

```<code><role rolename="admin-gui"/>
</code>```

And by default the Manager is only accessible from a browser running on the same machine as Tomcat. If you wish to modify this restriction, you'll need to edit the Manager's context.xml file.

webapps/manager/META-INF/context.xml

webapps/host-manager/META-INF/context.xml

Tomcat guide says:

In addition to the password restrictions, access to the Manager web application can be restricted by the remote IP address or host by adding a RemoteAddrValve or RemoteHostValve. See valves documentation for details. Here is an example of restricting access to the localhost by IP address:

```<code><Context privileged="true">
     <Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.0\.0\.1"/>
</Context>
</code>```

Title: Tomcat 9 manager console not working

Body:
I am facing issue with my Host Manager and Manager App. Currently i am not able to open my host-manager/html and manager/html. I am getting 403 error code with the status Forbidden. I google also but came with the same solution that is modification of the tomcat user but still the issue persists.I have done the same thing in my past with tomcat 6 which worked fine for me. Please let me know is anything more need to be done to fix this issue.

I have updated my tomcat-users file but still getting the same error.My tomcat user file is below.

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jax"/>
  <role rolename="manager-status"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
</tomcat-users>

I have checked the tomcat logs nothing is there. Can anything please explain what needs to done for the same

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jax"/>
  <role rolename="manager-status"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
</tomcat-users>

Body:
If you wan to login to the host manager, you should add "admin-gui" role:

<role rolename="admin-gui"/>

And by default the Manager is only accessible from a browser running on the same machine as Tomcat. If you wish to modify this restriction, you'll need to edit the Manager's context.xml file.

webapps/manager/META-INF/context.xml

webapps/host-manager/META-INF/context.xml

Tomcat guide says:

In addition to the password restrictions, access to the Manager web application can be restricted by the remote IP address or host by adding a RemoteAddrValve or RemoteHostValve. See valves documentation for details. Here is an example of restricting access to the localhost by IP address:

<Context privileged="true">
     <Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.0\.0\.1"/>
</Context>


来源: stackexchange

问:
Table view is not displaying the comments or username from Firebase
Here's the code I use to fetch the comments and username of users from firebase to display in my tableview cell for comments. It currently does not display anything but when I post comments it goes through and I can see it on the firebase database. I just need to read all the comment datas and display it.</p>

```<code>func fetchComment()
{
    let ref = FIRDatabase.database().reference().child("Newsfeed").child(itemSelected.title)

    ref.observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.hasChild("comments")
        {
            ref.child("comments").observeSingleEvent(of: .value, with: {snappy in
                for comPosted in snappy.children.allObjects as! [FIRDataSnapshot]
                {
                    let commentPosted = comment()

                    guard let comDict = comPosted.value as? [String: AnyObject]

                    else
                    {
                        continue
                    }

                    commentPosted.commentText = comDict["userComment"] as! String!
                    commentPosted.username = comDict["userId"] as! String!

                    self.comments.append(commentPosted)
                }
            })
        }
    })

    self.commentTableView.reloadData()
    ref.removeAllObservers()
}
</code>```

答:
Firebase  is asynchronous and therefore the code needs to allow Firebase time to return the data from the server. That data is only valid inside the closure and any code outside the closure will execute before the code inside. Code is much faster than the internet!

So moving the tableView.reloadData right after the for loop will ensure it executes after the dataSource array is populated.

Also, the two observe events in the code are Single events - meaning they don't stay attached to the node so the removeAllObservers is extraneous.

```<code>    let ref = FIRDatabase.database().reference().child("Newsfeed")
                         .child(itemSelected.title)

    ref.observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.hasChild("comments")
        {
            ref.child("comments").observeSingleEvent(of: .value, with: {snappy in
                for comPosted in snappy.children.allObjects as! [FIRDataSnapshot]
                {
                    let commentPosted = comment()
                    let comDict = comPosted.value as! [String: AnyObject]
                    commentPosted.commentText = comDict["userComment"] as! String!
                    commentPosted.username = comDict["userId"] as! String!
                    self.comments.append(commentPosted)
                }
                self.commentTableView.reloadData()

                //A quick check to ensure the array is populated.
                //Can be removed.
                for c in self.comments {
                    print(c.commentText)
                    print(c.username)
                }
            })
        }
    })
</code>```

The above code is tested and works so if the tableview is still not displaying the data, there may be an issue in the tableView delegate functions.

ContentLicense: CC BY-SA 3.0

Body:
Here's the code I use to fetch the comments and username of users from firebase to display in my tableview cell for comments. It currently does not display anything but when I post comments it goes through and I can see it on the firebase database. I just need to read all the comment datas and display it.

func fetchComment()
{
    let ref = FIRDatabase.database().reference().child("Newsfeed").child(itemSelected.title)

    ref.observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.hasChild("comments")
        {
            ref.child("comments").observeSingleEvent(of: .value, with: {snappy in
                for comPosted in snappy.children.allObjects as! [FIRDataSnapshot]
                {
                    let commentPosted = comment()

                    guard let comDict = comPosted.value as? [String: AnyObject]

                    else
                    {
                        continue
                    }

                    commentPosted.commentText = comDict["userComment"] as! String!
                    commentPosted.username = comDict["userId"] as! String!

                    self.comments.append(commentPosted)
                }
            })
        }
    })

    self.commentTableView.reloadData()
    ref.removeAllObservers()
}

Body:
Firebase  is asynchronous and therefore the code needs to allow Firebase time to return the data from the server. That data is only valid inside the closure and any code outside the closure will execute before the code inside. Code is much faster than the internet!

So moving the tableView.reloadData right after the for loop will ensure it executes after the dataSource array is populated.

Also, the two observe events in the code are Single events - meaning they don't stay attached to the node so the removeAllObservers is extraneous.

    let ref = FIRDatabase.database().reference().child("Newsfeed")
                         .child(itemSelected.title)

    ref.observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.hasChild("comments")
        {
            ref.child("comments").observeSingleEvent(of: .value, with: {snappy in
                for comPosted in snappy.children.allObjects as! [FIRDataSnapshot]
                {
                    let commentPosted = comment()
                    let comDict = comPosted.value as! [String: AnyObject]
                    commentPosted.commentText = comDict["userComment"] as! String!
                    commentPosted.username = comDict["userId"] as! String!
                    self.comments.append(commentPosted)
                }
                self.commentTableView.reloadData()

                //A quick check to ensure the array is populated.
                //Can be removed.
                for c in self.comments {
                    print(c.commentText)
                    print(c.username)
                }
            })
        }
    })

The above code is tested and works so if the tableview is still not displaying the data, there may be an issue in the tableView delegate functions.


问:
instance Of Operator in java
```<code>class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}
</code>```

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

答:
You can use this :

```<code>System.out.println(a.getClass().equals(B.class));
</code>```

Instead of :

```<code>System.out.println(a instanceof B);
</code>```

Title: instance Of Operator in java

Body:
class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

Body:
You can use this :

System.out.println(a.getClass().equals(B.class));

Instead of :

System.out.println(a instanceof B);


问:
Main column not rendering even with side column
I have a two column layout the main content area renders down the page. Not even with aside. I wonder if I need a wrapper div?
or maybe my CSS not right?
I did not post of the CSS just what Thought maybe important

@charset "utf-8";
body {
 font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
 background: #FFF;
    background-image:url(../assets/bg1.png);
 margin: 0;
 padding: 0;
 color: #000;
}
.sidebar h4 {
 padding-bottom: 0;
 font-size: 13px;
 color: #fff;
 text-transform: uppercase;
 font-weight: normal;
 padding: 7px 7px;
 border-bottom: 1px solid #A31923;
   background-color: #DE2D3A;
}
/* ~~this fixed width container surrounds the other divs~~ */
/*#container {
 width: 960px;
 margin: 20px auto;
 padding: 10px;
 box-shadow: 0 5px 5px 5px #CCCCCC;
 background-color: #fff;
}*/
.container {
 width: 1260px;
 margin: 20px auto;
 padding: 10px;
 background: #FFF;
    box-shadow: 0 0 5px 5px #B8B8B8;
 /*margin: 0 auto;  the auto value on the sides, coupled with the width, centers the layout */
}

.sidebar {
    float: left;
    width: 180px;
 margin-top: 10px;
}

.sidebar h4 {
 padding-bottom: 0;
 font-size: 13px;
 color: #fff;
 text-transform: uppercase;
 font-weight: normal;
 padding: 7px 7px;
 border-bottom: 1px solid #A31923;
   background-color: #DE2D3A;
}

.footer {
 padding: 10px 0;
 background: #CCC49F;
 position: relative;
 clear: both;
}

.fltrt {
 float: right;
 margin-left: 8px;
}
.fltlft {
 float: left;
 margin-right: 8px;
}
.clearfloat {
 clear:both;
 height:0;
 font-size: 1px;
 line-height: 0px;
}
.clear {
 clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div class="container">
   <header>
  <h2>our website slogan here with header image</h2>
 </header>
 <nav>
  <ul>
   <li>X</li>
   <li>X</li>
  </ul>
 </nav>
 <aside class="sidebar">
  <ul>
   <li>
    <h4>X</h4>
    <ul>
     <li>X</li>
     <li>X</li>
    </ul>
   </li>
   </ul>
 </aside>
 <main>
  <section>
  <article>
   <h2>CCCC</h2>
   <p>CCC</p>
  </article>
  <article>
   <h1>xXX<h1>
   <h2>XXX</h2>
   <p>XX</p>
  </article>
  <article>
   <h2>XXX</h2>
   <p>V</p>
  </article>
  </section>
 </main>
 <div class="clear"></div>
 <footer>
  <p>XXX.</p>
 </footer>

</body>
</html></code>```

答:
I wonder if I need a wrapper div?

Not really, you can achieve it without an additional wrapper.

or maybe my CSS not right?

That is the question, your CSS could be much better. You are using float, and unless there is a good reason behind its use, we are on 2017: use flexbox instead and forget float elements for a time.

Your example hasn't the full code, so I will do a simple code snippet with a full width header, a 180px aside with the main content next to it, and a full width footer. All of this within only one wrapper: the .container element.

span{
display: block;
  color: white;
  padding: 1rem;
}

.container{
  display: flex;
  flex-wrap: wrap;
}

header{
  width: 100%;
  min-height: 50px;
  background-color: #e74c3c;
}

aside{
  flex-basis: 180px;
  min-height: 300px;
  background-color: #f1c40f;
}

main{
  flex: 1;
  min-height: 300px;
  background-color: #f39c12;
}

footer{
  width: 100%;
  min-height: 80px;
  background-color: #2ecc71;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <span>Header</span>
    <!-- Put your content here -->
  </header>

  <aside>
    <span>Aside</span>
    <!-- Put your content here -->
  </aside>

  <main>
    <span>Main</span>
    <!-- Put your content here -->
  </main>

  <footer>
    <span>Footer</span>
    <!-- Put your content here -->
  </footer>
</div></code>```

Body:
I have a two column layout the main content area renders down the page. Not even with aside. I wonder if I need a wrapper div?
or maybe my CSS not right?
I did not post of the CSS just what Thought maybe important

@charset "utf-8";
body {
 font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
 background: #FFF;
    background-image:url(../assets/bg1.png);
 margin: 0;
 padding: 0;
 color: #000;
}
.sidebar h4 {
 padding-bottom: 0;
 font-size: 13px;
 color: #fff;
 text-transform: uppercase;
 font-weight: normal;
 padding: 7px 7px;
 border-bottom: 1px solid #A31923;
   background-color: #DE2D3A;
}
/* ~~this fixed width container surrounds the other divs~~ */
/*#container {
 width: 960px;
 margin: 20px auto;
 padding: 10px;
 box-shadow: 0 5px 5px 5px #CCCCCC;
 background-color: #fff;
}*/
.container {
 width: 1260px;
 margin: 20px auto;
 padding: 10px;
 background: #FFF;
    box-shadow: 0 0 5px 5px #B8B8B8;
 /*margin: 0 auto;  the auto value on the sides, coupled with the width, centers the layout */
}

.sidebar {
    float: left;
    width: 180px;
 margin-top: 10px;
}

.sidebar h4 {
 padding-bottom: 0;
 font-size: 13px;
 color: #fff;
 text-transform: uppercase;
 font-weight: normal;
 padding: 7px 7px;
 border-bottom: 1px solid #A31923;
   background-color: #DE2D3A;
}

.footer {
 padding: 10px 0;
 background: #CCC49F;
 position: relative;
 clear: both;
}

.fltrt {
 float: right;
 margin-left: 8px;
}
.fltlft {
 float: left;
 margin-right: 8px;
}
.clearfloat {
 clear:both;
 height:0;
 font-size: 1px;
 line-height: 0px;
}
.clear {
 clear: both;
}

our website slogan here with header image

X

X

X

X

X

CCCC

CCC

xXX

XXX

XX

XXX

V

XXX.

Body:
I wonder if I need a wrapper div?

Not really, you can achieve it without an additional wrapper.

or maybe my CSS not right?

That is the question, your CSS could be much better. You are using float, and unless there is a good reason behind its use, we are on 2017: use flexbox instead and forget float elements for a time.

Your example hasn't the full code, so I will do a simple code snippet with a full width header, a 180px aside with the main content next to it, and a full width footer. All of this within only one wrapper: the .container element.

span{
display: block;
  color: white;
  padding: 1rem;
}

.container{
  display: flex;
  flex-wrap: wrap;
}

header{
  width: 100%;
  min-height: 50px;
  background-color: #e74c3c;
}

aside{
  flex-basis: 180px;
  min-height: 300px;
  background-color: #f1c40f;
}

main{
  flex: 1;
  min-height: 300px;
  background-color: #f39c12;
}

footer{
  width: 100%;
  min-height: 80px;
  background-color: #2ecc71;
}

<div class="container">
  <header>
    <span>Header</span>
    <!-- Put your content here -->
  </header>

  <aside>
    <span>Aside</span>
    <!-- Put your content here -->
  </aside>

  <main>
    <span>Main</span>
    <!-- Put your content here -->
  </main>

  <footer>
    <span>Footer</span>
    <!-- Put your content here -->
  </footer>
</div>


问:
Get URL headers without the HTML
A bit of a strange question. Is there a way to ask a webserver to return only the headers and not the HTML itself ?

I want to ask a server for a URL and see if its valid (not 404/500/etc) and follow the redirections (if present) but not get the actual HTML content.

Thanks

Preferably a way to do this in Ruby

答:
As suggested, check the Net::HTTP library..</p>

```<code>require 'net/http'
Net::HTTP.new('www.twitter.com').request_head('/').class
</code>```

ContentLicense: CC BY-SA 2.5

Title: Get URL headers without the HTML

Body:
As suggested, check the Net::HTTP library..

require 'net/http'
Net::HTTP.new('www.twitter.com').request_head('/').class


问:
What do chained arrow functions mean in redux?
Looking at the real world example I see this setting up the api middleware:

```<code>export default store => next => action => {
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action)
  }
</code>```

What exactly is happening here?  I see that configureStore is importing whatever that is and passing it to applyMiddleware from redux, but what does this kind of statement mean in js?

I assume it's exporting an anonymous function that returns a function that returns a function?  Just tried this:

```<code>var a = b => c => d => {
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', c);
    console.log('d:', d);
};

a(5)(6)(7);

// outputs b: 5, c: 6, and d: 7
</code>```

答:
To understand this clearly you need to first know how middlewares work in redux. So first go through this

Now even after going through the documentation you are still confused, dont worry its a bit complicated, try reading it once again :).I understood this properly after 2-3 reads.

Now the one you mentioned in your question is a curried up ES6 syntax. If you try to convert this to vanilla javascript it would come to something like below

```<code>function (store) {
  return function (next) {
    return function (action) {
      var callAPI = action[CALL_API];
      if (typeof callAPI === 'undefined') {
        return next(action);
      }
    };
  };
};
</code>```

So if you see its nothing but just chaining of functions.

Body:
Looking at the real world example I see this setting up the api middleware:

export default store => next => action => {
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action)
  }

What exactly is happening here?  I see that configureStore is importing whatever that is and passing it to applyMiddleware from redux, but what does this kind of statement mean in js?

I assume it's exporting an anonymous function that returns a function that returns a function?  Just tried this:

var a = b => c => d => {
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', c);
    console.log('d:', d);
};

a(5)(6)(7);

// outputs b: 5, c: 6, and d: 7

Body:
To understand this clearly you need to first know how middlewares work in redux. So first go through this

Now even after going through the documentation you are still confused, dont worry its a bit complicated, try reading it once again :).I understood this properly after 2-3 reads.

Now the one you mentioned in your question is a curried up ES6 syntax. If you try to convert this to vanilla javascript it would come to something like below

function (store) {
  return function (next) {
    return function (action) {
      var callAPI = action[CALL_API];
      if (typeof callAPI === 'undefined') {
        return next(action);
      }
    };
  };
};

So if you see its nothing but just chaining of functions.


问:
How to execute Python code from within Visual Studio Code
Visual Studio Code was recently released and I liked the look of it and the features it offered, so I figured I would give it a go.

I downloaded the application from the downloads page, fired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Python code!

I really like the look and feel/usability/features of Visual Studio Code, but I can't seem to find out how to run my Python code, a real killer because that's what I program primarily in.

Is there is a way to execute Python code in Visual Studio Code?

答:
A simple and direct Python extension would save both time and efforts.
Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe"
With above steps at least the basic Python programs can be executed.

ContentLicense: CC BY-SA 4.0


问:
wordpress how to get yesterday published post ids
Is there any function to get yesterday published all post ids?
I always need yesterday or specific days post ids.

Example: today is: 01/04/2017 , i need all published post ids which published on 31/03/2017

答:
You can use the date parameters of get_posts to find this:

```<code><?php
// Get the date pieces using the timezone you set in WordPress, minus one day
$yesterday = getdate( current_time() - DAY_IN_SECONDS );

// Query for posts from yesterday
$yesterdays_posts = get_posts( array(
  'date_query' => array(
    array(
      'year' => $yesterday[ 'year' ],
      'month' => $yesterday[ 'mon' ],
      'day' => $yesterday[ 'mday' ]
    )
  ),
  'nopaging' => true
) );
</code>```

This will give you an array of post objects from yesterday. nopaging means "give me all of them". Now, you can iterate through the results. If you just need the IDs, you can add them to an array like this:

```<code><?php
$yesterdays_posts_ids = array();
if( $yesterdays_posts ){
  foreach( $yesterdays_posts as $yesterdays_post ){
    $yesterdays_posts_ids[] = $yesterdays_post->ID;
  }
}
</code>```

Body:
You can use the date parameters of get_posts to find this:

<?php
// Get the date pieces using the timezone you set in WordPress, minus one day
$yesterday = getdate( current_time() - DAY_IN_SECONDS );

// Query for posts from yesterday
$yesterdays_posts = get_posts( array(
  'date_query' => array(
    array(
      'year' => $yesterday[ 'year' ],
      'month' => $yesterday[ 'mon' ],
      'day' => $yesterday[ 'mday' ]
    )
  ),
  'nopaging' => true
) );

This will give you an array of post objects from yesterday. nopaging means "give me all of them". Now, you can iterate through the results. If you just need the IDs, you can add them to an array like this:

<?php
$yesterdays_posts_ids = array();
if( $yesterdays_posts ){
  foreach( $yesterdays_posts as $yesterdays_post ){
    $yesterdays_posts_ids[] = $yesterdays_post->ID;
  }
}


问:
How to center this image in div
I've tried alot of solutions and maybe I just implemented them wrongly for my code but I need help as my yr 11 task is due in 1 more day! Someone save me aha.
I apologize for not having a fiddle example to use as I don't know how to set it up or whatever, also the site just wants me to add more details so I'm just gonna keep writing till it lets me post cause I'm tired af and can't think. Whoever helps me your a bloody legend, cheers from straya :)

.slideshow {
  display: none;
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: inline-block;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  height: 100%;
  float: left;
}

.slide_info {
  display: inline-block;
  float: right;
  width: 75%;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <div class="slide_selection">
    <div onclick="test(1);" class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>WinRar</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>OllyDBG</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>NortonAV</figcaption>
    </div>
  </div>
  <div class="slide_content">
    <div class="slide_image">
      <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
    </div>
    <div class="slide_info">
      <h4>Software Type: </h4>
      <h4>Release Date: </h4>
      <p>Winrar Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

    </div>

  </div>
</div></code>```

答:
Can I be consider as bloody legend?

Codepen: http://codepen.io/anon/pen/NpoGPr

What I did is use flexbox to center the image.

justify-content is for horizontal centering

align-items is for vertical centering

.slideshow {
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: flex;
  height: 100%;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.slide_info {
  display: inline-block;
  width: 75%;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <div class="slide_selection">
    <div onclick="test(1);" class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>WinRar</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>OllyDBG</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>NortonAV</figcaption>
    </div>
  </div>
  <div class="slide_content">
    <div class="slide_image">
      <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
    </div>
    <div class="slide_info">
      <h4>Software Type: </h4>
      <h4>Release Date: </h4>
      <p>Winrar Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
</div></code>```

Title: How to center this image in div

Body:
I've tried alot of solutions and maybe I just implemented them wrongly for my code but I need help as my yr 11 task is due in 1 more day! Someone save me aha.
I apologize for not having a fiddle example to use as I don't know how to set it up or whatever, also the site just wants me to add more details so I'm just gonna keep writing till it lets me post cause I'm tired af and can't think. Whoever helps me your a bloody legend, cheers from straya :)

.slideshow {
  display: none;
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: inline-block;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  height: 100%;
  float: left;
}

.slide_info {
  display: inline-block;
  float: right;
  width: 75%;
  text-align: left;
}

WinRar

OllyDBG

NortonAV

Software Type:

Release Date:

Winrar Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
Can I be consider as bloody legend?

Codepen: http://codepen.io/anon/pen/NpoGPr

What I did is use flexbox to center the image.

justify-content is for horizontal centering

align-items is for vertical centering

.slideshow {
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: flex;
  height: 100%;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.slide_info {
  display: inline-block;
  width: 75%;
  text-align: left;
}

<div class="slideshow">
  <div class="slide_selection">
    <div onclick="test(1);" class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>WinRar</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>OllyDBG</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>NortonAV</figcaption>
    </div>
  </div>
  <div class="slide_content">
    <div class="slide_image">
      <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
    </div>
    <div class="slide_info">
      <h4>Software Type: </h4>
      <h4>Release Date: </h4>
      <p>Winrar Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
</div>


问:
WPF - ObservableCollection casting
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

```<code>public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}
</code>```

答:
```<code>PersonsMeeting(Emp.OfType<Person>);
</code>```

or

```<code>PersonsMeeting(Emp.Cast<Person>);
</code>```

Title: WPF - ObservableCollection casting

Body:
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}

Body:
PersonsMeeting(Emp.OfType<Person>);

or

PersonsMeeting(Emp.Cast<Person>);


问:
Broadcast Receiver class send status to fragment
I have a broadcast receiver as part of my class, in moving the Broadcast receiver to its own class I am not able to return any sort of value back to the class that needs that data. Is there a way to set the data and then send it back to the class that has registered it?

The Overview Class should be able to pick up the status of what the BatteryReceiver class issues.

```<code>public class Overview extends Fragment {

    private Unbinder unbinder;

    private BroadcastReceiver batteryReceiver = new BatteryReceiver();

    @BindView(R.id.bat_generic)
    TextView batText;

    public Overview() {
        // Required empty public constructor
    }

    public static Overview newInstance() {
        return new Overview();
    }

    @Override
    public void onCreate(Bundle outState) {
        super.onCreate(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_overview, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            initView();

            getActivity().registerReceiver(
                    batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            );

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        unbinder.unbind();
        getActivity().unregisterReceiver(batteryReceiver);
    }

    private void initView() {

        batText.setText(
          // TODO: logic
        );
}
</code>```

The BatteryReceiver class should be able to send the data back to the class that implements it.

```<code>public class BatteryReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int percentage = (int) (((float) level / (float) scale) * 100.0f);

        switch (deviceStatus) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
                context.getString((R.string.bat_charge), "Charging:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                context.getString((R.string.bat_charge), "Discharging:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_FULL:
                context.getString((R.string.bat_charge), "Full:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:
                context.getString((R.string.bat_charge), "Unknown:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                context.getString((R.string.bat_charge), "Not charging:", percentage, "%");
                break;
        }
    }
</code>```

答:
Basically you can't register a broadcast in a class that isn't context but there is a way around you can pass context to other class.

```<code>        // implements OnBatteryChange in your activity
    public class MainActivity extends AppCompatActivity implements OnBatteryChange {...
    // add following method in your activity
     @Override
      public void batteryChanged(String data) {
        txtBat.setText(data);
      }
    // add following line in onCreate() in activity

    OtherReceiver reciever = new OtherReceiver(getApplicationContext(),this);
    reciever.doSomethingWithReceivedIntent();

        //OtherReceiver class

        public class OtherReceiver {
    Context context;
    OnBatteryChange batteryChange;

    public OtherReceiver(Context context, OnBatteryChange batteryChange) {
        this.context = context;
        this.batteryChange = batteryChange;
    }

    public void doSomethingWithReceivedIntent() {
        BatteryReceiver batteryReceiver = new BatteryReceiver();
        batteryReceiver.setBatteryChange(batteryChange);
        context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
}

    //OnBatteryChange interface

    public interface OnBatteryChange {
        void batteryChanged(String data);
    }

    //amend BatteryReceiver to following code
public class BatteryReceiver extends BroadcastReceiver {
    OnBatteryChange batteryChange;

    public void setBatteryChange(OnBatteryChange batteryChange) {
        this.batteryChange = batteryChange;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int percentage = (int) (((float) level / (float) scale) * 100.0f);

        switch (deviceStatus) {
            case BatteryManager.BATTERY_STATUS_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Charging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Discharging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_FULL:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Full:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Unknown:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Not charging:", percentage, "%"));
                break;
        }
    }

}
</code>```

for unregistering you can define another method too.

Body:
I have a broadcast receiver as part of my class, in moving the Broadcast receiver to its own class I am not able to return any sort of value back to the class that needs that data. Is there a way to set the data and then send it back to the class that has registered it?

The Overview Class should be able to pick up the status of what the BatteryReceiver class issues.

public class Overview extends Fragment {

    private Unbinder unbinder;

    private BroadcastReceiver batteryReceiver = new BatteryReceiver();

    @BindView(R.id.bat_generic)
    TextView batText;

    public Overview() {
        // Required empty public constructor
    }

    public static Overview newInstance() {
        return new Overview();
    }

    @Override
    public void onCreate(Bundle outState) {
        super.onCreate(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_overview, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            initView();

            getActivity().registerReceiver(
                    batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            );

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        unbinder.unbind();
        getActivity().unregisterReceiver(batteryReceiver);
    }

    private void initView() {

        batText.setText(
          // TODO: logic
        );
}

The BatteryReceiver class should be able to send the data back to the class that implements it.

public class BatteryReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int percentage = (int) (((float) level / (float) scale) * 100.0f);

        switch (deviceStatus) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
                context.getString((R.string.bat_charge), "Charging:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                context.getString((R.string.bat_charge), "Discharging:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_FULL:
                context.getString((R.string.bat_charge), "Full:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:
                context.getString((R.string.bat_charge), "Unknown:", percentage, "%");
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                context.getString((R.string.bat_charge), "Not charging:", percentage, "%");
                break;
        }
    }

Body:
Basically you can't register a broadcast in a class that isn't context but there is a way around you can pass context to other class.

        // implements OnBatteryChange in your activity
    public class MainActivity extends AppCompatActivity implements OnBatteryChange {...
    // add following method in your activity
     @Override
      public void batteryChanged(String data) {
        txtBat.setText(data);
      }
    // add following line in onCreate() in activity

    OtherReceiver reciever = new OtherReceiver(getApplicationContext(),this);
    reciever.doSomethingWithReceivedIntent();

        //OtherReceiver class

        public class OtherReceiver {
    Context context;
    OnBatteryChange batteryChange;

    public OtherReceiver(Context context, OnBatteryChange batteryChange) {
        this.context = context;
        this.batteryChange = batteryChange;
    }

    public void doSomethingWithReceivedIntent() {
        BatteryReceiver batteryReceiver = new BatteryReceiver();
        batteryReceiver.setBatteryChange(batteryChange);
        context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
}

    //OnBatteryChange interface

    public interface OnBatteryChange {
        void batteryChanged(String data);
    }

    //amend BatteryReceiver to following code
public class BatteryReceiver extends BroadcastReceiver {
    OnBatteryChange batteryChange;

    public void setBatteryChange(OnBatteryChange batteryChange) {
        this.batteryChange = batteryChange;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int percentage = (int) (((float) level / (float) scale) * 100.0f);

        switch (deviceStatus) {
            case BatteryManager.BATTERY_STATUS_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Charging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Discharging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_FULL:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Full:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Unknown:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Not charging:", percentage, "%"));
                break;
        }
    }

}

for unregistering you can define another method too.


问:
How can I implement a view such that it increase like a rounded circle
I have a task in which I have to increase the view size depending on timer value. I know view frame will be increased, however I am searching the way like the first round completed then another layer round comes on it so that the view frame size increased and the desired output will also shows.

答:
Something like this...

```<code>var radius = 1
func drawCircle() {
    let circle = UIView()
    circle.frame.size = CGSize(width: radius * 2, height: radius * 2)
    circle.backgroundColor =  .clear
    circle.layer.cornerRadius = radius
    circle.layer.borderWidth = 1
    circle.layer.borderColor = UIColor.red.cgColor
    circle.center = self.center
    view.addSubview(circle)
    radius += 1
}
</code>```

Note. Not sure if you wanna keep adding views. If not, put the view property outside the method and only update the size and / or remove it first from the superview before you initialize it again. Moreover you probably wanna limit the radius to a maximum value.

Body:
Something like this...

var radius = 1
func drawCircle() {
    let circle = UIView()
    circle.frame.size = CGSize(width: radius * 2, height: radius * 2)
    circle.backgroundColor =  .clear
    circle.layer.cornerRadius = radius
    circle.layer.borderWidth = 1
    circle.layer.borderColor = UIColor.red.cgColor
    circle.center = self.center
    view.addSubview(circle)
    radius += 1
}

Note. Not sure if you wanna keep adding views. If not, put the view property outside the method and only update the size and / or remove it first from the superview before you initialize it again. Moreover you probably wanna limit the radius to a maximum value.


问:
Corona Labs - Open up links from newWebView in device's browser
I have written some of the content for my Corona app in HTML and I display it in my app using the native.newWebview.  Within this HTML content, I have links to external web pages, for example https://google.com.

When a user clicks on the link in my app, I'd like my HTML content to remain in the app and for Google to open up in the device's web browser.

However, what happens is that when they click on a link in my app,  Google will open up in both my app and in the web browser.

As a note, in iOS, it seems the first time the link is clicked, it opens up in just the device's default browser and not the app, but if you return to the app and click the link again it will open up in both the app and the browser.  For Android it always opens up in both the app and in the browser.

Here is a simplified version of my code.

main.lua

```<code>local function webListener( event )
    if event.url then
        system.openURL(event.url)
    end
end

htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
htmlContent:request( "links.html", system.ResourceDirectory )
htmlContent:addEventListener( "urlRequest", webListener )
</code>```

And here is the html content with the link that is displayed in the app.

links.html

```<code><html>
<head>
</head>
<body>
    Go to <a href="https://google.com/">Google</a>.
</body>
</html>
</code>```

答:
Try (tested)

links.html

```<code><html>
  <head></head>
  <body>
    Go to <a href="#corona://https://google.com/>Google</a>.
  </body>
</html>
</code>```

main.lua

```<code>local function webListener( event )
    if event.url then
        local pattern = 'corona://'
        local position = string.find( event.url, pattern ) or 0
        local len = position == 0 and 0 or string.len( pattern )
        local url = string.sub( event.url, position + len )
        if len > 0 then -- ensures that the app doesn't try to open links.html in the default browser window
            system.openURL( url )
            --print( url )
        end
    end
end

local htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight-2*100 )
htmlContent:request( "links.html", system.ResourceDirectory )
htmlContent:addEventListener( "urlRequest", webListener )
</code>```

Body:
I have written some of the content for my Corona app in HTML and I display it in my app using the native.newWebview.  Within this HTML content, I have links to external web pages, for example https://google.com.

When a user clicks on the link in my app, I'd like my HTML content to remain in the app and for Google to open up in the device's web browser.

However, what happens is that when they click on a link in my app,  Google will open up in both my app and in the web browser.

As a note, in iOS, it seems the first time the link is clicked, it opens up in just the device's default browser and not the app, but if you return to the app and click the link again it will open up in both the app and the browser.  For Android it always opens up in both the app and in the browser.

Here is a simplified version of my code.

main.lua

local function webListener( event )
    if event.url then
        system.openURL(event.url)
    end
end

htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
htmlContent:request( "links.html", system.ResourceDirectory )
htmlContent:addEventListener( "urlRequest", webListener )

And here is the html content with the link that is displayed in the app.

links.html

    Go to Google.

Body:
Try (tested)

links.html

<html>
  <head></head>
  <body>
    Go to <a href="#corona://https://google.com/>Google</a>.
  </body>
</html>

main.lua

local function webListener( event )
    if event.url then
        local pattern = 'corona://'
        local position = string.find( event.url, pattern ) or 0
        local len = position == 0 and 0 or string.len( pattern )
        local url = string.sub( event.url, position + len )
        if len > 0 then -- ensures that the app doesn't try to open links.html in the default browser window
            system.openURL( url )
            --print( url )
        end
    end
end

local htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight-2*100 )
htmlContent:request( "links.html", system.ResourceDirectory )
htmlContent:addEventListener( "urlRequest", webListener )


问:
How to sum two columns using sub query in a grouped data of joined tables
I've a query :

```<code>SELECT COUNT(*) as Avalied
FROM PY_LeaveTransactionMasterTAB as lm
JOIN PY_LeaveTransactionSubsidaryTAB as ls
ON lm.LV_TransMasterId = ls.LV_TransMasterId
WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by lm.Status
</code>```

The Above query returns:

```<code>Availed
-------
   3
</code>```

and another query :

```<code>SELECT PY_Leave + CY_Leave as Openning
FROM PY_LeaveOpeningTAB
WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
</code>```

this query returns :

```<code>Openning
--------
   25
   23
   30
</code>```

I want to combine the above two queries to get the below result :

```<code>Openning   Availed
--------   --------
   25         3
   23         0
   30         0
</code>```

How do I achieve the above result? Thanks :)

答:
It doesn't make sense to me that you would want "3" on one row but "0" on the other rows.  You could do something like this:

```<code>SELECT (PY_Leave + CY_Leave) as Openning,
       (CASE WHEN PY_Leave + CY_Leave = 25 THEN x.Avalied ELSE 0 END) as Avalied
FROM PY_LeaveOpeningTAB lo CROSS JOIN
     (SELECT COUNT(*) as Avalied
      FROM PY_LeaveTransactionMasterTAB lm JOIN
           PY_LeaveTransactionSubsidaryTAB as ls
           ON lm.LV_TransMasterId = ls.LV_TransMasterId
      WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND
            lm.Status ='Approved'
     ) x
WHERE lo.SystemCode = 'faheem123' and lo.EmployeeCode = '0014';
</code>```

As I say, it makes more sense (to me) to remove the CASE and put the "3" on all three "matching" rows.

Body:
I've a query :

SELECT COUNT(*) as Avalied
FROM PY_LeaveTransactionMasterTAB as lm
JOIN PY_LeaveTransactionSubsidaryTAB as ls
ON lm.LV_TransMasterId = ls.LV_TransMasterId
WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by lm.Status

The Above query returns:

Availed
-------
   3

and another query :

SELECT PY_Leave + CY_Leave as Openning
FROM PY_LeaveOpeningTAB
WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'

this query returns :

Openning
--------
   25
   23
   30

I want to combine the above two queries to get the below result :

Openning   Availed
--------   --------
   25         3
   23         0
   30         0

How do I achieve the above result? Thanks :)

Body:
It doesn't make sense to me that you would want "3" on one row but "0" on the other rows.  You could do something like this:

SELECT (PY_Leave + CY_Leave) as Openning,
       (CASE WHEN PY_Leave + CY_Leave = 25 THEN x.Avalied ELSE 0 END) as Avalied
FROM PY_LeaveOpeningTAB lo CROSS JOIN
     (SELECT COUNT(*) as Avalied
      FROM PY_LeaveTransactionMasterTAB lm JOIN
           PY_LeaveTransactionSubsidaryTAB as ls
           ON lm.LV_TransMasterId = ls.LV_TransMasterId
      WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND
            lm.Status ='Approved'
     ) x
WHERE lo.SystemCode = 'faheem123' and lo.EmployeeCode = '0014';

As I say, it makes more sense (to me) to remove the CASE and put the "3" on all three "matching" rows.


问:
Angular JS - Cannot push object into scope array
im sure im missing something probably very basic but cant seem to wrap my head around this issue. I am simple trying to push an object into a scope array on click. I am currently getting error: TypeError: Cannot read property 'push' of undefined(…)

Heres an example of what I got so far:

```<code>var app = angular.module('myApp', []);

app.factory('MyService', function($http, $q, $timeout){

    var My_Stored_Data = {}

    return {

        template: function(){

            var template = { data1: "", data2: "", data3: "", data4: "" }
            return template

        }

    }
});
</code>```

Here is the controller:

```<code>app.controller('MyController', function ($scope,$q,MyService) {

    $scope.Main_scope = {};

    $scope.add_new_object = function(){

        $scope.Main_scope.My_array.push(MyService.template());
        //This give an error TypeError: Cannot read property 'push' of undefined(…)
    }

});
</code>```

Anyone have anyidea what im missing?

答:
The error is verbose and clear My_array is not defined.

You need to define the array in your Main_scope variable.

```<code>$scope.Main_scope = {
    My_array : []
};
</code>```

Body:
im sure im missing something probably very basic but cant seem to wrap my head around this issue. I am simple trying to push an object into a scope array on click. I am currently getting error: TypeError: Cannot read property 'push' of undefined(…)

Heres an example of what I got so far:

var app = angular.module('myApp', []);

app.factory('MyService', function($http, $q, $timeout){

    var My_Stored_Data = {}

    return {

        template: function(){

            var template = { data1: "", data2: "", data3: "", data4: "" }
            return template

        }

    }
});

Here is the controller:

app.controller('MyController', function ($scope,$q,MyService) {

    $scope.Main_scope = {};

    $scope.add_new_object = function(){

        $scope.Main_scope.My_array.push(MyService.template());
        //This give an error TypeError: Cannot read property 'push' of undefined(…)
    }

});

Anyone have anyidea what im missing?

Body:
The error is verbose and clear My_array is not defined.

You need to define the array in your Main_scope variable.

$scope.Main_scope = {
    My_array : []
};


问:
How to solve NullPointerException void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest) with Butterknife
Actually, I am trying to make an app with free and paid flavors. When I use simple findViewById method to bind then it works fine. But when I trying to add butterKnife, I desperately stuck with butterKnife.

I am trying to bind content (such as AdMob OR Button) by butterknife bind in MainActivity.java file. but it shows Nullpointer exception error first it shows on AdMob object nullpointer exception. I run clean project then it shows on button.onClickListener Nullpointer exception.

Please help me...

Here is the Error: which shows AdMob nullpointerException:

```<code>09-08 19:04:30.860 19466-19466/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.santossingh.jokeapp.free, PID: 19466
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.santossingh.jokeapp.free/com.santossingh.jokeapp.free.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
                                                       at com.santossingh.jokeapp.free.MainActivity.onCreate(MainActivity.java:62)
                                                       at android.app.Activity.performCreate(Activity.java:6237)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-08 19:04:35.652 837-2192/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0xf2cf6c90
09-08 19:04:56.030 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:06:20.986 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:07:41.011 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:09:01.042 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:10:20.982 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:11:46.019 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:13:06.051 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:14:41.018 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:16:06.047 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
</code>```

2-MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements AsyncResponse{

    @BindView(R.id.avi) AVLoadingIndicatorView avLoadingIndicatorView;
    @BindView(R.id.button_jokeTeller) Button button_JokeTeller;
    @BindView(R.id.instruction_TextView)
    TextView instruction;
    @BindView(R.id.container) RelativeLayout relativeLayout;
    @BindView(R.id.adView) AdView adView;
    @BindView(R.id.progressBar) LinearLayout linearLayout;

    private InterstitialAd mInterstitialAd;
    EndpointsAsyncTask endpointsAsyncTask;
    private static final String JOKE_TAG="joke";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        endpointsAsyncTask = new EndpointsAsyncTask(this);

        AdRequest adRequestBanner = new AdRequest.Builder().build();
        adView.loadAd(adRequestBanner);

        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        AdRequest adRequestInterstitial = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(adRequestInterstitial);

        button_JokeTeller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInterstitial();
            }
        });

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                showProgressbar(true);
                showJoke();
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLeftApplication() {
                showProgressbar(true);
                Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdOpened() {
                Toast.makeText(getApplicationContext(), "Ad is opened!", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showInterstitial() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }

    public void showJoke(){
        endpointsAsyncTask.execute(getString(R.string.keyword));
    }

    @Override
    public void processFinish(String result) {
        Intent intent = new Intent(this, JokeActivity
                .class)
                .putExtra(JOKE_TAG, result);
        showProgressbar(false);
        startActivity(intent);
    }

    public void showProgressbar(boolean a){
        if(a==true){
            relativeLayout.setVisibility(View.GONE);
            linearLayout.setVisibility(View.VISIBLE);
        }else{
            linearLayout.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.VISIBLE);
        }
    }
}
</code>```

3- activity_main.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0e73a6"
    android:padding="10dp"
    tools:context="com.santossingh.jokeapp.free.MainActivity"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <LinearLayout
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="match_parent">

    <com.wang.avi.AVLoadingIndicatorView
        android:id="@+id/avi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/AVLoadingIndicatorView"
        android:visibility="visible"
        app:indicatorName="BallPulseIndicator"
    />
</LinearLayout>
    <RelativeLayout android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/container">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/instructions"
            android:textColor="#fff"
            android:id="@+id/instruction_TextView"
        />

        <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button_jokeTeller"
                android:layout_below="@+id/instruction_TextView"
                android:text="@string/button_text"
        />

        <!-- view for AdMob Banner Ad -->
        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"/>
    </RelativeLayout>

</RelativeLayout>
</code>```

4- manifest file

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application>
        <activity android:name="com.santossingh.jokeapp.free.MainActivity"
        >
            <!-- This meta-data tag is required to use Google Play Services. -->
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version"/>

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent"/>
</manifest>
</code>```

答:
I faced similar issue. When I checked closely in resource file There were two resource file for my activity:

\res\layout\activity_main_lauch.xml

\res\layout-v21\activity_main_lauch.xml

I was modifying single file, hence it was throwing error. When I apply the change in both files it started working.

Body:
Actually, I am trying to make an app with free and paid flavors. When I use simple findViewById method to bind then it works fine. But when I trying to add butterKnife, I desperately stuck with butterKnife.

I am trying to bind content (such as AdMob OR Button) by butterknife bind in MainActivity.java file. but it shows Nullpointer exception error first it shows on AdMob object nullpointer exception. I run clean project then it shows on button.onClickListener Nullpointer exception.

Please help me...

Here is the Error: which shows AdMob nullpointerException:

09-08 19:04:30.860 19466-19466/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.santossingh.jokeapp.free, PID: 19466
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.santossingh.jokeapp.free/com.santossingh.jokeapp.free.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
                                                       at com.santossingh.jokeapp.free.MainActivity.onCreate(MainActivity.java:62)
                                                       at android.app.Activity.performCreate(Activity.java:6237)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-08 19:04:35.652 837-2192/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0xf2cf6c90
09-08 19:04:56.030 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:06:20.986 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:07:41.011 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:09:01.042 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:10:20.982 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:11:46.019 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:13:06.051 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:14:41.018 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null
09-08 19:16:06.047 837-853/system_process E/BluetoothAdapter: Bluetooth binder is null

2-MainActivity.java

public class MainActivity extends AppCompatActivity implements AsyncResponse{

    @BindView(R.id.avi) AVLoadingIndicatorView avLoadingIndicatorView;
    @BindView(R.id.button_jokeTeller) Button button_JokeTeller;
    @BindView(R.id.instruction_TextView)
    TextView instruction;
    @BindView(R.id.container) RelativeLayout relativeLayout;
    @BindView(R.id.adView) AdView adView;
    @BindView(R.id.progressBar) LinearLayout linearLayout;

    private InterstitialAd mInterstitialAd;
    EndpointsAsyncTask endpointsAsyncTask;
    private static final String JOKE_TAG="joke";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        endpointsAsyncTask = new EndpointsAsyncTask(this);

        AdRequest adRequestBanner = new AdRequest.Builder().build();
        adView.loadAd(adRequestBanner);

        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        AdRequest adRequestInterstitial = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(adRequestInterstitial);

        button_JokeTeller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInterstitial();
            }
        });

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                showProgressbar(true);
                showJoke();
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLeftApplication() {
                showProgressbar(true);
                Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdOpened() {
                Toast.makeText(getApplicationContext(), "Ad is opened!", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showInterstitial() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }

    public void showJoke(){
        endpointsAsyncTask.execute(getString(R.string.keyword));
    }

    @Override
    public void processFinish(String result) {
        Intent intent = new Intent(this, JokeActivity
                .class)
                .putExtra(JOKE_TAG, result);
        showProgressbar(false);
        startActivity(intent);
    }

    public void showProgressbar(boolean a){
        if(a==true){
            relativeLayout.setVisibility(View.GONE);
            linearLayout.setVisibility(View.VISIBLE);
        }else{
            linearLayout.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.VISIBLE);
        }
    }
}

3- activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0e73a6"
    android:padding="10dp"
    tools:context="com.santossingh.jokeapp.free.MainActivity"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <LinearLayout
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="match_parent">

    <com.wang.avi.AVLoadingIndicatorView
        android:id="@+id/avi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/AVLoadingIndicatorView"
        android:visibility="visible"
        app:indicatorName="BallPulseIndicator"
    />
</LinearLayout>
    <RelativeLayout android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/container">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/instructions"
            android:textColor="#fff"
            android:id="@+id/instruction_TextView"
        />

        <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button_jokeTeller"
                android:layout_below="@+id/instruction_TextView"
                android:text="@string/button_text"
        />

        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"/>
    </RelativeLayout>

</RelativeLayout>

4- manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application>
        <activity android:name="com.santossingh.jokeapp.free.MainActivity"
        >

            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version"/>

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent"/>
</manifest>


问:
How to insert value in textarea in Flask?
I have a form:

class simple_order(Form):
    order_info = TextAreaField()
,in the template i am added:
{{form.order_info(cols=60, rows=20)}}

How to add text into render textarea, like value in the input tag?

答:
There are several ways to do it.

i. When creating a model you can do like below:

```<code>order_info = TextAreaField(default='This is default text')
</code>```

ii. Before rendering the form, you can add the content:

```<code>form = simple_order()
form.order_info.data = 'This is default text'
</code>```

Hope it helps.

Body:
There are several ways to do it.

i. When creating a model you can do like below:

order_info = TextAreaField(default='This is default text')

ii. Before rendering the form, you can add the content:

form = simple_order()
form.order_info.data = 'This is default text'

Hope it helps.


答:
You need to initialize My_array  inside the Main_scope Object</p>

```<code>app.controller('MyController', function ($scope,$q,MyService) {
     $scope.Main_scope = {};
     $scope.Main_scope.My_array =[];
</code>```

Title: Angular JS - Cannot push object into scope array

Body:
You need to initialize My_array  inside the Main_scope Object

app.controller('MyController', function ($scope,$q,MyService) {
     $scope.Main_scope = {};
     $scope.Main_scope.My_array =[];


问:
Routing to different controllers depending on authentication
In rewriting an app using Symfony2, I'm attempting to preserve some legacy behaviour and am looking for a clean solution.

My goal is to have the URI "/" display a splash page if the user is not logged in, and the same URI display a per-user dashboard if they are logged in.

The solution also needs to be scalable - there are several pages on the "public" site which have different representations on the "private" site (i.e. the index, support, about, contact, etc) - because of this I can't simply use a catch-all route and forward to the correct controller myself.

I have one potential solution, which I will post as an answer, but I'm looking for advice on better approaches.

答:
N.B. This answer is something of a hack; I'm posting it in the hopes of finding a better way.

One way to achieve this could be to make use of the Routing system's support for conditions - this has the advantage of not affecting URL generation and allowing the routing system to take care of parameters, etc.

However, in order to use the condition for this purpose, we need to expose the request's authentication status through either the Request or the RequestContext (the only two available variables).

This can be done by creating an EventListener which runs before the RouterListener and stores the authentication status in the Request's attributes.

Unfortunately, as shown in the event reference, the firewall only runs after the RouterListener, meaning that the authentication status isn't available in our listener.

As far as I can tell, the only solution is to modify the priorities such that the Firewall runs first, then our new EventListener, then finally the RouterListener. This is almost definitely a bad idea, and could cause unexpected effects.

I welcome any better suggestions as to how to achieve this.


问:
pyinstaller 3.2 with django 1.10.1
System: windows 7 64 bit, python 3.5, anaconda 3 (64 bit) , django 1.10.1

I'm trying to compile my django project in 2 ways:

First:

```<code>[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies manage.py
</code>```

Second according to this soloution:

```<code>[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies --runtime-hook=pyi_rth_django.py manage.py
</code>```

When I try to run the output:

```<code>c:\compilation\Gui\dist\gui>gui.exe runserver
</code>```

I get (for the 2 versions I get the same output):

```<code>c:\compilation\Gui\dist\gui>gui.exe runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044E9D90>
Traceback (most recent call last):
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
File "site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
File "site-packages\django\utils\six.py", line 685, in reraise
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\__init__.py", line 27, in setup
File "site-packages\django\apps\registry.py", line 85, in populate
File "site-packages\django\apps\config.py", line 116, in create
File "importlib\__init__.py", line 126, in import_module
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'django.contrib.admin.apps'
</code>```

Please advice.

答:
To fix the "ImportError: No module named django.contrib.admin.apps" problem you have to create a directory, let's call it "your_project/other_hooks".
Inside that directory create a file called  hook-django.contrib.py with this content:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_submodules
hiddenimports = collect_submodules('django.contrib')
</code>```

Now call pyinstaller in this way:

```<code>pyinstaller --name=yourProject --additional-hooks-dir=your_project\other_hooks  your_project\manage.py
</code>```

While you can use any name for the directory, the file name is mandatory, it has to be "hook-django.contrib.py".

Hope this helps.

References:

https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django
https://github.com/pyinstaller/pyinstaller/issues/2332
https://pythonhosted.org/PyInstaller/hooks.html#how-a-hook-is-loaded

Title: pyinstaller 3.2 with django 1.10.1

Body:
System: windows 7 64 bit, python 3.5, anaconda 3 (64 bit) , django 1.10.1

I'm trying to compile my django project in 2 ways:

First:

[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies manage.py

Second according to this soloution:

[Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies --runtime-hook=pyi_rth_django.py manage.py

When I try to run the output:

c:\compilation\Gui\dist\gui>gui.exe runserver

I get (for the 2 versions I get the same output):

c:\compilation\Gui\dist\gui>gui.exe runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044E9D90>
Traceback (most recent call last):
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
File "site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
File "site-packages\django\utils\six.py", line 685, in reraise
File "site-packages\django\utils\autoreload.py", line 226, in wrapper
File "site-packages\django\__init__.py", line 27, in setup
File "site-packages\django\apps\registry.py", line 85, in populate
File "site-packages\django\apps\config.py", line 116, in create
File "importlib\__init__.py", line 126, in import_module
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'django.contrib.admin.apps'

Please advice.

Body:
To fix the "ImportError: No module named django.contrib.admin.apps" problem you have to create a directory, let's call it "your_project/other_hooks".
Inside that directory create a file called  hook-django.contrib.py with this content:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_submodules
hiddenimports = collect_submodules('django.contrib')

Now call pyinstaller in this way:

pyinstaller --name=yourProject --additional-hooks-dir=your_project\other_hooks  your_project\manage.py

While you can use any name for the directory, the file name is mandatory, it has to be "hook-django.contrib.py".

Hope this helps.

References:

https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Executable-From-Django
https://github.com/pyinstaller/pyinstaller/issues/2332
https://pythonhosted.org/PyInstaller/hooks.html#how-a-hook-is-loaded