问:
Django channels - custom routing does not seem to work
I'm working on understanding Django's channel package and want to try and have more flexibility when it comes to the different things one can do on the same page. I'm stuck at trying to figure out why my webSocketBridge does not work as it looks like it should work looking at other examples.

Here is the app routing:

```<code>channel_routing = [
    route('websocket.connect', ws_connect),
    route('websocket.disconnect', ws_disconnect),
    route('websocket.receive', ws_receive),
]
custom_routing = [
    route("chat.receive", receive_chat_message, command="^send$"),
]
</code>```

The main routing that the settings.py read from:

```<code>channel_routing = [
    include("ChatApp.routing.channel_routing", path=r"^/chat/stream/$"),
    include("ChatApp.routing.custom_routing"),
]
</code>```

The consumer, not that it's even being called:

```<code>@channel_session_user
def receive_chat_message(message):
    log.debug("ws recieved a message")
    try:
        data = json.loads(message['text'])
    except ValueError:
        log.debug("ws message isn't json text")
        return

    if 'message' not in data:
        log.debug("ws message unexpected format data=%s", data)
        return

    if data:
        room = Room.objects.first()
        log.debug('chat message handle=%s message=%s', message.user, data['message'])
        reply = Message.objects.create(
            room=room,
            handle=message.user.username,
            message=data['message'],
        )

        Group('users').send({
            'text': json.dumps({
                'reply': reply.message,
                'handle': reply.handle,
                'timestamp': reply.formatted_timestamp
            })
        })
</code>```

Then there is the current JS tied to all of this:

```<code>$(function () {
  // Correctly decide between ws:// and wss://
  let ws_path = "/chat/stream/";
  console.log("Connecting to " + ws_path);

  let webSocketBridge = new channels.WebSocketBridge();
  webSocketBridge.connect(ws_path);

  webSocketBridge.listen(function(data) {
    if (data.username) {
      const username = encodeURI(data['username']);
      const user = $('li').filter(function () {
        return $(this).data('username') === username;
      });

      if (data['is_logged_in']) {
        user.html(username + ': Online');
      }
      else {
        user.html(username + ': Offline');
      }
    }
  });

  $("#chatform").on("submit", function(event) {
    event.preventDefault();
    const $message = $('#message');
    const message = {
      'command': 'send',
      'message': $message.val()
    };
    console.log(message);
    webSocketBridge.send(JSON.stringify(message));
    $message.val('').focus();
    return false;
  });

  // Helpful debugging
  webSocketBridge.socket.onopen = function () {
    console.log("Connected to chat socket");
  };
  webSocketBridge.socket.onclose = function () {
    console.log("Disconnected from chat socket");
  }
});
</code>```

Everything inside the webSockedBridge.listen() seem to do what it's supposed to, calling the ws_connect and ws_disconnect. But the part that happens on #chatformsubmit with the command thingy does not seem to work for me.

Right now it simply calls the route('websocket.receive', ws_receive) instead of the custom routing. What is missing to get it to use the command?

答:
There's something wrong with your routing:

```<code> include("ChatApp.routing.channel_routing", path=r"^/chat/stream/$")
</code>```

Remove $ at the end.

This is my  Project structure:

```<code>Project/
   project/
        ...
        routing.py
        settings.py
   app/
        ...
        routing.py
</code>```

In settings.py

```<code>CHANNEL_LAYERS = {
'default': {
    'BACKEND' : 'asgi_redis.RedisChannelLayer',
    'CONFIG': {
        'hosts': [('localhost', 6379)],
    },
    'ROUTING': 'project.routing.channel_routing'
}
}
</code>```

Project/project/routing.py

```<code>from channels import include

channel_routing = [
    include('app.routing.channel_routing', path=r'^/chat/stream/'),
    include('app.routing.custom_routing'),
]
</code>```

Project/app/routing.py

```<code>from channels import route
from .consumers import ( ws_connect,
                     ws_receive,
                     ws_disconnect,
                     receive_chat_message,
                     another_command_chat_message,
                    )

channel_routing = [
    route('websocket.connect', ws_connect),
    route('websocket.receive', ws_receive),
    route('websocket.disconnect', ws_disconnect),
]

custom_routing = [
    route('chat.receive', receive_chat_message, command="^send$"),
    route('chat.receive', another_command_chat_message, command="^cmd$"),
]
</code>```

consumers.py

```<code>from channels import Channel
import json

def ws_receive(message):
    print('Message received')
    message.reply_channel.send({'text':message.content['text']})

    print('Message.content:', message.content)
    print(type(message.content))

    print('Message[text]:', message['text'])
    print(type(message['text']))

    payload = json.loads(message['text'])
    payload['reply_channel'] = message.content['reply_channel']

    # receive the message and send to chat.receive channel
    # with command as a filter
    Channel('chat.receive').send(payload)

def ws_connect(message):
    print('Connection estabslihed')
    print(message.content)
    message.reply_channel.send({'accept': True})

def ws_disconnect(message):
    print('Disconnecting')

def receive_chat_message(message):
    print('chat receive message with `send` command')
    print(message)
    print(message.content)

def another_command_chat_message(message):
    print('chat another command with `cmd` ')
    print(message)
    print(message.content)
</code>```

Body:
I'm working on understanding Django's channel package and want to try and have more flexibility when it comes to the different things one can do on the same page. I'm stuck at trying to figure out why my webSocketBridge does not work as it looks like it should work looking at other examples.

Here is the app routing:

channel_routing = [
    route('websocket.connect', ws_connect),
    route('websocket.disconnect', ws_disconnect),
    route('websocket.receive', ws_receive),
]
custom_routing = [
    route("chat.receive", receive_chat_message, command="^send$"),
]

The main routing that the settings.py read from:

channel_routing = [
    include("ChatApp.routing.channel_routing", path=r"^/chat/stream/$"),
    include("ChatApp.routing.custom_routing"),
]

The consumer, not that it's even being called:

@channel_session_user
def receive_chat_message(message):
    log.debug("ws recieved a message")
    try:
        data = json.loads(message['text'])
    except ValueError:
        log.debug("ws message isn't json text")
        return

    if 'message' not in data:
        log.debug("ws message unexpected format data=%s", data)
        return

    if data:
        room = Room.objects.first()
        log.debug('chat message handle=%s message=%s', message.user, data['message'])
        reply = Message.objects.create(
            room=room,
            handle=message.user.username,
            message=data['message'],
        )

        Group('users').send({
            'text': json.dumps({
                'reply': reply.message,
                'handle': reply.handle,
                'timestamp': reply.formatted_timestamp
            })
        })

Then there is the current JS tied to all of this:

$(function () {
  // Correctly decide between ws:// and wss://
  let ws_path = "/chat/stream/";
  console.log("Connecting to " + ws_path);

  let webSocketBridge = new channels.WebSocketBridge();
  webSocketBridge.connect(ws_path);

  webSocketBridge.listen(function(data) {
    if (data.username) {
      const username = encodeURI(data['username']);
      const user = $('li').filter(function () {
        return $(this).data('username') === username;
      });

      if (data['is_logged_in']) {
        user.html(username + ': Online');
      }
      else {
        user.html(username + ': Offline');
      }
    }
  });

  $("#chatform").on("submit", function(event) {
    event.preventDefault();
    const $message = $('#message');
    const message = {
      'command': 'send',
      'message': $message.val()
    };
    console.log(message);
    webSocketBridge.send(JSON.stringify(message));
    $message.val('').focus();
    return false;
  });

  // Helpful debugging
  webSocketBridge.socket.onopen = function () {
    console.log("Connected to chat socket");
  };
  webSocketBridge.socket.onclose = function () {
    console.log("Disconnected from chat socket");
  }
});

Everything inside the webSockedBridge.listen() seem to do what it's supposed to, calling the ws_connect and ws_disconnect. But the part that happens on #chatformsubmit with the command thingy does not seem to work for me.

Right now it simply calls the route('websocket.receive', ws_receive) instead of the custom routing. What is missing to get it to use the command?

Body:
There's something wrong with your routing:

 include("ChatApp.routing.channel_routing", path=r"^/chat/stream/$")

Remove $ at the end.

This is my  Project structure:

Project/
   project/
        ...
        routing.py
        settings.py
   app/
        ...
        routing.py

In settings.py

CHANNEL_LAYERS = {
'default': {
    'BACKEND' : 'asgi_redis.RedisChannelLayer',
    'CONFIG': {
        'hosts': [('localhost', 6379)],
    },
    'ROUTING': 'project.routing.channel_routing'
}
}

Project/project/routing.py

from channels import include

channel_routing = [
    include('app.routing.channel_routing', path=r'^/chat/stream/'),
    include('app.routing.custom_routing'),
]

Project/app/routing.py

from channels import route
from .consumers import ( ws_connect,
                     ws_receive,
                     ws_disconnect,
                     receive_chat_message,
                     another_command_chat_message,
                    )

channel_routing = [
    route('websocket.connect', ws_connect),
    route('websocket.receive', ws_receive),
    route('websocket.disconnect', ws_disconnect),
]

custom_routing = [
    route('chat.receive', receive_chat_message, command="^send$"),
    route('chat.receive', another_command_chat_message, command="^cmd$"),
]

consumers.py

from channels import Channel
import json

def ws_receive(message):
    print('Message received')
    message.reply_channel.send({'text':message.content['text']})

    print('Message.content:', message.content)
    print(type(message.content))

    print('Message[text]:', message['text'])
    print(type(message['text']))

    payload = json.loads(message['text'])
    payload['reply_channel'] = message.content['reply_channel']

    # receive the message and send to chat.receive channel
    # with command as a filter
    Channel('chat.receive').send(payload)

def ws_connect(message):
    print('Connection estabslihed')
    print(message.content)
    message.reply_channel.send({'accept': True})

def ws_disconnect(message):
    print('Disconnecting')

def receive_chat_message(message):
    print('chat receive message with `send` command')
    print(message)
    print(message.content)

def another_command_chat_message(message):
    print('chat another command with `cmd` ')
    print(message)
    print(message.content)


来源: stackexchange

问:
JFrame/JPanel's Dimensions are Incorrect
So, right now whenever the Game class runs (which contains a MainPanel object), I get only a small box just big enough to fit the "minimize", "restore", and "close" buttons, rather than a 1280x720 screen. All of my other JFrame/JPanel combinations work except for this one, and I can't seem to figure out why. It is most likely just a small mistake, but I've been puzzled for far too long on this issue. Thanks!

```<code> public class Game extends JFrame{
    public static MainPanel mp = new MainPanel();
    public static void main( String[] args){
        Game g1 = new Game();
        g1.play();
    }

    public Game(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle( "Game" );
        setResizable( false );
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(1280, 720));
        setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        setUndecorated(false);

        mp.setBackground( Color.BLACK );
        mp.setPreferredSize( new Dimension(1280, 720) );
        mp.setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        mp.setLayout( null );
        mp.repaint();

        getContentPane().add( mp );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }

}
</code>```

and

```<code>public class MainPanel extends JPanel{
    private JPanel jp = new JPanel();
    public MainPanel(){
        jp.setBackground( Color.BLACK );
        jp.setPreferredSize( new Dimension(1280,720) );
        jp.setLayout( null );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                setVisible(true);
            }
        });
    }
}
</code>```

答:
Instead of using:

```<code>setPreferredSize(Dimension dimension);
</code>```

use:

```<code>setSize(int width, int height);
</code>```

setPreferredSize(Dimension dimension); don't work in JFrame and only work for components like JPanel.

I hope that helps!!

ContentLicense: CC BY-SA 3.0

Body:
So, right now whenever the Game class runs (which contains a MainPanel object), I get only a small box just big enough to fit the "minimize", "restore", and "close" buttons, rather than a 1280x720 screen. All of my other JFrame/JPanel combinations work except for this one, and I can't seem to figure out why. It is most likely just a small mistake, but I've been puzzled for far too long on this issue. Thanks!

 public class Game extends JFrame{
    public static MainPanel mp = new MainPanel();
    public static void main( String[] args){
        Game g1 = new Game();
        g1.play();
    }

    public Game(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle( "Game" );
        setResizable( false );
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(1280, 720));
        setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        setUndecorated(false);

        mp.setBackground( Color.BLACK );
        mp.setPreferredSize( new Dimension(1280, 720) );
        mp.setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        mp.setLayout( null );
        mp.repaint();

        getContentPane().add( mp );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }

}

and

public class MainPanel extends JPanel{
    private JPanel jp = new JPanel();
    public MainPanel(){
        jp.setBackground( Color.BLACK );
        jp.setPreferredSize( new Dimension(1280,720) );
        jp.setLayout( null );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                setVisible(true);
            }
        });
    }
}

Body:
Instead of using:

setPreferredSize(Dimension dimension);

use:

setSize(int width, int height);

setPreferredSize(Dimension dimension); don't work in JFrame and only work for components like JPanel.

I hope that helps!!


问:
python how to split http request line?
here is my request line example:

```<code>GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1
</code>```

I want to split this string and looking forward to result:

```<code>['GET', 'https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200', 'HTTP/1.1']
</code>```

thanks:-)

答:
You need to be a bit more precise with specifications like whether it's a string. But given that it is a string it should look like:

```<code>string = GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1

data = string.split();
</code>```

Of course if it is not a string you can't do that.

Title: python how to split http request line?

Body:
here is my request line example:

GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1

I want to split this string and looking forward to result:

['GET', 'https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200', 'HTTP/1.1']

thanks:-)

Body:
You need to be a bit more precise with specifications like whether it's a string. But given that it is a string it should look like:

string = GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1

data = string.split();

Of course if it is not a string you can't do that.


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答: The fastest would be to simply write a lot of if statements to compare them to determine their exact order. That will remove the overhead that any sorting algoritm has.

ContentLicense: CC BY-SA 2.5


问:
Determining homography from known planes?
I've got a question related to multiple view geometry.

I'm currently dealing with a problem where I have a number of images collected by a drone flying around an object of interest. This object is planar, and I am hoping to eventually stitch the images together.

Letting aside the classical way of identifying corresponding feature pairs, computing a homography and warping/blending, I want to see what information related to this task I can infer from prior known data.

Specifically, for each acquired image I know the following two things: I know the correspondence between the central point of my image and a point on the object of interest (on whose plane I would eventually want to warp my image). I also have a normal vector to the plane of each image.

So, knowing the centre point (in object-centric world coordinates) and the normal, I can derive the plane equation of each image.

My question is, knowing the plane equation of 2 images is it possible to compute a homography (or part of the transformation matrix, such as the rotation) between the 2?

I get the feeling that this may seem like a very straightforward/obvious answer to someone with deep knowledge of visual geometry but since it's not my strongest point I'd like to double check...

Thanks in advance!

答:
Your "normal" is the direction of the focal axis of the camera.

So, IIUC, you have a 3D point that projects on the image center in both images, which is another way of saying that (absent other information) the motion of the camera consists of the focal axis orbiting about a point on the ground plane, plus an arbitrary rotation about the focal axis, plus an arbitrary translation along the focal axis.

The motion has a non-zero baseline, therefore the transformation between images is generally not a homography. However, the portion of the image occupied by the ground plane does, of course, transform as a homography.

Such a motion is defined by 5 parameters, e.g. the 3 components of the rotation vector for the orbit, plus the the angle of rotation about the focal axis, plus the displacement along the focal axis. However the one point correspondence you have gives you only two equations.

It follows that you don't have enough information to constrain the homography between the images of the ground plane.


问:
Fetch data from a Core Controller in CodeIgniter
I'm working on a Social Network app.
I'm facing a problem in which I'm trying to get the name and username from a table called users in my database.
To be able to do this without accessing to all the controllers individually I had to create a Core controller with the name of MY_Controller.

Here is the problem(MY_Controller without the public $users):

```<code><?php

class MY_Controller extends CI_Controller
{

//public $users = array('username' => $this->input->post('username'));

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $this->users = $this->User_model->get_list();

        //Load Menu Library
        $this->load->library('menu');
        $this->pages = $this->menu->get_pages();

        // Brand/Logo
        $this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
        $this->brand = 'Some Name';
        $this->description = 'Some Description';
        $this->credits = 'https://blogpersonal.net/';
        $this->version = '1.1.1';
    }
}

class Admin_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_admin) {
            redirect('admin/login');
        }

        //some code here

    }
}

class Public_Controller extends MY_Controller{
    function __construct(){
        parent::__construct();

        //some code here

    }

}

class Social_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_member) {
            redirect('dashboard/login');
        }

        //some code here

    }
}
</code>```

As you can see I loaded the User_model using the __construct function to make it available and use it in all controllers.

I want to fetch data in a folder called templates.
views>templates>any document but when I try to fetch it in a view like this:

```<code>    <?php if($this->users) : ?>
        <li class="dropdown user user-menu">
          <!-- Menu Toggle Button -->
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <!-- The user image in the navbar-->
            <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
            <!-- hidden-xs hides the username on small devices so only the image appears. -->
            <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
          </a>

        </li>
    <?php endif; ?>
</code>```

THIS IS THE OLD ERROR. it shows me an error. Am I doing something wrong? Can somebody explain me how to fix it. This is the first time in which I'm unable to fetch data.

This is the result that I get:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: users

Filename: Templates/public.php

Line Number: 161

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 161 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File: C:\xampp\htdocs\codeigniter\application\controllers\Pages.php
  Line: 12 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Here is my model(User_model) in case you might need it:

```<code><?php

class User_model extends CI_MODEL
{

    function __construct()
    {
        parent::__construct();
        $this->table = 'users';
    }

    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        return $query->row();
    }

    public function add($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }

    public function login($username, $password)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->row()->id;
        } else {
            return false;
        }
    }
}
</code>```

Now with the changes that were suggested to me, it now shows a new error:

The New error:

A PHP Error was encountered

Severity: Notice Message:  Undefined index: username Filename:
  Templates/public.php Line Number: 168

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 168 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File:
  C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php
  Line: 13 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Now if a un-comment the public $users in the Core controller(MY_Controller) ,it shows me a new error as well:

New error with public $users out of __construct function

Fatal error: Constant expression contains invalid operations in
  C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php on line
  6 A PHP Error was encountered

Severity: Compile Error

Message: Constant expression contains invalid operations

Filename: core/MY_Controller.php

Line Number: 6

Backtrace:

Here is a picture in which I'm trying to get the data to:

Am I doing something wrong? thanks for helping.

Here is the view (public.php) file:

```<code><ul class="nav navbar-nav">
          <?php if(!$this->session->is_member) : ?>
          <li><?php echo anchor('public/users/login', 'Login'); ?></li>
          <li><?php echo anchor('public/users/register', 'Register'); ?></li>
          <?php else : ?>
            <!-- Messages: style can be found in dropdown.less-->
            <li class="dropdown messages-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-envelope-o"></i>
                <span class="label label-success">4</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 4 messages</li>
                <li>
                  <!-- inner menu: contains the messages -->
                  <ul class="menu">
                    <li><!-- start message -->
                      <a href="#">
                        <div class="pull-left">
                          <!-- User Image -->
                          <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                        </div>
                        <!-- Message title and timestamp -->
                        <h4>
                          Support Team
                          <small><i class="fa fa-clock-o"></i> 5 mins</small>
                        </h4>
                        <!-- The message -->
                        <p>Why not buy a new awesome theme?</p>
                      </a>
                    </li>
                    <!-- end message -->
                  </ul>
                  <!-- /.menu -->
                </li>
                <li class="footer"><a href="#">See All Messages</a></li>
              </ul>
            </li>
            <!-- /.messages-menu -->
            <!-- Notifications Menu -->
            <li class="dropdown notifications-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-bell-o"></i>
                <span class="label label-warning">10</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 10 notifications</li>
                <li>
                  <!-- Inner Menu: contains the notifications -->
                  <ul class="menu">
                    <li><!-- start notification -->
                      <a href="#">
                        <i class="fa fa-users text-aqua"></i> 5 new members joined today
                      </a>
                    </li>
                    <!-- end notification -->
                  </ul>
                </li>
                <li class="footer"><a href="#">View all</a></li>
              </ul>
            </li>
            <!-- Tasks Menu -->
            <li class="dropdown tasks-menu">
              <!-- Menu Toggle Button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-flag-o"></i>
                <span class="label label-danger">9</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 9 tasks</li>
                <li>
                  <!-- Inner menu: contains the tasks -->
                  <ul class="menu">
                    <li><!-- Task item -->
                      <a href="#">
                        <!-- Task title and progress text -->
                        <h3>
                          Design some buttons
                          <small class="pull-right">20%</small>
                        </h3>
                        <!-- The progress bar -->
                        <div class="progress xs">
                          <!-- Change the css width attribute to simulate progress -->
                          <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
                            <span class="sr-only">20% Complete</span>
                          </div>
                        </div>
                      </a>
                    </li>
                    <!-- end task item -->
                  </ul>
                </li>
                <li class="footer">
                  <a href="#">View all tasks</a>
                </li>
              </ul>
            </li>
            <!-- User Account Menu -->
            <?php if($this->users) : ?>
                <li class="dropdown user user-menu">
                  <!-- Menu Toggle Button -->
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                    <!-- The user image in the navbar-->
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
                    <!-- hidden-xs hides the username on small devices so only the image appears. -->
                    <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
                  </a>
                  <ul class="dropdown-menu">
                    <!-- The user image in the menu -->
                    <li class="user-header">
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                      <p><?php echo $this->users['name']; ?> - Web Developer<small>Member since Nov. 2012</small></p>
                    </li>
                    <!-- Menu Body -->
                    <li class="user-body">
                      <div class="row">
                        <div class="col-xs-4 text-center">
                          <a href="#">Followers</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Sales</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Friends</a>
                        </div>
                      </div>
                      <!-- /.row -->
                    </li>
                    <!-- Menu Footer-->
                    <li class="user-footer">
                      <div class="pull-left">
                        <a href="#" class="btn btn-default btn-flat">Profile</a>
                      </div>
                      <div class="pull-right">
                        <a href="<?php echo base_url(); ?>public/users/logout" class="btn btn-default btn-flat">Sign out</a>
                      </div>
                    </li>
                  </ul>
                </li>
            <?php endif; ?>
            <li>
                <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
            </li>
          <?php endif; ?>
          </ul>
</code>```

答:
You currently have this... and I am only showing snippets here...

```<code>class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $data['users'] = $this->User_model->get_list();

<<<<snip>>>>
</code>```

It was suggested that you turn your locally defined $data['users'] into a "Property"

So we now have two changes...

1 Declare the Property

2 Set the property.

```<code>class MY_Controller extends CI_Controller
{
    public $users = array(); // Add the property $user, safe def of an empty array

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        //$data['users'] = $this->User_model->get_list();
        // Give the property something to share.
        $this->users = $this->User_model->get_list();

    <<<<snip>>>>
</code>```

Now all of your controllers that extend your MY_Controller now have access to $this->users created in MY_Controller...

So you reference $this->users where you want to use it.

I'd suggest you read up on Classes, Properties, Methods and Inheritance to begin with. Usually that is enough to make you dangerous. It takes a little getting used to but its worth the effort...

Update:
In your controller that calls your View you would do
$data['users'] = $this->users;

And in your view, you now refer to it as $users->field_name just like before.
All we have done is define $users in your base class which is now accessible as $this->users so it's accessible to all your controllers / methods that extend the MY_Controller class.

Body:
I'm working on a Social Network app.
I'm facing a problem in which I'm trying to get the name and username from a table called users in my database.
To be able to do this without accessing to all the controllers individually I had to create a Core controller with the name of MY_Controller.

Here is the problem(MY_Controller without the public $users):

<?php

class MY_Controller extends CI_Controller
{

//public $users = array('username' => $this->input->post('username'));

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $this->users = $this->User_model->get_list();

        //Load Menu Library
        $this->load->library('menu');
        $this->pages = $this->menu->get_pages();

        // Brand/Logo
        $this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
        $this->brand = 'Some Name';
        $this->description = 'Some Description';
        $this->credits = 'https://blogpersonal.net/';
        $this->version = '1.1.1';
    }
}

class Admin_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_admin) {
            redirect('admin/login');
        }

        //some code here

    }
}

class Public_Controller extends MY_Controller{
    function __construct(){
        parent::__construct();

        //some code here

    }

}

class Social_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_member) {
            redirect('dashboard/login');
        }

        //some code here

    }
}

As you can see I loaded the User_model using the __construct function to make it available and use it in all controllers.

I want to fetch data in a folder called templates.
views>templates>any document but when I try to fetch it in a view like this:

    <?php if($this->users) : ?>

            <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">

            <?php echo $this->users['username']; ?>

    <?php endif; ?>

THIS IS THE OLD ERROR. it shows me an error. Am I doing something wrong? Can somebody explain me how to fix it. This is the first time in which I'm unable to fetch data.

This is the result that I get:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: users

Filename: Templates/public.php

Line Number: 161

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 161 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File: C:\xampp\htdocs\codeigniter\application\controllers\Pages.php
  Line: 12 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Here is my model(User_model) in case you might need it:

<?php

class User_model extends CI_MODEL
{

    function __construct()
    {
        parent::__construct();
        $this->table = 'users';
    }

    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        return $query->row();
    }

    public function add($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }

    public function login($username, $password)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->row()->id;
        } else {
            return false;
        }
    }
}

Now with the changes that were suggested to me, it now shows a new error:

The New error:

A PHP Error was encountered

Severity: Notice Message:  Undefined index: username Filename:
  Templates/public.php Line Number: 168

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 168 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File:
  C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php
  Line: 13 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Now if a un-comment the public $users in the Core controller(MY_Controller) ,it shows me a new error as well:

New error with public $users out of __construct function

Fatal error: Constant expression contains invalid operations in
  C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php on line
  6 A PHP Error was encountered

Severity: Compile Error

Message: Constant expression contains invalid operations

Filename: core/MY_Controller.php

Line Number: 6

Backtrace:

Here is a picture in which I'm trying to get the data to:

Am I doing something wrong? thanks for helping.

Here is the view (public.php) file:

          <?php if(!$this->session->is_member) : ?>

<?php echo anchor('public/users/login', 'Login'); ?>

<?php echo anchor('public/users/register', 'Register'); ?>

          <?php else : ?>

                4

You have 4 messages

                          <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">

                          Support Team
                           5 mins

Why not buy a new awesome theme?

See All Messages

                10

You have 10 notifications

                         5 new members joined today

View all

                9

You have 9 tasks

                          Design some buttons
                          20%

                            20% Complete

                  View all tasks

            <?php if($this->users) : ?>

                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">

                    <?php echo $this->users['username']; ?>

                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">

<?php echo $this->users['name']; ?> - Web DeveloperMember since Nov. 2012

                          Followers

                          Sales

                          Friends

                        Profile

                        <a href="<?php echo base_url(); ?>public/users/logout" class="btn btn-default btn-flat">Sign out

            <?php endif; ?>

          <?php endif; ?>

Body:
You currently have this... and I am only showing snippets here...

class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $data['users'] = $this->User_model->get_list();

<<<<snip>>>>

It was suggested that you turn your locally defined $data['users'] into a "Property"

So we now have two changes...

1 Declare the Property

2 Set the property.

class MY_Controller extends CI_Controller
{
    public $users = array(); // Add the property $user, safe def of an empty array

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        //$data['users'] = $this->User_model->get_list();
        // Give the property something to share.
        $this->users = $this->User_model->get_list();

    <<<<snip>>>>

Now all of your controllers that extend your MY_Controller now have access to $this->users created in MY_Controller...

So you reference $this->users where you want to use it.

I'd suggest you read up on Classes, Properties, Methods and Inheritance to begin with. Usually that is enough to make you dangerous. It takes a little getting used to but its worth the effort...

Update:
In your controller that calls your View you would do
$data['users'] = $this->users;

And in your view, you now refer to it as $users->field_name just like before.
All we have done is define $users in your base class which is now accessible as $this->users so it's accessible to all your controllers / methods that extend the MY_Controller class.


问:
How to Perform a Naieve Bayes Classification in Scikit from CSV
I am looking to predict whether someone is a smoker from several columns of demographic data stored in a csv, as well as their smoker status.

The columns used are:
Gender, Age,Race, ServedInMilitary, CountryofBirth, EducationLevel MaritalStatus, HouseholdIncome, FamilyIncome, ChildrenInHouse, QuantitiyofAlcohol, PerUnitTime, ShortnessOfBreath, Asthma, Exercise, Smoker, SmokedBefore, AgeStartedSmoking.

All columns have numeric, but not necessarily binary values. Could someone help me correct my code to take these factors into account when determining smoker status and then help me measure the accuracy of my classifier?

I have the following code from a similar question: how to Load CSV Data in scikit and using it for Naive Bayes Classification

```<code>target_names = np.array(['Positives','Negatives'])

# add columns to your data frame
data['is_train'] = np.random.uniform(0, 1, len(df)) <= 0.75
data['Type'] = pd.Factor(targets, target_names)
data['Targets'] = targets

# define training and test sets
train = data[data['is_train']==True]
test = data[data['is_train']==False]

trainTargets = np.array(train['Targets']).astype(int)
testTargets = np.array(test['Targets']).astype(int)

# columns you want to model
features = data.columns[0:7]

# call Gaussian Naive Bayesian class with default parameters
gnb = GaussianNB()

# train model
y_gnb = gnb.fit(train[features], trainTargets).predict(train[features])

#Predict Output
</code>```

答:
There seems to be a missing line here for the dataframe, but I will assume you have it. If you don't, then read your data using pandas.read_csv.

Also, your columns seem to have data that is both categorical and numerical. For example, the "SmokedBefore" column is likely 1/0 whereas your "Age" column is likely numbers such as 20 or 30.

This makes a difference, because in "SmokedBefore" the intent is not to say that 1>0. The intent is to say Yes/No. If your model assumes that higher (or lower) is better, then this will cause an issue. Therefore it is categorical and should not be treated like a numerical value. It is simply a tag to indicate whether someone has smoked before.

However, in "Age" the intent is to say that 30 is different than 20 by 10.  Therefore, it is numerical and should be treated as such.

To treat this, you will need to transform your categorical features into another set of binary features that will balance out this effect and handle it for you. This is called One Hot Encoding. Instead of 1/0 on your "SmokedBefore", it will become "is_1" and "is_0" with corresponding data. Like that, each column will have a 1 and a 0.

You can simply use the onehotencoder function provided in sklearn. Use the categorical_features argument to specify which columns have categorical features

Body:
I am looking to predict whether someone is a smoker from several columns of demographic data stored in a csv, as well as their smoker status.

The columns used are:
Gender, Age,Race, ServedInMilitary, CountryofBirth, EducationLevel MaritalStatus, HouseholdIncome, FamilyIncome, ChildrenInHouse, QuantitiyofAlcohol, PerUnitTime, ShortnessOfBreath, Asthma, Exercise, Smoker, SmokedBefore, AgeStartedSmoking.

All columns have numeric, but not necessarily binary values. Could someone help me correct my code to take these factors into account when determining smoker status and then help me measure the accuracy of my classifier?

I have the following code from a similar question: how to Load CSV Data in scikit and using it for Naive Bayes Classification

target_names = np.array(['Positives','Negatives'])

# add columns to your data frame
data['is_train'] = np.random.uniform(0, 1, len(df)) <= 0.75
data['Type'] = pd.Factor(targets, target_names)
data['Targets'] = targets

# define training and test sets
train = data[data['is_train']==True]
test = data[data['is_train']==False]

trainTargets = np.array(train['Targets']).astype(int)
testTargets = np.array(test['Targets']).astype(int)

# columns you want to model
features = data.columns[0:7]

# call Gaussian Naive Bayesian class with default parameters
gnb = GaussianNB()

# train model
y_gnb = gnb.fit(train[features], trainTargets).predict(train[features])

#Predict Output


问:
Trouble changing css `top` value to fixed element with js
Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.

html:

```<code><div id="red">
  <div id="blue"></div>
</div>
</code>```

css:

```<code>#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}
</code>```

js:

```<code>window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(document.body.scrollTop / 10));
  //console.log("yPos = " + yPos); //output is correct
  document.getElementById('blue').style.top = yPos + 'px';
  //document.getElementById('blue').setAttribute('top',yPos); //also tried this
});
</code>```

https://jsfiddle.net/akzx43yL/

Why isn't the top css value changing and how can I get it to do so? No jquery please.

答:
If you check your console, you will be see your console.log("yPos = " + yPos) is always 0 you most update your code as follow:

```<code>window.addEventListener('scroll', function() {
    var yPos = -(Math.floor(document.documentElement.scrollTop / 10));
    console.log("yPos = " + yPos);
    document.getElementById('blue').style.top = yPos + "px";
});
</code>```

Tip:

Ways to get srollTop (pure js):

```<code>var top  = window.pageYOffset || document.documentElement.scrollTop;
</code>```

Body:
Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.

html:

css:

#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}

js:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(document.body.scrollTop / 10));
  //console.log("yPos = " + yPos); //output is correct
  document.getElementById('blue').style.top = yPos + 'px';
  //document.getElementById('blue').setAttribute('top',yPos); //also tried this
});

https://jsfiddle.net/akzx43yL/

Why isn't the top css value changing and how can I get it to do so? No jquery please.

Body:
If you check your console, you will be see your console.log("yPos = " + yPos) is always 0 you most update your code as follow:

window.addEventListener('scroll', function() {
    var yPos = -(Math.floor(document.documentElement.scrollTop / 10));
    console.log("yPos = " + yPos);
    document.getElementById('blue').style.top = yPos + "px";
});

Tip:

Ways to get srollTop (pure js):

var top  = window.pageYOffset || document.documentElement.scrollTop;


问:
Outputting an image summary to Tensorboard
I'm trying to visualize the filters of a convolutional layer using this code, but cannot get the image to write to my summary file.  I have scalars that I am outputting with no issue, and I attempted to modify the code to add the image as follows

```<code>summary = tf.Summary()
summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward))
summary.value.add(tag='Perf/Length', simple_value=float(mean_length))
with tf.variable_scope(self.name + "/conv1", reuse=True):
    weights = tf.get_variable("weights")
    grid = put_kernels_on_grid(weights)
    image = tf.summary.image('conv1/weights', grid, max_outputs=1)
    summary.value.add(tag='conv1/weights', image=image)
self.summary_writer.add_summary(summary, episode_count)
</code>```

With only the scalars, this works fine, but adding the image gives the error

```<code>TypeError: Parameter to MergeFrom() must be instance of same class: expected Image got Tensor. for field Value.image
</code>```

I also tried adding the image summary directly by changing the code to

```<code>summary = tf.Summary()
summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward))
summary.value.add(tag='Perf/Length', simple_value=float(mean_length))
with tf.variable_scope(self.name + "/conv1", reuse=True):
    weights = tf.get_variable("weights")
    grid = put_kernels_on_grid(weights)
    image = tf.summary.image('conv1/weights', grid, max_outputs=1)
    self.summary_writer.add_summary(image, episode_count)
self.summary_writer.add_summary(summary, episode_count)
</code>```

But got the error

```<code>AttributeError: 'Tensor' object has no attribute 'value'
</code>```

What is the correct way to output my image to my summary file?

答:
<s>put_kernels_on_grid is returning a tensor; by 'image' I think the author just means that you can print it out to see what the kernel looks like.  Try using tf.summary.tensor_summary.</s>

Whoops, sorry.  I have been able to save a tensor as an image using the following:

```<code>import tensorflow as tf
import numpy as np

batch_xs = np.ones((100, 100, 1)) * 200
init = tf.constant(batch_xs, dtype=tf.uint8)
grid = tf.get_variable('var_name', dtype=tf.uint8, initializer=init)

encoded_image = tf.image.encode_jpeg(grid)

fwrite = tf.write_file("junk.jpeg", encoded_image)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    result = sess.run(fwrite)
</code>```

However tf.image.encode_jpeg still returns a tensor with DataType string, so tf.summary.image won't accept it.  The code you're working from predates TensorFlow 1.0, so it's definitely not going to work as written.

Hopefully this helps somewhat.

Body:
I'm trying to visualize the filters of a convolutional layer using this code, but cannot get the image to write to my summary file.  I have scalars that I am outputting with no issue, and I attempted to modify the code to add the image as follows

summary = tf.Summary()
summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward))
summary.value.add(tag='Perf/Length', simple_value=float(mean_length))
with tf.variable_scope(self.name + "/conv1", reuse=True):
    weights = tf.get_variable("weights")
    grid = put_kernels_on_grid(weights)
    image = tf.summary.image('conv1/weights', grid, max_outputs=1)
    summary.value.add(tag='conv1/weights', image=image)
self.summary_writer.add_summary(summary, episode_count)

With only the scalars, this works fine, but adding the image gives the error

TypeError: Parameter to MergeFrom() must be instance of same class: expected Image got Tensor. for field Value.image

I also tried adding the image summary directly by changing the code to

summary = tf.Summary()
summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward))
summary.value.add(tag='Perf/Length', simple_value=float(mean_length))
with tf.variable_scope(self.name + "/conv1", reuse=True):
    weights = tf.get_variable("weights")
    grid = put_kernels_on_grid(weights)
    image = tf.summary.image('conv1/weights', grid, max_outputs=1)
    self.summary_writer.add_summary(image, episode_count)
self.summary_writer.add_summary(summary, episode_count)

But got the error

AttributeError: 'Tensor' object has no attribute 'value'

What is the correct way to output my image to my summary file?

Body:
<s>put_kernels_on_grid is returning a tensor; by 'image' I think the author just means that you can print it out to see what the kernel looks like.  Try using tf.summary.tensor_summary.</s>

Whoops, sorry.  I have been able to save a tensor as an image using the following:

import tensorflow as tf
import numpy as np

batch_xs = np.ones((100, 100, 1)) * 200
init = tf.constant(batch_xs, dtype=tf.uint8)
grid = tf.get_variable('var_name', dtype=tf.uint8, initializer=init)

encoded_image = tf.image.encode_jpeg(grid)

fwrite = tf.write_file("junk.jpeg", encoded_image)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    result = sess.run(fwrite)

However tf.image.encode_jpeg still returns a tensor with DataType string, so tf.summary.image won't accept it.  The code you're working from predates TensorFlow 1.0, so it's definitely not going to work as written.

Hopefully this helps somewhat.


答:
Two step approach using str.partition and str.rpartition (could also be accomplished by a str.split and str.rsplit with a maxsplit=1 parameter each time):

```<code>line = 'GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1'
method, _, rest = line.partition(' ')
url, _, protocol = rest.rpartition(' ')
parsed_line = [method, url, protocol]
</code>```

Title: python how to split http request line?

Body:
Two step approach using str.partition and str.rpartition (could also be accomplished by a str.split and str.rsplit with a maxsplit=1 parameter each time):

line = 'GET https://example.com/hello?ageSelections=0&category=6000&productPeriodType=3&resourcePlace=resourcePlace AND 5089=5089-- PStU&twoCategory=6200 HTTP/1.1'
method, _, rest = line.partition(' ')
url, _, protocol = rest.rpartition(' ')
parsed_line = [method, url, protocol]


问:
HTML5 formatting on MacOS X? (preferably with TextMate)
Are there any editors or bundles available for MacOS X that support formatting of HTML5 documents? Tidy errors out on newer tags like canvas.</p>

答: Textmate has a bundle that will validate against the W3C validator - http://validator.w3.org/</p>


问:
Using another classes function in c#
im trying to be able to call the function from the dieclass and use the roll number in the matchplay class... is this possible?

```<code>public class DieClass
{
    public void DiceRoll(int min, int max)
    {
        Random random = new Random();

        int roll1 = random.Next(0, 6);
        int roll2 = random.Next(0, 6);
        int roll3 = random.Next(0, 6);
    }
}

public class MatchPlay
{
    public void Match()
    {
        DieClass.DiceRoll();

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");
        Console.WriteLine("Your first dice is [0]", roll1);
        Console.WriteLine("Your second dice is [0]", roll2);
        Console.WriteLine("Your third dice is [0]", roll3);
    }
}
</code>```

}

答:
There are a few things that need fixin':

Your DiceRoll method is an instance method, so you'd need to create an instance of the DiceClass class in order to use it.

The roll1, roll2, and roll3 variables are local to the method, so you won't be able to use them once the method completes. Instead, you might make them public properties of the class.

You don't need to instantiate a new Random every time the method is called (in fact this can lead to problems because Random is seeded with a value based on the system clock, so if your method is called very rapidly, it will produce the same numbers over and over). You can just make it static and instantiate it once.

Since you're taking in min and max arguments to the Roll method, shouldn't we use them? You currently have 0 and 6 hard-coded.

To use a format string, you need to use the curley braces ({}) instead of square brackets ([]).

Finally, from a naming convention point of view, you don't need the word Class as part of your class name, and you don't need Dice as part of the method name. This will simplify the amount of typing, and will still be very understandable.

What you might consider doing is creating a class that represents a single Die object, and give it a Roll() method and a Value property. Then the user can create as many as they like and keep them in a List:

```<code>public class Die
{
    public int Value { get; set; }

    // Make this static and instantiate it only once to avoid re-seeding issues
    private static readonly Random rnd = new Random();

    public Die()
    {
        Value = 1;
    }

    public void Roll()
    {
        // This method uses values 1-6 as a standard die
        Roll(1, 6);
    }

    public void Roll(int minValue, int maxValue)
    {
        Value = rnd.Next(minValue, maxValue + 1);
    }
}
</code>```

Now, you can use the Die class as follows:

```<code>public class MatchPlay
{
    public void Match()
    {
        // Add three Die objects to our list of dice
        List<Die> dice = new List<Die>
        {
            new Die(), new Die(), new Die()
        };

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");

        // Roll all dice
        dice.ForEach(d => d.Roll());

        Console.WriteLine("Your first dice is {0}", dice[0].Value);
        Console.WriteLine("Your second dice is {0}", dice[1].Value);
        Console.WriteLine("Your third dice is {0}", dice[2].Value);
    }
}
</code>```

Finally, we can kick off a match in our Main method:

```<code>private static void Main()
{
    MatchPlay game = new MatchPlay();
    game.Match();

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Title: Using another classes function in c#

Body:
im trying to be able to call the function from the dieclass and use the roll number in the matchplay class... is this possible?

public class DieClass
{
    public void DiceRoll(int min, int max)
    {
        Random random = new Random();

        int roll1 = random.Next(0, 6);
        int roll2 = random.Next(0, 6);
        int roll3 = random.Next(0, 6);
    }
}

public class MatchPlay
{
    public void Match()
    {
        DieClass.DiceRoll();

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");
        Console.WriteLine("Your first dice is [0]", roll1);
        Console.WriteLine("Your second dice is [0]", roll2);
        Console.WriteLine("Your third dice is [0]", roll3);
    }
}

}

Body:
There are a few things that need fixin':

Your DiceRoll method is an instance method, so you'd need to create an instance of the DiceClass class in order to use it.

The roll1, roll2, and roll3 variables are local to the method, so you won't be able to use them once the method completes. Instead, you might make them public properties of the class.

You don't need to instantiate a new Random every time the method is called (in fact this can lead to problems because Random is seeded with a value based on the system clock, so if your method is called very rapidly, it will produce the same numbers over and over). You can just make it static and instantiate it once.

Since you're taking in min and max arguments to the Roll method, shouldn't we use them? You currently have 0 and 6 hard-coded.

To use a format string, you need to use the curley braces ({}) instead of square brackets ([]).

Finally, from a naming convention point of view, you don't need the word Class as part of your class name, and you don't need Dice as part of the method name. This will simplify the amount of typing, and will still be very understandable.

What you might consider doing is creating a class that represents a single Die object, and give it a Roll() method and a Value property. Then the user can create as many as they like and keep them in a List:

public class Die
{
    public int Value { get; set; }

    // Make this static and instantiate it only once to avoid re-seeding issues
    private static readonly Random rnd = new Random();

    public Die()
    {
        Value = 1;
    }

    public void Roll()
    {
        // This method uses values 1-6 as a standard die
        Roll(1, 6);
    }

    public void Roll(int minValue, int maxValue)
    {
        Value = rnd.Next(minValue, maxValue + 1);
    }
}

Now, you can use the Die class as follows:

public class MatchPlay
{
    public void Match()
    {
        // Add three Die objects to our list of dice
        List<Die> dice = new List<Die>
        {
            new Die(), new Die(), new Die()
        };

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");

        // Roll all dice
        dice.ForEach(d => d.Roll());

        Console.WriteLine("Your first dice is {0}", dice[0].Value);
        Console.WriteLine("Your second dice is {0}", dice[1].Value);
        Console.WriteLine("Your third dice is {0}", dice[2].Value);
    }
}

Finally, we can kick off a match in our Main method:

private static void Main()
{
    MatchPlay game = new MatchPlay();
    game.Match();

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}


问:
Number of months between two dates
Is there a standard/common method/formula to calculate the number of months between two dates in R?

I am looking for something that is similar to MathWorks months function

答:
```<code>library(lubridate)
date1 = "1 April 1977"
date2 = "7 July 2017"

date1 = dmy(date1)
date2 = dmy(date2)
number_of_months = (year(date1) - year(date2)) * 12 + month(date1) - month(date2)
</code>```

Difference in months = 12 * difference in years + difference in months.

Following may need to be corrected using ifelse condition
  for the month subtractions

Title: Number of months between two dates

Body:
library(lubridate)
date1 = "1 April 1977"
date2 = "7 July 2017"

date1 = dmy(date1)
date2 = dmy(date2)
number_of_months = (year(date1) - year(date2)) * 12 + month(date1) - month(date2)

Difference in months = 12 * difference in years + difference in months.

Following may need to be corrected using ifelse condition
  for the month subtractions


问:
Excel: I need the VBA to Display Text When An Image Is Clicked
Can I ask the VBA code to display text when I click an image in Excel.

Thank you.

答:
That's really simple.

Right click the image and select assign macro

type activesheet.range("A1") = "my text" Within the sub

activesheet.range("A1") = "my text" This would create text my text on the active worksheet at Cell A1. You can play around and modify the values according to your needs.

You might want to consider search on Search Engine first before posting.


问:
Floating Action Button Not Rendering on API < 21
EDIT: I have updated to the latest Android Support library and am still receiving the error.

I know this question is redundant and I have researched all questions on SO, but I am still unable to determine why my FAB is not rendering on API 19. I understand there were considerable changes with API 21, and backwards compatibility is resolved with the AppCompat libraries. I also understand a critical change required is changing

```<code>        android:backgroundTint="@color/actionRed"
</code>```

to

```<code>            app:backgroundTint="@color/actionRed"
</code>```

which I have done.

It may have to do with my themes, as I am still learning the basics of Android themes and material design. Below is all of the relevant code depicting my libraries, XML, and the errors I am receiving:

Manifest (I was previously using NoActionBar theme, tried changing to Theme.AppCompat):

```<code>    <application
    android:name="android.support.multidex.MultiDexApplication"
    android:allowBackup="true"
    android:icon="@drawable/xxxxxxxx"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat">
</code>```

XML:

```<code>        <android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:visibility="visible"
        android:id="@+id/myFAB"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundTint="@color/actionRed"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginBottom="6dp"
        app:srcCompat="@drawable/ic_add_white_24dp"
        app:elevation="4dp"
        />
</code>```

App-Level Gradle:

```<code>android {
compileSdkVersion 26
buildToolsVersion '26.0.2'

defaultConfig {
    vectorDrawables.useSupportLibrary = true
    applicationId "xxxxxxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

    // Support library
compile "com.android.support:design:$supportLibVersion"
compile "com.android.support:cardview-v7:$supportLibVersion"
compile "com.android.support:support-v4:$supportLibVersion"
compile "com.android.support:appcompat-v7:$supportLibVersion"
</code>```

Root Gradle:

```<code>ext {
supportLibVersion = "27.0.2"
playServicesVersion = "11.4.2"
  }
</code>```

Drawable (is it because I am using my own FAB image? I want the red button with a white "+" sign):

Error:

```<code>1:28.981 3807-3807/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: xxxxxxxxxxxxx, PID: 3807
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troychuinard.fanpolls/com.troychuinard.fanpolls.HomeActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class android.support.design.widget.FloatingActionButton
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class android.support.design.widget.FloatingActionButton
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:620)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: java.lang.reflect.InvocationTargetException
                                                 at java.lang.reflect.Constructor.constructNative(Native Method)
                                                 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:594)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: java.lang.NoSuchMethodError: android.support.v4.content.res.ConfigurationHelper.getScreenWidthDp
                                                 at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:442)
                                                 at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:434)
                                                 at android.support.design.widget.FloatingActionButton$ShadowDelegateImpl.getRadius(FloatingActionButton.java:819)
                                                 at android.support.design.widget.FloatingActionButtonGingerbread.setBackgroundDrawable(FloatingActionButtonGingerbread.java:92)
                                                 at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:181)
                                                 at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:153)
                                                 at java.lang.reflect.Constructor.constructNative(Native Method)
                                                 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:594)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at
dalvik.system.NativeStart.main(Native Method)
12-06 23:41:28.981 569-870/? W/ActivityManager:   Force finishing
activity xxxxxxxxxxxx/.HomeActivity
</code>```

Any help, resources with material design, AppCompat, backwards compatibility, or any associated advice would be appreciated.

答:
You must replace:

```<code>android:src
</code>```

with:

```<code>app:srcCompat
</code>```

Body:
EDIT: I have updated to the latest Android Support library and am still receiving the error.

I know this question is redundant and I have researched all questions on SO, but I am still unable to determine why my FAB is not rendering on API 19. I understand there were considerable changes with API 21, and backwards compatibility is resolved with the AppCompat libraries. I also understand a critical change required is changing

        android:backgroundTint="@color/actionRed"

to

            app:backgroundTint="@color/actionRed"

which I have done.

It may have to do with my themes, as I am still learning the basics of Android themes and material design. Below is all of the relevant code depicting my libraries, XML, and the errors I am receiving:

Manifest (I was previously using NoActionBar theme, tried changing to Theme.AppCompat):

    <application
    android:name="android.support.multidex.MultiDexApplication"
    android:allowBackup="true"
    android:icon="@drawable/xxxxxxxx"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat">

XML:

        <android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:visibility="visible"
        android:id="@+id/myFAB"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundTint="@color/actionRed"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginBottom="6dp"
        app:srcCompat="@drawable/ic_add_white_24dp"
        app:elevation="4dp"
        />

App-Level Gradle:

android {
compileSdkVersion 26
buildToolsVersion '26.0.2'

defaultConfig {
    vectorDrawables.useSupportLibrary = true
    applicationId "xxxxxxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

    // Support library
compile "com.android.support:design:$supportLibVersion"
compile "com.android.support:cardview-v7:$supportLibVersion"
compile "com.android.support:support-v4:$supportLibVersion"
compile "com.android.support:appcompat-v7:$supportLibVersion"

Root Gradle:

ext {
supportLibVersion = "27.0.2"
playServicesVersion = "11.4.2"
  }

Drawable (is it because I am using my own FAB image? I want the red button with a white "+" sign):

Error:

1:28.981 3807-3807/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: xxxxxxxxxxxxx, PID: 3807
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troychuinard.fanpolls/com.troychuinard.fanpolls.HomeActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class android.support.design.widget.FloatingActionButton
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class android.support.design.widget.FloatingActionButton
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:620)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: java.lang.reflect.InvocationTargetException
                                                 at java.lang.reflect.Constructor.constructNative(Native Method)
                                                 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:594)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: java.lang.NoSuchMethodError: android.support.v4.content.res.ConfigurationHelper.getScreenWidthDp
                                                 at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:442)
                                                 at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:434)
                                                 at android.support.design.widget.FloatingActionButton$ShadowDelegateImpl.getRadius(FloatingActionButton.java:819)
                                                 at android.support.design.widget.FloatingActionButtonGingerbread.setBackgroundDrawable(FloatingActionButtonGingerbread.java:92)
                                                 at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:181)
                                                 at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:153)
                                                 at java.lang.reflect.Constructor.constructNative(Native Method)
                                                 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
                                                 at android.view.LayoutInflater.createView(LayoutInflater.java:594)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                 at com.troychuinard.fanpolls.HomeActivity.onCreate(HomeActivity.java:66)
                                                 at android.app.Activity.performCreate(Activity.java:5231)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at
dalvik.system.NativeStart.main(Native Method)
12-06 23:41:28.981 569-870/? W/ActivityManager:   Force finishing
activity xxxxxxxxxxxx/.HomeActivity

Any help, resources with material design, AppCompat, backwards compatibility, or any associated advice would be appreciated.

Body:
You must replace:

android:src

with:

app:srcCompat


问:
PyWinAuto - Application() multiple windows with same process id
I have application that have 5 windows (1 window, 4x pane) that have parent Desktop and they share the same  process_id.

When I try something like this:

```<code>for line in pywinauto.findwindows.find_windows(process=proc_id):
    print line  ### this will print all 5 handles of windows
    app = Application().connect(handle=line)   ### this will connect to specific handle
    app.top_window().set_focus()    ### this will set focus ONLY to one window and bring it to forward
    time.sleep(5)
</code>```

This FOR loop should bring forward one window every 5 seconds (1 control_type="Window" element and 4time control_type="Pane" elements) But this will only bring to forward one window and nothing else, and it will get 5x focus on it. No windows change is done.

thanks

答:
Because top_window() always chooses the first top window. What other could you expect from this method? Anyway we have plans to redesign or to remove it.

The right method for your purpose is app.windows():

```<code>for w in app.windows():
    print(w.window_text())
    w.set_focus()
</code>```

Note: the app.windows() returns the list of wrappers, so only listing .children() or .descendants() is possible without advanced implicit waits and more detailed search specifications.

Body:
I have application that have 5 windows (1 window, 4x pane) that have parent Desktop and they share the same  process_id.

When I try something like this:

for line in pywinauto.findwindows.find_windows(process=proc_id):
    print line  ### this will print all 5 handles of windows
    app = Application().connect(handle=line)   ### this will connect to specific handle
    app.top_window().set_focus()    ### this will set focus ONLY to one window and bring it to forward
    time.sleep(5)

This FOR loop should bring forward one window every 5 seconds (1 control_type="Window" element and 4time control_type="Pane" elements) But this will only bring to forward one window and nothing else, and it will get 5x focus on it. No windows change is done.

thanks

Body:
Because top_window() always chooses the first top window. What other could you expect from this method? Anyway we have plans to redesign or to remove it.

The right method for your purpose is app.windows():

for w in app.windows():
    print(w.window_text())
    w.set_focus()

Note: the app.windows() returns the list of wrappers, so only listing .children() or .descendants() is possible without advanced implicit waits and more detailed search specifications.