问:
PHP client Web socket to send messages
I have following code

index.php

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">

.panel{

margin-right: 3px;
}

.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    margin-right: 30%;
    margin-left: 30%;
    text-decoration: none;
    display: block;
    font-size: 16px;
    cursor: pointer;
    width:30%;
    height:40px;
    margin-top: 5px;

}
input[type=text]{
        width:100%;
        margin-top:5px;

    }

.chat_wrapper {
    width: 70%;
    height:472px;
    margin-right: auto;
    margin-left: auto;
    background: #3B5998;
    border: 1px solid #999999;
    padding: 10px;
    font: 14px 'lucida grande',tahoma,verdana,arial,sans-serif;
}
.chat_wrapper .message_box {
    background: #F7F7F7;
    height:350px;
        overflow: auto;
    padding: 10px 10px 20px 10px;
    border: 1px solid #999999;
}
.chat_wrapper  input{
    //padding: 2px 2px 2px 5px;
}
.system_msg{color: #BDBDBD;font-style: italic;}
.user_name{font-weight:bold;}
.user_message{color: #88B6E0;}

@media only screen and (max-width: 720px) {
    /* For mobile phones: */
    .chat_wrapper {
        width: 95%;
    height: 40%;
    }

    .button{ width:100%;
    margin-right:auto;
    margin-left:auto;
    height:40px;}

}

</style>
</head>
<body>
<?php
$colours = array('007AFF','FF7000','FF7000','15E25F','CFC700','CFC700','CF1100','CF00BE','F00');
$user_colour = array_rand($colours);
?>

<script src="jquery-3.1.1.js"></script>

<script language="javascript" type="text/javascript">
$(document).ready(function(){
    //create a new WebSocket object.
    var wsUri = "ws://localhost:9000/demo/server.php";
    websocket = new WebSocket(wsUri);

    websocket.onopen = function(ev) { // connection is open
        $('#message_box').append("<div class=\"system_msg\">Connected!</div>"); //notify user
    }

    $('#send-btn').click(function(){ //use clicks message send button
        var mymessage = $('#message').val(); //get message text
        var myname = $('#name').val(); //get user name

        if(myname == ""){ //empty name?
            alert("Enter your Name please!");
            return;
        }
        if(mymessage == ""){ //emtpy message?
            alert("Enter Some message Please!");
            return;
        }
        document.getElementById("name").style.visibility = "hidden";

        var objDiv = document.getElementById("message_box");
        objDiv.scrollTop = objDiv.scrollHeight;
        //prepare json data
        var msg = {
        message: mymessage,
        name: myname,
        color : '<?php echo $colours[$user_colour]; ?>'
        };
        //convert and send data to server
        websocket.send(JSON.stringify(msg));
    });

    //#### Message received from server?
    websocket.onmessage = function(ev) {
        var msg = JSON.parse(ev.data); //PHP sends Json data
        var type = msg.type; //message type
        var umsg = msg.message; //message text
        var uname = msg.name; //user name
        var ucolor = msg.color; //color

        if(type == 'usermsg')
        {
            $('#message_box').append("<div><span class=\"user_name\" style=\"color:#"+ucolor+"\">"+uname+"</span> : <span class=\"user_message\">"+umsg+"</span></div>");
        }
        if(type == 'system')
        {
            $('#message_box').append("<div class=\"system_msg\">"+umsg+"</div>");
        }

        $('#message').val(''); //reset text

        var objDiv = document.getElementById("message_box");
        objDiv.scrollTop = objDiv.scrollHeight;
    };

    websocket.onerror   = function(ev){$('#message_box').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");};
    websocket.onclose   = function(ev){$('#message_box').append("<div class=\"system_msg\">Connection Closed</div>");};
});

</script>
<div class="chat_wrapper">
<div class="message_box" id="message_box"></div>
<div class="panel">
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />

<input type="text" name="message" id="message" placeholder="Message" maxlength="80"
onkeydown = "if (event.keyCode == 13)document.getElementById('send-btn').click()"  />

</div>

<button id="send-btn" class=button>Send</button>

</div>

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

server.php

```<code><?php
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var

//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

//bind socket to specified host
socket_bind($socket, 0, $port);

//listen to port
socket_listen($socket);

//create & add listning socket to the list
$clients = array($socket);

//start endless loop, so that our script doesn't stop
while (true) {
    //manage multipal connections
    $changed = $clients;
    //returns the socket resources in $changed array
    socket_select($changed, $null, $null, 0, 10);

    //check for new socket
    if (in_array($socket, $changed)) {
        $socket_new = socket_accept($socket); //accpet new socket
        $clients[] = $socket_new; //add socket to client array

        $header = socket_read($socket_new, 1024); //read data sent by the socket
        perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake

        socket_getpeername($socket_new, $ip); //get ip address of connected socket
        $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
        send_message($response); //notify all users about new connection

        //make room for new socket
        $found_socket = array_search($socket, $changed);
        unset($changed[$found_socket]);
    }

    //loop through all connected sockets
    foreach ($changed as $changed_socket) {

        //check for any incomming data
        while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
        {
            $received_text = unmask($buf); //unmask data
            $tst_msg = json_decode($received_text); //json decode
            $user_name = $tst_msg->name; //sender name
            $user_message = $tst_msg->message; //message text
            $user_color = $tst_msg->color; //color

            //prepare data to be sent to client
            $response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
            send_message($response_text); //send data
            break 2; //exist this loop
        }

        $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
        if ($buf === false) { // check disconnected client
            // remove client for $clients array
            $found_socket = array_search($changed_socket, $clients);
            socket_getpeername($changed_socket, $ip);
            unset($clients[$found_socket]);

            //notify all users about disconnected connection
            $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
            send_message($response);
        }
    }
}
// close the listening socket
socket_close($socket);

function send_message($msg)
{
    global $clients;
    foreach($clients as $changed_socket)
    {
        @socket_write($changed_socket,$msg,strlen($msg));
    }
    return true;
}

//Unmask incoming framed message
function unmask($text) {
    $length = ord($text[1]) & 127;
    if($length == 126) {
        $masks = substr($text, 4, 4);
        $data = substr($text, 8);
    }
    elseif($length == 127) {
        $masks = substr($text, 10, 4);
        $data = substr($text, 14);
    }
    else {
        $masks = substr($text, 2, 4);
        $data = substr($text, 6);
    }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i%4];
    }
    return $text;
}

//Encode message for transfer to client.
function mask($text)
{
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)
        $header = pack('CCn', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCNN', $b1, 127, $length);
    return $header.$text;
}

//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
    $headers = array();
    $lines = preg_split("/\r\n/", $receved_header);
    foreach($lines as $line)
    {
        $line = chop($line);
        if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
        {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
    "Upgrade: websocket\r\n" .
    "Connection: Upgrade\r\n" .
    "WebSocket-Origin: $host\r\n" .
    "WebSocket-Location: ws://$host:$port/demo/shout.php\r\n".
    "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_conn,$upgrade,strlen($upgrade));
}
</code>```

The above code is working fine.But now i am looking for client side as php .can any provide me some example to make client websocket using php

UPDATES

I need to send byte array using php or javascript library through websocket

Update 2
I have found simple class of websocket but dont know how to use

https://github.com/paragi/PHP-websocket-client/blob/master/websocket_client.php

Also as per Niket Pathak answer i tried but getting following error

```<code><?php
$host = 'ws://echo.websocket.org';  // your websocket server
$port = 80;
$local = "http://localhost";  // url where this script run | Client
$data = '{"id": 2,"command": "server_info"}';  // data to be sent

$head = "GET / HTTP/1.1"."\r\n".
        "Upgrade: WebSocket"."\r\n".
        "Connection: Upgrade"."\r\n".
        "Origin: $local"."\r\n".
        "Host: $host"."\r\n".
        "Sec-WebSocket-Version: 13"."\r\n".
        "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
        "Content-Length: ".strlen($data)."\r\n"."\r\n";
// WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, hybi10Encode($data)) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);

var_dump(hybi10Decode($wsdata));

// hibi10 decoding of data
function hybi10Decode($data)
{
    $bytes = $data;
    $dataLength = '';
    $mask = '';
    $coded_data = '';
    $decodedData = '';
    $secondByte = sprintf('%08b', ord($bytes[1]));
    $masked = ($secondByte[0] == '1') ? true : false;
    $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
    if($masked === true)
    {
        if ($dataLength === 126) {
           $mask = substr($bytes, 4, 4);
           $coded_data = substr($bytes, 8);
        }
        elseif ($dataLength === 127) {
            $mask = substr($bytes, 10, 4);
            $coded_data = substr($bytes, 14);
        }
        else {
            $mask = substr($bytes, 2, 4);
            $coded_data = substr($bytes, 6);
        }
        for ($i = 0; $i < strlen($coded_data); $i++) {
            $decodedData .= $coded_data[$i] ^ $mask[$i % 4];
        }
    }
    else {
        if ($dataLength === 126) {
           $decodedData = substr($bytes, 4);
        }
        elseif ($dataLength === 127) {
            $decodedData = substr($bytes, 10);
        }
        else {
            $decodedData = substr($bytes, 2);
        }
    }

    return $decodedData;
}

// hibi10 encoding of data
function hybi10Encode($payload, $type = 'text', $masked = true) {
    $frameHead = array();
    $frame = '';
    $payloadLength = strlen($payload);

    switch ($type) {
        case 'text':
            // first byte indicates FIN, Text-Frame (10000001):
            $frameHead[0] = 129;
            break;
        case 'close':
            // first byte indicates FIN, Close Frame(10001000):
            $frameHead[0] = 136;
            break;
        case 'ping':
            // first byte indicates FIN, Ping frame (10001001):
            $frameHead[0] = 137;
            break;
        case 'pong':
            // first byte indicates FIN, Pong frame (10001010):
            $frameHead[0] = 138;
            break;
     }

    // set mask and payload length (using 1, 3 or 9 bytes)
    if ($payloadLength > 65535) {
        $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 255 : 127;
        for ($i = 0; $i < 8; $i++) {
            $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
        }

        // most significant bit MUST be 0 (close connection if frame too big)
        if ($frameHead[2] > 127) {
            $this->close(1004);
            return false;
        }
    } elseif ($payloadLength > 125) {
        $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 254 : 126;
        $frameHead[2] = bindec($payloadLengthBin[0]);
        $frameHead[3] = bindec($payloadLengthBin[1]);
    } else {
        $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
    }

    // convert frame-head to string:
    foreach (array_keys($frameHead) as $i) {
        $frameHead[$i] = chr($frameHead[$i]);
    }
    if ($masked === true) {
        // generate a random mask:
        $mask = array();
        for ($i = 0; $i < 4; $i++) {
            $mask[$i] = chr(rand(0, 255));
        }
        $frameHead = array_merge($frameHead, $mask);
    }
    $frame = implode('', $frameHead);
    // append payload to frame:
    for ($i = 0; $i < $payloadLength; $i++) {
        $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
    }

    return $frame;
}
</code>```

Error

Warning: fsockopen(): unable to connect to ws://echo.websocket.org:80
  (Unable to find the socket transport "ws" - did you forget to enable
  it when you configured PHP?) in G:\XAMPP\htdocs\a\server.php on line
  16

Warning: fwrite() expects parameter 1 to be resource, boolean given in
  G:\XAMPP\htdocs\a\server.php on line 17 error:407024:Unable to find
  the socket transport "ws" - did you forget to enable it when you
  configured PHP?

答:
My unswer NO. You can not fully use the websocket client logick, using only the server part(for example php). Because the server side know anything about the browser. Server - receives a request and returns a static result. All magic in the browser is javascript. Javascript can dynamically listen all user events, post a query to server and insert a response from the server to the page. Websocket can not work without javascript in browser.
This is WebSocket definition:

WebSockets are a bi-directional, full-duplex, persistent connection
  from a web browser to a server. Once a WebSocket connection is
  established the connection stays open until the client or server
  decides to close this connection. With this open connection, the
  client or server can send a message at any given time to the other.
  This makes web programming entirely event driven, not (just) user
  initiated. It is stateful. As well, at this time, a single running
  server application is aware of all connections, allowing you to
  communicate with any number of open connections at any given time.

The only thing you can do, is learn node js. It will allow you to write the browser (client) part and server part on one language - javascript. But however this will be different parts of application, and you will use different approaches, to program each part

Title: PHP client Web socket to send messages

Body:
I have following code

index.php

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

<?php
$colours = array('007AFF','FF7000','FF7000','15E25F','CFC700','CFC700','CF1100','CF00BE','F00');
$user_colour = array_rand($colours);
?>

<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />

<input type="text" name="message" id="message" placeholder="Message" maxlength="80"
onkeydown = "if (event.keyCode == 13)document.getElementById('send-btn').click()"  />

<button id="send-btn" class=button>Send</button>

server.php

<?php
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var

//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

//bind socket to specified host
socket_bind($socket, 0, $port);

//listen to port
socket_listen($socket);

//create & add listning socket to the list
$clients = array($socket);

//start endless loop, so that our script doesn't stop
while (true) {
    //manage multipal connections
    $changed = $clients;
    //returns the socket resources in $changed array
    socket_select($changed, $null, $null, 0, 10);

    //check for new socket
    if (in_array($socket, $changed)) {
        $socket_new = socket_accept($socket); //accpet new socket
        $clients[] = $socket_new; //add socket to client array

        $header = socket_read($socket_new, 1024); //read data sent by the socket
        perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake

        socket_getpeername($socket_new, $ip); //get ip address of connected socket
        $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
        send_message($response); //notify all users about new connection

        //make room for new socket
        $found_socket = array_search($socket, $changed);
        unset($changed[$found_socket]);
    }

    //loop through all connected sockets
    foreach ($changed as $changed_socket) {

        //check for any incomming data
        while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
        {
            $received_text = unmask($buf); //unmask data
            $tst_msg = json_decode($received_text); //json decode
            $user_name = $tst_msg->name; //sender name
            $user_message = $tst_msg->message; //message text
            $user_color = $tst_msg->color; //color

            //prepare data to be sent to client
            $response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
            send_message($response_text); //send data
            break 2; //exist this loop
        }

        $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
        if ($buf === false) { // check disconnected client
            // remove client for $clients array
            $found_socket = array_search($changed_socket, $clients);
            socket_getpeername($changed_socket, $ip);
            unset($clients[$found_socket]);

            //notify all users about disconnected connection
            $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
            send_message($response);
        }
    }
}
// close the listening socket
socket_close($socket);

function send_message($msg)
{
    global $clients;
    foreach($clients as $changed_socket)
    {
        @socket_write($changed_socket,$msg,strlen($msg));
    }
    return true;
}

//Unmask incoming framed message
function unmask($text) {
    $length = ord($text[1]) & 127;
    if($length == 126) {
        $masks = substr($text, 4, 4);
        $data = substr($text, 8);
    }
    elseif($length == 127) {
        $masks = substr($text, 10, 4);
        $data = substr($text, 14);
    }
    else {
        $masks = substr($text, 2, 4);
        $data = substr($text, 6);
    }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i%4];
    }
    return $text;
}

//Encode message for transfer to client.
function mask($text)
{
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)
        $header = pack('CCn', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCNN', $b1, 127, $length);
    return $header.$text;
}

//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
    $headers = array();
    $lines = preg_split("/\r\n/", $receved_header);
    foreach($lines as $line)
    {
        $line = chop($line);
        if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
        {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
    "Upgrade: websocket\r\n" .
    "Connection: Upgrade\r\n" .
    "WebSocket-Origin: $host\r\n" .
    "WebSocket-Location: ws://$host:$port/demo/shout.php\r\n".
    "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_conn,$upgrade,strlen($upgrade));
}

The above code is working fine.But now i am looking for client side as php .can any provide me some example to make client websocket using php

UPDATES

I need to send byte array using php or javascript library through websocket

Update 2
I have found simple class of websocket but dont know how to use

https://github.com/paragi/PHP-websocket-client/blob/master/websocket_client.php

Also as per Niket Pathak answer i tried but getting following error

<?php
$host = 'ws://echo.websocket.org';  // your websocket server
$port = 80;
$local = "http://localhost";  // url where this script run | Client
$data = '{"id": 2,"command": "server_info"}';  // data to be sent

$head = "GET / HTTP/1.1"."\r\n".
        "Upgrade: WebSocket"."\r\n".
        "Connection: Upgrade"."\r\n".
        "Origin: $local"."\r\n".
        "Host: $host"."\r\n".
        "Sec-WebSocket-Version: 13"."\r\n".
        "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
        "Content-Length: ".strlen($data)."\r\n"."\r\n";
// WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, hybi10Encode($data)) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);

var_dump(hybi10Decode($wsdata));

// hibi10 decoding of data
function hybi10Decode($data)
{
    $bytes = $data;
    $dataLength = '';
    $mask = '';
    $coded_data = '';
    $decodedData = '';
    $secondByte = sprintf('%08b', ord($bytes[1]));
    $masked = ($secondByte[0] == '1') ? true : false;
    $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
    if($masked === true)
    {
        if ($dataLength === 126) {
           $mask = substr($bytes, 4, 4);
           $coded_data = substr($bytes, 8);
        }
        elseif ($dataLength === 127) {
            $mask = substr($bytes, 10, 4);
            $coded_data = substr($bytes, 14);
        }
        else {
            $mask = substr($bytes, 2, 4);
            $coded_data = substr($bytes, 6);
        }
        for ($i = 0; $i < strlen($coded_data); $i++) {
            $decodedData .= $coded_data[$i] ^ $mask[$i % 4];
        }
    }
    else {
        if ($dataLength === 126) {
           $decodedData = substr($bytes, 4);
        }
        elseif ($dataLength === 127) {
            $decodedData = substr($bytes, 10);
        }
        else {
            $decodedData = substr($bytes, 2);
        }
    }

    return $decodedData;
}

// hibi10 encoding of data
function hybi10Encode($payload, $type = 'text', $masked = true) {
    $frameHead = array();
    $frame = '';
    $payloadLength = strlen($payload);

    switch ($type) {
        case 'text':
            // first byte indicates FIN, Text-Frame (10000001):
            $frameHead[0] = 129;
            break;
        case 'close':
            // first byte indicates FIN, Close Frame(10001000):
            $frameHead[0] = 136;
            break;
        case 'ping':
            // first byte indicates FIN, Ping frame (10001001):
            $frameHead[0] = 137;
            break;
        case 'pong':
            // first byte indicates FIN, Pong frame (10001010):
            $frameHead[0] = 138;
            break;
     }

    // set mask and payload length (using 1, 3 or 9 bytes)
    if ($payloadLength > 65535) {
        $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 255 : 127;
        for ($i = 0; $i < 8; $i++) {
            $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
        }

        // most significant bit MUST be 0 (close connection if frame too big)
        if ($frameHead[2] > 127) {
            $this->close(1004);
            return false;
        }
    } elseif ($payloadLength > 125) {
        $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 254 : 126;
        $frameHead[2] = bindec($payloadLengthBin[0]);
        $frameHead[3] = bindec($payloadLengthBin[1]);
    } else {
        $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
    }

    // convert frame-head to string:
    foreach (array_keys($frameHead) as $i) {
        $frameHead[$i] = chr($frameHead[$i]);
    }
    if ($masked === true) {
        // generate a random mask:
        $mask = array();
        for ($i = 0; $i < 4; $i++) {
            $mask[$i] = chr(rand(0, 255));
        }
        $frameHead = array_merge($frameHead, $mask);
    }
    $frame = implode('', $frameHead);
    // append payload to frame:
    for ($i = 0; $i < $payloadLength; $i++) {
        $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
    }

    return $frame;
}

Error

Warning: fsockopen(): unable to connect to ws://echo.websocket.org:80
  (Unable to find the socket transport "ws" - did you forget to enable
  it when you configured PHP?) in G:\XAMPP\htdocs\a\server.php on line
  16

Warning: fwrite() expects parameter 1 to be resource, boolean given in
  G:\XAMPP\htdocs\a\server.php on line 17 error:407024:Unable to find
  the socket transport "ws" - did you forget to enable it when you
  configured PHP?


来源: stackexchange

问:
Display an image in real device from a computer in Android Application
I want to load an image from an external folder of my system to my android application. I use the following code, but the image is not displaying. When I debugged it, the Bitmap object 'bitmap' is shown as null. How can I solve this problem?

```<code>      ImageView img=(ImageView)findViewById(R.id.myImage);
      String fname="C:/Users/Public/Pictures/Garden.jpg";
      Bitmap bitmap = BitmapFactory.decodeFile(fname);
      img.setImageBitmap(bitmap);
</code>```

My actual need is my andorid application (on real device) should display some images which is stored into one computer. The admin of this application will upload some images to a specific folder in that computer. And the android application will access these images using IP address, and will display these images. If these images should be pushed to sdcard path, then how can i do it at runtime?

Please help me..

Thank you to all..

答:
An "external folder"? What is that? Android only has access to its internal file system (i.e. the internal storage, and the SD card, and whatever else you may have mounted via the Linux operating system). Using a Windows path is definitely never going to work. Where is that data supposed to be coming from?

You need to use a proper UNIX-style path that either points to the phone's internal storage, or the SD card, and the path needs to be accessible by your application.

ContentLicense: CC BY-SA 2.5

Body:
I want to load an image from an external folder of my system to my android application. I use the following code, but the image is not displaying. When I debugged it, the Bitmap object 'bitmap' is shown as null. How can I solve this problem?

      ImageView img=(ImageView)findViewById(R.id.myImage);
      String fname="C:/Users/Public/Pictures/Garden.jpg";
      Bitmap bitmap = BitmapFactory.decodeFile(fname);
      img.setImageBitmap(bitmap);

My actual need is my andorid application (on real device) should display some images which is stored into one computer. The admin of this application will upload some images to a specific folder in that computer. And the android application will access these images using IP address, and will display these images. If these images should be pushed to sdcard path, then how can i do it at runtime?

Please help me..

Thank you to all..


ContentLicense: CC BY-SA 3.0

Title: Why does scipy.optimize.linprog return a solution that does not satisfy constraints?

Body:
Am I doing something wrong or it is a bug?

c = np.array([-1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
A_ub = np.array([[   1., -724.,  911., -551., -555., -896.,  478.,  -80., -293.],
       [   1.,  566.,   42.,  937.,  233.,  883.,  392., -909.,   57.],
       [   1., -208., -894.,  539.,  321.,  532., -924.,  942.,   55.],
       [   1.,  857., -859.,   83.,  462., -265., -971.,  826.,  482.],
       [   1.,  314., -424.,  245., -424.,  194., -443., -104., -429.],
       [   1.,  540.,  679.,  361.,  149., -827.,  876.,  633.,  302.],
       [   0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.],
       [   0.,    1.,    0.,    0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    1.,    0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    1.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    1.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    1.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    1.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    1.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.,    1.]])
b_ub = np.array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
                 0., 0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
A_eq = np.array([[ 0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
b_eq = np.array([[ 1.]])
bounds = [(None, None), (None, None), (None, None), (None, None), (None, None),
         (None, None), (None, None), (None, None), (None, None)]

soln = scipy.optimize.linprog(c, A_ub, b_ub, A_eq, b_eq, bounds)
print(soln)
print(A_ub.dot(soln['x']) <= b_ub)
print(A_ub.dot(soln['x']) - b_ub)
print(abs(A_eq.dot(soln['x']) - b_eq))](url)

outputs

     fun: 39.866871820032244
 message: 'Optimization terminated successfully.'
     nit: 19
   slack: array([   0.   ,    0.   ,    0.   ,    0.   ,  365.161,    0.   ,
          0.   ,    0.   ,    0.   ,    0.   ,    0.167,    0.61 ,
          0.115,    0.518,    1.   ,    1.   ,    1.   ,    1.   ,
          0.833,    0.39 ,    0.885,    0.482])
  status: 0
 success: True
       x: array([-39.812,  -0.281,  -0.625,   0.   ,  -0.031,  -0.125,   0.625,
         0.312,   0.406])

[ True  True False False  True False False False  True False False  True
  True  True  True  True  True  True  True  True  True  True]
[-121.5   -358.812  240.125  121.781 -357.781  350.656    0.281    0.625
    0.       0.031    0.125   -0.625   -0.312   -0.406   -1.281   -1.625
   -1.      -1.031   -1.125   -0.375   -0.688   -0.594]
[[ 0.719]]

From middle part of A_ub that must be clear that solution must satisfy soln['x'][1:] > 0, however, it is clearly not satisfied!

Am I doing something wrong?

Python 3.6
scipy==0.18.1

Body:
Yes, it looks like a bug. I usually recommend people to use alternatives to scipy's linprog because:

bad robustness

bad performance (especially on big sparse problems)

does not seem to be maintained anymore; not much progress despite open issues

There is currently an interior-point-based solver in development for scipy, which solves this problem correctly. Of course you can also use the much better alternatives available (e.g. through cvxpy).

Here is some code, which shows, that cvxpy's default solver (for these kind of problems; ECOS can solve a much broader class of problems!) ECOS and the not yet incorporated IPM-solver solve it, while linprog-simplex struggles. Keep in mind, that the code will not run on vanilla-scipy as method='interior-point' is missing:

import numpy as np
from scipy.optimize import linprog

c = np.array([-1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
A_ub = np.array([[   1., -724.,  911., -551., -555., -896.,  478.,  -80., -293.],
       [   1.,  566.,   42.,  937.,  233.,  883.,  392., -909.,   57.],
       [   1., -208., -894.,  539.,  321.,  532., -924.,  942.,   55.],
       [   1.,  857., -859.,   83.,  462., -265., -971.,  826.,  482.],
       [   1.,  314., -424.,  245., -424.,  194., -443., -104., -429.],
       [   1.,  540.,  679.,  361.,  149., -827.,  876.,  633.,  302.],
       [   0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.,   -0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -0.,   -1.],
       [   0.,    1.,    0.,    0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    1.,    0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    1.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    1.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    1.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    1.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    1.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.,    1.]])
b_ub = np.array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
                 0., 0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
A_eq = np.array([[ 0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
b_eq = np.array([[ 1.]])
bounds = [(None, None), (None, None), (None, None), (None, None), (None, None),
         (None, None), (None, None), (None, None), (None, None)]

soln = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method='simplex')
print('linprog: ', soln)

soln = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method='interior-point')
print('linprog IPM: ', soln)

from cvxpy import *
x = Variable(A_eq.shape[1])
constraints = []
constraints.append(A_ub*x <= b_ub)
constraints.append(A_eq*x == b_eq)
objective = Minimize(c*x)
problem = Problem(objective, constraints)
problem.solve(verbose=True)
print(np.round(x.value, 2))
print(problem.value)

Output:

linprog:       fun: 39.866871820032244
 message: 'Optimization terminated successfully.'
     nit: 19
   slack: array([  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   3.65161351e+02,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   1.66922982e-01,   6.10104031e-01,
         1.14953670e-01,   5.18298274e-01,   1.00000000e+00,
         1.00000000e+00,   1.00000000e+00,   1.00000000e+00,
         8.33077018e-01,   3.89895969e-01,   8.85046330e-01,
         4.81701726e-01])
  status: 0
 success: True
       x: array([ -3.98125000e+01,  -2.81250000e-01,  -6.25000000e-01,
         0.00000000e+00,  -3.12500000e-02,  -1.25000000e-01,
         6.25000000e-01,   3.12500000e-01,   4.06250000e-01])
linprog IPM:       con: array([ -3.93646007e-08])
     fun: 108.56853369114262
 message: 'Optimization terminated successfully.'
     nit: 9
   slack: array([  1.23442489e+02,  -1.13909794e-05,  -7.46066462e-07,
         3.12539380e+02,   2.20799190e+02,  -1.41898576e-05,
         2.48742446e-09,   3.71114180e-01,   1.07937459e-09,
         1.33093066e-08,   3.70892271e-01,   2.03637625e-09,
         2.57993546e-01,   2.36290348e-08,   9.99999998e-01,
         6.28885820e-01,   9.99999999e-01,   9.99999987e-01,
         6.29107729e-01,   9.99999998e-01,   7.42006454e-01,
         9.99999976e-01])
  status: 0
 success: True
       x: array([ -1.08568534e+02,   2.48742446e-09,   3.71114180e-01,
         1.07937459e-09,   1.33093066e-08,   3.70892271e-01,
         2.03637625e-09,   2.57993546e-01,   2.36290348e-08])

ECOS 2.0.4 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS

It     pcost       dcost      gap   pres   dres    k/t    mu     step   sigma     IR    |   BT
 0  +2.934e+01  -6.533e+02  +2e+03  3e-01  5e-01  1e+00  8e+01    ---    ---    1  1  - |  -  -
 1  +9.527e+01  -1.952e+02  +9e+02  1e-01  2e-01  8e+00  4e+01  0.6128  2e-01   1  1  1 |  0  0
 2  +9.281e+01  -1.256e+01  +3e+02  4e-02  6e-02  5e+00  1e+01  0.6888  1e-01   1  1  1 |  0  0
 3  +1.004e+02  +6.363e+01  +1e+02  2e-02  2e-02  2e+00  5e+00  0.7367  1e-01   1  1  1 |  0  0
 4  +1.075e+02  +9.684e+01  +3e+01  5e-03  6e-03  9e-01  1e+00  0.8307  1e-01   1  1  1 |  0  0
 5  +1.086e+02  +1.084e+02  +4e-01  6e-05  7e-05  1e-02  2e-02  0.9872  1e-04   1  1  1 |  0  0
 6  +1.086e+02  +1.086e+02  +5e-03  7e-07  8e-07  1e-04  2e-04  0.9890  1e-04   1  1  1 |  0  0
 7  +1.086e+02  +1.086e+02  +5e-05  8e-09  9e-09  1e-06  2e-06  0.9890  1e-04   1  0  0 |  0  0
 8  +1.086e+02  +1.086e+02  +6e-07  8e-11  1e-10  2e-08  3e-08  0.9890  1e-04   1  0  0 |  0  0

OPTIMAL (within feastol=9.6e-11, reltol=5.2e-09, abstol=5.6e-07).
Runtime: 0.000424 seconds.

[[-108.57]
 [  -0.  ]
 [   0.37]
 [  -0.  ]
 [   0.  ]
 [   0.37]
 [  -0.  ]
 [   0.26]
 [   0.  ]]
108.56853545568384


问:
Using a different class in Android Studio
HOw do you use a method in a different class from the one you're calling it from in Android Studio? I have the following main class:

```<code>package com.example.bluebus;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BeeperControl test = new BeeperControl();
        //test.test();
        //test.test();*/

    }
}
</code>```

and in the same folder I have the following BeeperControl class:

```<code>import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by Arthur on 1/7/2017.
 */

public class BeeperControl extends AppCompatActivity {
        /*private final ScheduledExecutorService scheduler =
                Executors.newScheduledThreadPool(1);*/
        final TextView text = (TextView) findViewById(R.id.text);
    /*
        public void beepForAnHour() {
            final Runnable beeper = new Runnable() {
                public void run() {
                    text.setText("Hello!");
                }
            };
            final ScheduledFuture<?> beeperHandle =
                    scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
        }*/
        public void test(){
            text.setText("Who are you?");
        }
}
</code>```

When written as is, the app works fine. However, when I uncomment test.test(), the app keeps closing when I try to run it in an emulator. From what I've seen, it may be a problem with updating the manifest, but I'm not sure how to fix it. Any help will be appreciated!

答:
Have the method in the class return the value, your findbyid will return null as it is out of scope.

For example:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

public class MainActivity extends AppCompatActivity {

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BeeperControl test = new BeeperControl();
        TextView text = (TextView) findViewById(R.id.text);
        text.setText(test.test());
        //test.test();*/

    }
}
</code>```

Your Class:

```<code>import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by Arthur on 1/7/2017.
 */

public class BeeperControl extends AppCompatActivity {
        /*private final ScheduledExecutorService scheduler =
                Executors.newScheduledThreadPool(1);*/
        /* final TextView text = (TextView) findViewById(R.id.text);^/
    /*
        public void beepForAnHour() {
            final Runnable beeper = new Runnable() {
                public void run() {
                    text.setText("Hello!");
                }
            };
            final ScheduledFuture<?> beeperHandle =
                    scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
        }*/
        public string test(){
            return ("Who are you?");
        }
}
</code>```

This probably doesn't assist in your use of the class in whatever context it is used, if you pass text by reference to test() that may do it for you.
R/
Prescott ...

Body:
HOw do you use a method in a different class from the one you're calling it from in Android Studio? I have the following main class:

package com.example.bluebus;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BeeperControl test = new BeeperControl();
        //test.test();
        //test.test();*/

    }
}

and in the same folder I have the following BeeperControl class:

import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by Arthur on 1/7/2017.
 */

public class BeeperControl extends AppCompatActivity {
        /*private final ScheduledExecutorService scheduler =
                Executors.newScheduledThreadPool(1);*/
        final TextView text = (TextView) findViewById(R.id.text);
    /*
        public void beepForAnHour() {
            final Runnable beeper = new Runnable() {
                public void run() {
                    text.setText("Hello!");
                }
            };
            final ScheduledFuture<?> beeperHandle =
                    scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
        }*/
        public void test(){
            text.setText("Who are you?");
        }
}

When written as is, the app works fine. However, when I uncomment test.test(), the app keeps closing when I try to run it in an emulator. From what I've seen, it may be a problem with updating the manifest, but I'm not sure how to fix it. Any help will be appreciated!

Body:
Have the method in the class return the value, your findbyid will return null as it is out of scope.

For example:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

public class MainActivity extends AppCompatActivity {

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BeeperControl test = new BeeperControl();
        TextView text = (TextView) findViewById(R.id.text);
        text.setText(test.test());
        //test.test();*/

    }
}

Your Class:

import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by Arthur on 1/7/2017.
 */

public class BeeperControl extends AppCompatActivity {
        /*private final ScheduledExecutorService scheduler =
                Executors.newScheduledThreadPool(1);*/
        /* final TextView text = (TextView) findViewById(R.id.text);^/
    /*
        public void beepForAnHour() {
            final Runnable beeper = new Runnable() {
                public void run() {
                    text.setText("Hello!");
                }
            };
            final ScheduledFuture<?> beeperHandle =
                    scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
        }*/
        public string test(){
            return ("Who are you?");
        }
}

This probably doesn't assist in your use of the class in whatever context it is used, if you pass text by reference to test() that may do it for you.
R/
Prescott ...


问:
Gesture-driven animation between frames
I am trying to create an interactive animation between a thumbnail frame and a fullscreen frame. Panning upwards could cause the frame to go grow in both dimensions (until reaching fullscreen) while panning downwards does the opposite. Very similar to how Youtube animates their video player.

I tried using a UIPanGestureRecognizer, and a POPSpringAnimation that activates when the recognizers state is UIGestureRecognizerStateEnded, like so:

```<code>- (void)didPan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer translationInView:self.view.superview];
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + point.y);
    [recognizer setTranslation:CGPointZero inView:self.view.superview];
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        CGPoint velocity = [recognizer velocityInView:self.view.superview];
        // Initaite POPSpringAnimation using velocity and target frame
        // either fullscreen or thumbnail
    }
}
</code>```

The effect of this is that the view's center gets updated while panning, but its size will only start changing after you stop panning. I do not want to manually resize the frame in didPan: without knowing at what ratio to do it.

How can I create a panning-driven animation that simply goes from frame A to frame B?

This framework does almost the same thing, but the animation is not interactive. Same thing goes for this answer.

答:
I suggest using a UIViewPropertyAnimator, a class addd in iOS 10. It lets you pretty easily pause, reverse, or scrub animations back and forth.

I have a demo project on GitHub (Written in Swift, which might be harder for you to follow, since you're using Objective-C:

https://github.com/DuncanMC/UIViewPropertyAnimator-test

The class is actually pretty easy to use. You should be able to figure it out from the docs, and the sample project could at least serve as a roadmap on the APIs to use even if you can't follow the code line-by-line

Title: Gesture-driven animation between frames

Body:
I am trying to create an interactive animation between a thumbnail frame and a fullscreen frame. Panning upwards could cause the frame to go grow in both dimensions (until reaching fullscreen) while panning downwards does the opposite. Very similar to how Youtube animates their video player.

I tried using a UIPanGestureRecognizer, and a POPSpringAnimation that activates when the recognizers state is UIGestureRecognizerStateEnded, like so:

- (void)didPan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer translationInView:self.view.superview];
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + point.y);
    [recognizer setTranslation:CGPointZero inView:self.view.superview];
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        CGPoint velocity = [recognizer velocityInView:self.view.superview];
        // Initaite POPSpringAnimation using velocity and target frame
        // either fullscreen or thumbnail
    }
}

The effect of this is that the view's center gets updated while panning, but its size will only start changing after you stop panning. I do not want to manually resize the frame in didPan: without knowing at what ratio to do it.

How can I create a panning-driven animation that simply goes from frame A to frame B?

This framework does almost the same thing, but the animation is not interactive. Same thing goes for this answer.


问:
How to set channel gain in OpenAL?
I tried

```<code>alBufferf (myChannelId, AL_MAX_GAIN (and AL_GAIN), volumeValue);
</code>```

and got error 0xA002.

答:
0xA002 is an ILLEGAL ENUM ERROR in linux.

You got that because it's impossible to modify the gain of a buffer.  There's no such thing.

What you can do is set the AL_GAIN attribute either to the listener (applying it to all sources in the current context) or to a particular source.

Title: How to set channel gain in OpenAL?

Body:
I tried

alBufferf (myChannelId, AL_MAX_GAIN (and AL_GAIN), volumeValue);

and got error 0xA002.


答:
This will give you an idea. I have tested this on ORACLE and it is working fine,

```<code>WITH CUS_DET AS (
    SELECT *
    FROM INTERACTIONS
    WHERE ACTION = 'became_customer'
)
SELECT INTERACTIONS.USER_NAME
  , SUM(CASE
    WHEN (CUS_DET.ACTION_TIMESTAMP IS NULL
            OR INTERACTIONS.ACTION_TIMESTAMP < CUS_DET.ACTION_TIMESTAMP)
    THEN 1
    ELSE 0
  END) BEF
  , SUM(CASE
    WHEN INTERACTIONS.ACTION_TIMESTAMP > CUS_DET.ACTION_TIMESTAMP
    THEN 1
    ELSE 0
  END) AFT
FROM INTERACTIONS
  LEFT OUTER JOIN CUS_DET
    ON INTERACTIONS.USER_NAME = CUS_DET.USER_NAME
GROUP BY INTERACTIONS.USER_NAME;
</code>```

Title: Can I use a variable condition in a CASE statement?

Body:
Picture this table of interactions a business has with people:

+-----------+---------------------+-----------------+
| user_name | action_timestamp    | action          |
+-----------+---------------------+-----------------+
| john      | 2017-01-01 10:00:00 | phone_call      |
+-----------+---------------------+-----------------+
| john      | 2017-01-02 12:00:00 | became_customer |
+-----------+---------------------+-----------------+
| john      | 2017-01-03 14:00:00 | phone_call      |
+-----------+---------------------+-----------------+
| jane      | 2016-08-06 10:00:00 | phone_call      |
+-----------+---------------------+-----------------+
| jane      | 2016-08-06 11:00:00 | phone_call      |
+-----------+---------------------+-----------------+
| jane      | 2016-08-06 12:00:00 | became_customer |
+-----------+---------------------+-----------------+
| tony      | 2016-12-01 15:00:00 | phone_call      |
+-----------+---------------------+-----------------+

I want to get to something like this:

+-----------+---------------+-------------+---------------------+------------------------------+-----------------------------+
| user_name | total_actions | is_customer | became_customer     | interactions_before_customer | interactions_after_customer |
+-----------+---------------+-------------+---------------------+------------------------------+-----------------------------+
| john      | 3             | TRUE        | 2017-01-02 12:00:00 | 1                            | 1                           |
+-----------+---------------+-------------+---------------------+------------------------------+-----------------------------+
| jane      | 3             | TRUE        | 2016-08-06 12:00:00 | 2                            | 0                           |
+-----------+---------------+-------------+---------------------+------------------------------+-----------------------------+
| tony      | 1             | FALSE       | NULL                | 1                            | 0                           |
+-----------+---------------+-------------+---------------------+------------------------------+-----------------------------+

The first 4 columns are trivial with some grouping and CASEs, but I don't know how to do columns 5 and 6 (interactions before customer and interactions after customer) since the case is predicated on the result of a previous column, and needs to vary between rows.

Is this simpler than it appears? If anybody cares I don't work at a call center, it's just a much simpler analogue to what I'm trying to do ;)

Body:
This will give you an idea. I have tested this on ORACLE and it is working fine,

WITH CUS_DET AS (
    SELECT *
    FROM INTERACTIONS
    WHERE ACTION = 'became_customer'
)
SELECT INTERACTIONS.USER_NAME
  , SUM(CASE
    WHEN (CUS_DET.ACTION_TIMESTAMP IS NULL
            OR INTERACTIONS.ACTION_TIMESTAMP < CUS_DET.ACTION_TIMESTAMP)
    THEN 1
    ELSE 0
  END) BEF
  , SUM(CASE
    WHEN INTERACTIONS.ACTION_TIMESTAMP > CUS_DET.ACTION_TIMESTAMP
    THEN 1
    ELSE 0
  END) AFT
FROM INTERACTIONS
  LEFT OUTER JOIN CUS_DET
    ON INTERACTIONS.USER_NAME = CUS_DET.USER_NAME
GROUP BY INTERACTIONS.USER_NAME;


问:
How does the logstash kv{} filter plugin work?
I wanted to extract url query params and as per this forum answer I was able to do it with kv{}

But I want to understand how this works.

Here is my string: param1=val1&param2=val2&adv=val3&param3=val4&param4=val5

Now I have that field extracted in logstash as uri_query.

So then I use kv like this:

```<code>kv {
  source => "uriQuery"
  field_split => "&"
  prefix => "query_"
}
</code>```

And I get fields for each query param:

```<code>query_param1 val1
query_param2 val2
etc
</code>```

But what I don't understand is how it knows to strip out and break on the "=". Is that like the default token for kv's key=value syntax or something?

答:
Yep. = is the default token for kv.

Here is the documentation about that parameter for the kv plugin which is called value_split.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to extract url query params and as per this forum answer I was able to do it with kv{}

But I want to understand how this works.

Here is my string: param1=val1&param2=val2&adv=val3&param3=val4&param4=val5

Now I have that field extracted in logstash as uri_query.

So then I use kv like this:

kv {
  source => "uriQuery"
  field_split => "&"
  prefix => "query_"
}

And I get fields for each query param:

query_param1 val1
query_param2 val2
etc

But what I don't understand is how it knows to strip out and break on the "=". Is that like the default token for kv's key=value syntax or something?


问:
How to load fragments the easy way?
I have an Activity that needs to load only 1 fragment.

Can I do something so that the Activity loads the fragment through the xml instead of using FragmentManager? Right now I have to write a Fragment class and that is not something I want to do.

This is how I do it.

```<code>public class MyActivity extends Activity {

    private ExampleFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FrameLayout frame = new FrameLayout(this);
        if (savedInstanceState == null) {
            fragment = new ExampleFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(frame.getId(), mFragment).commit();
        }

        setContentView(frame);
    }
}
</code>```

答:
Not exactly the answer I was hoping for although it solves my question above so I am posting it. Maybe it helps someone. Cheers!</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:name="com.example.MyFragment"
        android:id="@+id/myFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

Title: How to load fragments the easy way?

Body:
I have an Activity that needs to load only 1 fragment.

Can I do something so that the Activity loads the fragment through the xml instead of using FragmentManager? Right now I have to write a Fragment class and that is not something I want to do.

This is how I do it.

public class MyActivity extends Activity {

    private ExampleFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FrameLayout frame = new FrameLayout(this);
        if (savedInstanceState == null) {
            fragment = new ExampleFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(frame.getId(), mFragment).commit();
        }

        setContentView(frame);
    }
}

Body:
Not exactly the answer I was hoping for although it solves my question above so I am posting it. Maybe it helps someone. Cheers!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:name="com.example.MyFragment"
        android:id="@+id/myFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


问:
loading google maps in windows phone 8.1 using webview
I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:

default.html:

```<code><!DOCTYPE html>
<html>
 <head>
<meta charset="utf-8" />
<title>Maps</title>

<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>

<!-- Maps references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>

</head>
<body>
<h1>Google Maps API on Windows phone 8.1</h1>
<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>
</body>
</html>
</code>```

maps.html:

```<code><!DOCTYPE html>
<html>
<head>
<title></title>

<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>

<!-- map references -->
<link href="/map.css" rel="stylesheet" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script src="/map.js"></script>
</head>

<body>
<div id="mapdisplay" height="500px" width="500px"></div>
</body>
</html>
</code>```

maps.js:

```<code>var map;
var dataResults;

function initialize() {
    map = new google.maps.Map(document.getElementById('mapdisplay'), {
    zoom: 3,
    center: new google.maps.LatLng(40, -187.3),
    mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}

eqfeed_callback = function (results) {
   dataResults = results;
}

function addMarkers() {
  for (var i = 0; i < dataResults.features.length; i++) {
    var quake = dataResults.features[i];
    var coors = quake.geometry.coordinates;
    var latLong = new google.maps.LatLng(coors[1], coors[0]);
    var marker = new google.maps.Marker({
        position: latLong,
        map: map
        //icon: getCircle(earthquake.properties.mag)
    });
   }
 }

 function getCircle(magnitude) {
  return {
    path: google.maps.SymbolPath.CIRCLE,
    fillColor: 'red',
    fillOpacity: .2,
    scale: Math.pow(2, magnitude) / Math.PI,
    strokeColor: 'white',
    strokeWeight: .5
  };
 }
</code>```

What's the mistake I'm doing in the above code, please let me know..

答:
"maps.html" does not work because of multiple synchronicity issues.

Load maps.js beforehttp://maps.googleapis.com/maps/api/js so initialise is defined,

Load  http://maps.googleapis.com/maps/api/jsand after the HTML has been parsed so the mapdisplay element exists when initialise is called.

Call addMarkers from eqfeed_callback not initialise so dataResults has been set with valid object data.

Most of this could have been found out by opening the developers console and checking it for errors when viewing "maps.html" in a desktop browser. You may also like to research other questions on the topic and/or check the api documentation for working examples - and notice how the api documentation uses defer and async attributes on the script tag to make sure it doesn't execute until after the page has been parsed.

Body:
I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:

default.html:

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Maps</title>

<link href="/css/ui-themed.css" rel="stylesheet" />

<link href="/css/default.css" rel="stylesheet" />

Google Maps API on Windows phone 8.1

<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>

maps.html:

<!DOCTYPE html>

<title></title>

<link href="/map.css" rel="stylesheet" />

maps.js:

var map;
var dataResults;

function initialize() {
    map = new google.maps.Map(document.getElementById('mapdisplay'), {
    zoom: 3,
    center: new google.maps.LatLng(40, -187.3),
    mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}

eqfeed_callback = function (results) {
   dataResults = results;
}

function addMarkers() {
  for (var i = 0; i < dataResults.features.length; i++) {
    var quake = dataResults.features[i];
    var coors = quake.geometry.coordinates;
    var latLong = new google.maps.LatLng(coors[1], coors[0]);
    var marker = new google.maps.Marker({
        position: latLong,
        map: map
        //icon: getCircle(earthquake.properties.mag)
    });
   }
 }

 function getCircle(magnitude) {
  return {
    path: google.maps.SymbolPath.CIRCLE,
    fillColor: 'red',
    fillOpacity: .2,
    scale: Math.pow(2, magnitude) / Math.PI,
    strokeColor: 'white',
    strokeWeight: .5
  };
 }

What's the mistake I'm doing in the above code, please let me know..


问:
Image mapping with different screen sizes.
So guys If u want code I can provide it! I made a website for planets which had a big photo of planets and I used image mapping on it (from W3Schools). Problem is that when I open the same website on a bigger laptop image gets bigger since I am using bootstrap and Image mapping gets messed up. Is there any solution to this ? Can I use image mapping for all screens ?</p>

答:
You need to set max-width for your image tag so it doesn't get as big as it gets. You also need to set the @media query for the screen size you are on. But you can also set your image on a percentage of how big it's container is. (e.g) width: 50%;

For example:

```<code>//Desktop or Landscape Tablet Screen Size
@media all and (min-width: 981px) {
img {
max-width: 400px;
}
}
</code>```

Body:
You need to set max-width for your image tag so it doesn't get as big as it gets. You also need to set the @media query for the screen size you are on. But you can also set your image on a percentage of how big it's container is. (e.g) width: 50%;

For example:

//Desktop or Landscape Tablet Screen Size
@media all and (min-width: 981px) {
img {
max-width: 400px;
}
}


问:
Detect Gestures on Fingerprint Sensor-Android
I have authenticated user using authenticate() method in my app. I was looking through documentation regarding gestures on Finger-Print Sensor but couldn't find any class pertaining to gestures. Is there any class regarding same which detects gestures like long Press,Tap, etc on finger print sensor.

I went through FingerprintManager class & this but couldn't find much info regarding gestures.

答: From android O onward you can use this: https://developer.android.com/reference/android/accessibilityservice/FingerprintGestureController.html </p>


问:
Angular2 using .filter() to get index and object from array?
Is there any way to make the following code simpler?

```<code>let objectModified = this.objectsModified.filter(objectModified => {
  if(objectModified.index === this.objectCurrent.index) {
    return objectModified;
  }
})[0]; /*[0] because there is no way the could be .length > 1 */

if(objectModified) {
  let index = this.objectsModified.indexOf(objectModified);
  this.objectsModified[index] = "something";
}

else {
  this.objectsModified.push("something");
}
</code>```

It seems to me that there must be a smarter, more readable solution. But I can't figure it out.

答:
Using findIndex would simplify things:

let objectModifiedIndex = this.objectsModified.findIndex(
  objectModified => objectModified.index === this.objectCurrent.index
);
if (objectModifiedIndex !== -1) {
  this.objectsModified[objectModifiedIndex] = "something";
} else {
  this.objectsModified.push("something");
}
```

Body:
Is there any way to make the following code simpler?

let objectModified = this.objectsModified.filter(objectModified => {
  if(objectModified.index === this.objectCurrent.index) {
    return objectModified;
  }
})[0]; /*[0] because there is no way the could be .length > 1 */

if(objectModified) {
  let index = this.objectsModified.indexOf(objectModified);
  this.objectsModified[index] = "something";
}

else {
  this.objectsModified.push("something");
}

It seems to me that there must be a smarter, more readable solution. But I can't figure it out.


问:
C# How to disable the "tour" of Down keys, Up, by the items?
Well, I created an editor program (football) where the main focus is a combobox.
Which constantly has to be triggered to select the desired team and make changes and etc.
Only it gets very boring and impractical always having to click with the mouse on it to focus it and select the team with the Down and Up keys,
So what I wanted was to disable the "walk" of the Down and Up keys by the other items,
For example: there are 6 radioButtons and when I select the team in the combobox and then I click on a radioButton to mark the modification and save, I would click on Down or Up and the focus will automatically return to the combobox,
And not go down or up to another radioButton or button understood?
Or if the combobox did not lose its focus ever, no matter how much it clicked on another item.</p>

答:
```<code>void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     MyCombo.Select();
}
</code>```


问:
Why there is no need of external firefox driver like IE and chrome in selenium2.0..?
I have two doubts kindly help me to solve these

1)Why there is  no firefox driver [.exe] like IE and chrome for running selenium2.0..?

2)Why do we need to initialize the IE and chrome driver while working with IE and chrome in selenium2.0..?

Thanks
Mahesh

答:
1. Mozilla has created the geckodriver binary for use with Firefox v48 and later.

NOTE: If using Firefox v47 and earlier then the following can be ignored as it uses the native Firefox browser implementation.

Geckdriver - GitHub

Geckodriver Releases

In order for Selenium to hook into Firefox the Geckodriver Binary Path System Property must be set before instantiating the WebDriver.

webdriver.gecko.driver = path/to/geckodriver

The following is sets the property in Java.

System.setProperty("webdriver.gecko.driver","path/to/geckodriver");
WebDriver driver = new FirefoxDriver();

As of 2017-03 the latest Geckodriver must be used with Selenium v3.3 and later.

Selenium Java - Maven Repository

2. The reason for initalizing the InternetExplorerDriver and Chromedriver is that each have specific browser options.

InternetExplorerDriver - SeleniumHQ

Chromedriver - Chrome Options

Also, the other reason for a driver binary is that Selenium does not have native implementations of the browser events that are part of Internet Explorer, Chrome and Firefox (as of v48 and later).

The only proof of this that I can find is from How to Use GeckoDriver - ToolsQA (2016-09-28) that states the removal of native Firefox events from Selenium.

Gecko Driver is the link between your tests in Selenium and the Firefox browser.

GeckoDriver is a proxy for using W3C WebDriver-compatible clients to interact with Gecko-based browsers i.e. Mozilla Firefox in this case.

As Selenium 3 will not have any native implementation of FF, we have to direct all the driver commands through Gecko Driver.

A logical assumption is that Selenium never had native events for Internet Explorer or Chrome previously and that is why it has been required to use the specific driver binary for each browser type.


问:
How to get the html of an input checkbox with jquery or javascript?
This is what I have in html file

 <input type="checkbox" id="abc-news-au" /> ABC News (AU)

    <input type="checkbox" id="ars-technica" /> Ars Technica

    <input type="checkbox" id="associated-press" /> Associated Press
```
</div>
</div>
</p>

<p>I want to get the text between labels Ex. ABC NEWs (AU)</p>

<p>I use the following code but didnt work *(v is the id of the element)</p>

```console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined
```

<p>The only code that shows something is </p>

```console.log("get text: "+ v) //abc-news-au
```

which is obviously the id of the element...
How do I get the text of the element?

答:
I want to get the text between labels Ex. ABC NEWs (AU)

you could use the DOM node nextSibling property, example:

<!DOCTYPE html>

<input type="checkbox" id="abc-news-au" /> ABC News (AU)

<input type="checkbox" id="ars-technica" /> Ars Technica

<input type="checkbox" id="associated-press" /> Associated Press

```

Body:
This is what I have in html file

 <input type="checkbox" id="abc-news-au" /> ABC News (AU)

    <input type="checkbox" id="ars-technica" /> Ars Technica

    <input type="checkbox" id="associated-press" /> Associated Press

I want to get the text between labels Ex. ABC NEWs (AU)

I use the following code but didnt work *(v is the id of the element)

console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined

The only code that shows something is

console.log("get text: "+ v) //abc-news-au

which is obviously the id of the element...
How do I get the text of the element?

Body:
I want to get the text between labels Ex. ABC NEWs (AU)

you could use the DOM node nextSibling property, example:

<!DOCTYPE html>
<html>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br />
<label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br />
<label><input type="checkbox" id="associated-press" /> Associated Press</label><br />

<script>
 $('input[type=checkbox]').click(function (e) {
     if($(this).is(':checked')) {
         var data = this.nextSibling.nodeValue;
         console.log(data);
     }
 });
</script>

</body>
</html>


答:
Using conditional aggregation if a user can only become a customer once:

```<code>select
    t.user_name
  , case when c.action_timestamp is not null then 'Yes' else 'No' end as Is_Customer
  , c.action_timestamp as became_customer
  , count(case when t.action_timestamp < coalesce(c.action_timestamp,'2525-01-01') then 1 end) as interactions_before_customer
  , count(case when t.action_timestamp > c.action_timestamp then 1 end) as interactions_after_customer
from t
  left join t as c
    on t.user_name = c.user_name
      and c.action = 'became_customer'
group by t.user_name, c.action_timestamp
</code>```

rextester demo: http://rextester.com/LOUGN53032

```<code>+-----------+-------------+---------------------+------------------------------+-----------------------------+
| user_name | Is_Customer |   became_customer   | interactions_before_customer | interactions_after_customer |
+-----------+-------------+---------------------+------------------------------+-----------------------------+
| tony      | No          | NULL                |                            1 |                           0 |
| jane      | Yes         | 2016-08-06 12:00:00 |                            2 |                           0 |
| john      | Yes         | 2017-01-02 12:00:00 |                            1 |                           1 |
+-----------+-------------+---------------------+------------------------------+-----------------------------+
</code>```

Body:
Using conditional aggregation if a user can only become a customer once:

select
    t.user_name
  , case when c.action_timestamp is not null then 'Yes' else 'No' end as Is_Customer
  , c.action_timestamp as became_customer
  , count(case when t.action_timestamp < coalesce(c.action_timestamp,'2525-01-01') then 1 end) as interactions_before_customer
  , count(case when t.action_timestamp > c.action_timestamp then 1 end) as interactions_after_customer
from t
  left join t as c
    on t.user_name = c.user_name
      and c.action = 'became_customer'
group by t.user_name, c.action_timestamp

rextester demo: http://rextester.com/LOUGN53032

+-----------+-------------+---------------------+------------------------------+-----------------------------+
| user_name | Is_Customer |   became_customer   | interactions_before_customer | interactions_after_customer |
+-----------+-------------+---------------------+------------------------------+-----------------------------+
| tony      | No          | NULL                |                            1 |                           0 |
| jane      | Yes         | 2016-08-06 12:00:00 |                            2 |                           0 |
| john      | Yes         | 2017-01-02 12:00:00 |                            1 |                           1 |
+-----------+-------------+---------------------+------------------------------+-----------------------------+


问:
How can I change the "Database Name" in AWS RDS for Postgresql?
I wanted to create a replicate of my production database for staging and created the staging DB instance from a production snapshot.  However, this new instance still has the Database Name: "production-database".  I was able to rename the database on PSQl to "staging-databse," but this is not reflected in the AWS Console. I'm afraid that future developers will be very confused, and was wonderign how to rename the "Database Name" on AWS?</p>

答:
Don't use the default database option.  All it does is create a custom-named database by default.  There may be uses for it, but I never use it, because it seems to serve no purpose at all other than to specify what the database that's created by default (when the instance is first created) will be named.

Database Name

If you want to specify a database name for the default database, type a name for your database of up to 63 alpha-numeric characters. If you do not provide a name, the default "postgres" database is created.

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreatePostgreSQLInstance.html

I assume this is intended to be a convenience for new RDS users, but to me, it seems unnecessary.  It has no apparent impact on ongoing operation of the instance, which can, of course, have multiple independent databases on it.

This apparently can't subsequently be changed, so it's more of an annoyance than anything.  I always leave this blank.


问:
XINERaMA&FAKEEXTN in linux
what is the XINERaMA&FAKEEXTN in fedora or linux and what is the use of that..?</p>

答: This refers to a workaround for a bug in an old version of the Sun JDK. There is no need for it when using IcedTea.</p>

Title: XINERaMA&FAKEEXTN in linux


答:
You can use $("#"+v).parent().text() to get what you want.
This is because the text is inside  node, not <input> node.

Example: https://jsfiddle.net/epL3tkza/

Title: How to get the html of an input checkbox with jquery or javascript?

Body:
You can use $("#"+v).parent().text() to get what you want.
This is because the text is inside <label> node, not <input> node.

Example: https://jsfiddle.net/epL3tkza/


问:
For loop while using scrapy
I am trying to crawl a website. I want to do it for different dates. So i am storing date in a list. But while trying to access items of list, crawler works only for 1st value in list. Please help. following is my code:</p>

```<code>class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'retail_price'

    def start_requests(self):
        print "start request"
        urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"

        yield scrapy.Request(url=urls, callback=self.parse)

    def parse(self, response):
        dated = ["05/03/2017","04/03/2017"]
        urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"
        #frmdata =
        cookies1 ={}
        val = response.headers.getlist('Set-Cookie')
        print "login session values" ,response.headers.getlist('Set-Cookie')
        if(len(val) != 0):
            cookies1['ASP.NET_SessionId'] = str(response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")[1])
            cookies1['path'] = str(response.headers.getlist('Set-Cookie')[0].split(";")[1].split("=")[1])
        print cookies1;
        for i in range(len(dated)):
            yield scrapy.FormRequest(url=urls, callback=self.parse1, formdata={'ctl00$MainContent$btn_getdata1':"Get Data",
            'ctl00$MainContent$Txt_FrmDate':dated[i],
            'ctl00$MainContent$Ddl_Rpt_Option0':"Daily Prices",
            'ctl00$MainContent$Rbl_Rpt_type':"Price report",
            'ctl00$MainContent$ddl_Language':"English",
            'ctl00$MainContent$Ddl_Rpt_type':"Retail",
            '__EVENTVALIDATION':"IwZyKgfTXVzxiHxiPXGk/W8XQZBDb0EOPxJh6s8hofq0ffqOpiHSH77CafcxySF3PbkYgSMNFCJhLM2cGnL6SxT0PJuGDCJtV0V8Y4a94UErUCiSANiin+4uKckk9v9Ux8JqTVeaipppmlH+wyks2U9SgPfkNUsqw4eHCkDyB5akNNZImRIixOHHVY3JSXGkwXn7ueK9w+AgnqJzpXaWdMr9J1++M4VAFImSNF8brFSfPHe5kb/qzkGIwUr/KRouaRYK8WLWZh/Mbl9xwREwhDSxWJSOdihSE0WWoaqSMtpaR99rDDCsD3mdJqfu0aPIlREupTZRzlrmztXU0eS3949YW+ywdTRvykaMNgOW2Q4saYP5j/niKbRW6GiDnaLV2A38X/HW80+trrsjwJr9tjTKVFyikf6s/3gzyiTp11ivSkwIY2b3hutjYn7OfTDo",
            #'__EVENTVALIDATION':"HqVo2xHk04clYwnBposXbZGhbIr181A7RbyeZv74Cia7rXSKmpOpbeSnn3XXnoDJKRxMK0W9nxKZFfkNje+P/K7gE5HVjHJr9Gr0Gs46TntzKDsvzyii8jZ7e0fdZgQCJKoXxQNgR2vNkWqChKcEldBuMHCOgJRqCNCF/JPFKpdKZoIWr7GU8rhzwLijf/Gkm+FuTULs/fl2HHK6Z1QQEozzEHFsDwzl0G4IiN//eNYfHuUBXKZ3wdZzPqG0s53WHEuSBzhqBC9AtCJOs4ZZhdtwFh8iyTJ4PlsLP9DLHYHRCOAd72UO0UH8gT7gAkKVo1I4L540DilowOR9SttH7MM/oOs9qhKlnG61FgqkYGW8zGzF/yNEXO+beVAK1RVvuO+FDnuq/g36TRnUieei5GpAZ+96CSoCIxykdvHx8R+smTNF/5erlowV4ci+tcI7",
            '__VIEWSTATEENCRYPTED':"",
            '__VIEWSTATEGENERATOR':"85862B00",
            '__VIEWSTATE':"+a+3jrBEKxDdkPOzx2wXwKaTMWvCB60WPaHRfJUAZQrdFIpxSqFr5VseTclpGzeHXdxaFnxJe/PkxDKYa7sj3Wiv/os1bNeX0IEB3s45eFsHYWGiU8cvsXCGa5z7rrGRDL5hotg7k/MuUWj8w27xXZO423MN5OsHS+wh+tC/5/Xix+w3zxuQhi8jR5DnreimHbhGZn1sYaKYIGCc8mDIDRNl+w1OZ058F+3LAx96QUu5BYiMYOmrlyxrb9b2yPTmmIrI4NtC4ClBQlxuST5wMDP3vUqqWMhn4auk8ev5gHyPestCRrsAXWs07wDNnikemMwo/4wPiTEbnZQV6SLcDUw0gZpXjXwLI7mhsVjEyVNaQnJp6+Wi6FLsAEEMlFYmQut3JecpVIUkjF9uYSN2GLIbXHPs37AiEXPeQ8E/GyBMx3z1X5l8sw/xSNmFgYQC3riajn8V0+SdkuV2PbNbYKtc+uoSCNLppLYCqiOv5eWanGvAQro2Q67FBA4w2xY+V/K8mzHaGMLoDBxJxLslWyJpL5cX0C6qoXVUu8B028auAQM4eVzH1YPF5qrJiCDo",
            #'__VIEWSTATE':"W+m8kNAS6QHiRPo+zFj00EDs/Dbq+y/XvtCmSNwOIkGKlikAlphT8HBAWQDskSm1vdNterBuo0Hy7m4xPbXMOnyEm6IlseXO3jPw+ofnI2WHAKknLil+GeS0IfMWGeoD5aNyiz3zh1jZkKU7R7hQsxwARoHRyjhf8UCooFbkVvL6ddHVYZbH5LcocmCF1BTOCqYN5y5yzfDfYbp3KNW9kH53pdmwCsjiEirdxxUGDoG1Ke3JBEXfSl+4XubirHSR8z+VlFmPPXZGU8mMogwq9Eg822RYjvbwvZG74djcf7kdfB9KXCPO9u6cWIjLiW+cfXHSXD+1XYFVf9ATU2/NV4YbUzsI4PJRwoGD4BryUNIm2JFeT4c8F4REYTA16shxz5mDTFQ6rbmg6SmqP8G9gAc2Hr9ABD8+2BUNabGhNZ8wDIZArfYS4pl5DNrlPlpqeCjhmvv0znKAJSOac3pCUej8G90ZGwQKOPORWbNVzQShoH7QvrXV8pCklcia6psuAGO+Oj72oDWPxedE4DjdjX5TbLoW4bzsk/YNfUv4JpjGR8DWpG8IFYJG9CCjMEYb",
            '__LASTFOCUS':"",
            '__EVENTARGUMENT':"",
            '__EVENTTARGET':"",
            'ctl00_MainContent_ToolkitScriptManager1_HiddenField':";;AjaxControlToolkit,+Version=4.1.51116.0,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:fd384f95-1b49-47cf-9b47-2fa2a921a36a:475a4ef5:addc6819:5546a2b:d2e10b12:effe2a26:37e2e5c9:5a682656:c7029a2:e9e598a9"},method='POST',cookies = cookies1)

    def parse1(self, response):
        path1 = "id('Panel1')"
        value1 = response.xpath(path1).extract_first()
        print value1
</code>```

答:
First of all, you are sending the spider more time on the same site, though with different form parameters. You have therefore to use dont_filter=True in the request, otherwise Scrapy blocks duplicate calls.

Then it seems to me that the site you are scraping don't allow you to make more than one request during the same session. Try for example to go to http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx with your browser, compile the form, get the data and than to go back to the initial page: It's impossible. So you have to modify your spider. Here's a very rough code just to give an idea. It works for me, but please don't use it in production!

```<code>class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'retail_price'
    urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"

    def start_requests(self):
        dated = ["01/03/2017","05/03/2017","04/03/2017"]
        for i in dated:
            request = scrapy.Request(url=self.urls, dont_filter=True, callback=self.parse)
            request.meta['question'] = i
            yield request

    def parse(self, response):
        thedate = response.meta['question']
        cookies1 ={}
        val = response.headers.getlist('Set-Cookie')
        print("login session values" ,response.headers.getlist('Set-Cookie'))
        if(len(val) != 0):
            cookies1['ASP.NET_SessionId'] = str(str(response.headers.getlist('Set-Cookie')[0]).split(";")[0].split("=")[1])
            cookies1['path'] = str(str(response.headers.getlist('Set-Cookie')[0]).split(";")[1].split("=")[1])

        yield scrapy.FormRequest(url=self.urls, dont_filter=True, callback=self.parse1, formdata={'ctl00$MainContent$btn_getdata1':"Get Data",
        'ctl00$MainContent$Txt_FrmDate': thedate,
        'ctl00$MainContent$Ddl_Rpt_Option0':"Daily Prices",
        'ctl00$MainContent$Rbl_Rpt_type':"Price report",
        'ctl00$MainContent$ddl_Language':"English",
        'ctl00$MainContent$Ddl_Rpt_type':"Retail",
        '__EVENTVALIDATION':"IwZyKgfTXVzxiHxiPXGk/W8XQZBDb0EOPxJh6s8hofq0ffqOpiHSH77CafcxySF3PbkYgSMNFCJhLM2cGnL6SxT0PJuGDCJtV0V8Y4a94UErUCiSANiin+4uKckk9v9Ux8JqTVeaipppmlH+wyks2U9SgPfkNUsqw4eHCkDyB5akNNZImRIixOHHVY3JSXGkwXn7ueK9w+AgnqJzpXaWdMr9J1++M4VAFImSNF8brFSfPHe5kb/qzkGIwUr/KRouaRYK8WLWZh/Mbl9xwREwhDSxWJSOdihSE0WWoaqSMtpaR99rDDCsD3mdJqfu0aPIlREupTZRzlrmztXU0eS3949YW+ywdTRvykaMNgOW2Q4saYP5j/niKbRW6GiDnaLV2A38X/HW80+trrsjwJr9tjTKVFyikf6s/3gzyiTp11ivSkwIY2b3hutjYn7OfTDo",
        #'__EVENTVALIDATION':"HqVo2xHk04clYwnBposXbZGhbIr181A7RbyeZv74Cia7rXSKmpOpbeSnn3XXnoDJKRxMK0W9nxKZFfkNje+P/K7gE5HVjHJr9Gr0Gs46TntzKDsvzyii8jZ7e0fdZgQCJKoXxQNgR2vNkWqChKcEldBuMHCOgJRqCNCF/JPFKpdKZoIWr7GU8rhzwLijf/Gkm+FuTULs/fl2HHK6Z1QQEozzEHFsDwzl0G4IiN//eNYfHuUBXKZ3wdZzPqG0s53WHEuSBzhqBC9AtCJOs4ZZhdtwFh8iyTJ4PlsLP9DLHYHRCOAd72UO0UH8gT7gAkKVo1I4L540DilowOR9SttH7MM/oOs9qhKlnG61FgqkYGW8zGzF/yNEXO+beVAK1RVvuO+FDnuq/g36TRnUieei5GpAZ+96CSoCIxykdvHx8R+smTNF/5erlowV4ci+tcI7",
        '__VIEWSTATEENCRYPTED':"",
        '__VIEWSTATEGENERATOR':"85862B00",
        '__VIEWSTATE':"+a+3jrBEKxDdkPOzx2wXwKaTMWvCB60WPaHRfJUAZQrdFIpxSqFr5VseTclpGzeHXdxaFnxJe/PkxDKYa7sj3Wiv/os1bNeX0IEB3s45eFsHYWGiU8cvsXCGa5z7rrGRDL5hotg7k/MuUWj8w27xXZO423MN5OsHS+wh+tC/5/Xix+w3zxuQhi8jR5DnreimHbhGZn1sYaKYIGCc8mDIDRNl+w1OZ058F+3LAx96QUu5BYiMYOmrlyxrb9b2yPTmmIrI4NtC4ClBQlxuST5wMDP3vUqqWMhn4auk8ev5gHyPestCRrsAXWs07wDNnikemMwo/4wPiTEbnZQV6SLcDUw0gZpXjXwLI7mhsVjEyVNaQnJp6+Wi6FLsAEEMlFYmQut3JecpVIUkjF9uYSN2GLIbXHPs37AiEXPeQ8E/GyBMx3z1X5l8sw/xSNmFgYQC3riajn8V0+SdkuV2PbNbYKtc+uoSCNLppLYCqiOv5eWanGvAQro2Q67FBA4w2xY+V/K8mzHaGMLoDBxJxLslWyJpL5cX0C6qoXVUu8B028auAQM4eVzH1YPF5qrJiCDo",
        #'__VIEWSTATE':"W+m8kNAS6QHiRPo+zFj00EDs/Dbq+y/XvtCmSNwOIkGKlikAlphT8HBAWQDskSm1vdNterBuo0Hy7m4xPbXMOnyEm6IlseXO3jPw+ofnI2WHAKknLil+GeS0IfMWGeoD5aNyiz3zh1jZkKU7R7hQsxwARoHRyjhf8UCooFbkVvL6ddHVYZbH5LcocmCF1BTOCqYN5y5yzfDfYbp3KNW9kH53pdmwCsjiEirdxxUGDoG1Ke3JBEXfSl+4XubirHSR8z+VlFmPPXZGU8mMogwq9Eg822RYjvbwvZG74djcf7kdfB9KXCPO9u6cWIjLiW+cfXHSXD+1XYFVf9ATU2/NV4YbUzsI4PJRwoGD4BryUNIm2JFeT4c8F4REYTA16shxz5mDTFQ6rbmg6SmqP8G9gAc2Hr9ABD8+2BUNabGhNZ8wDIZArfYS4pl5DNrlPlpqeCjhmvv0znKAJSOac3pCUej8G90ZGwQKOPORWbNVzQShoH7QvrXV8pCklcia6psuAGO+Oj72oDWPxedE4DjdjX5TbLoW4bzsk/YNfUv4JpjGR8DWpG8IFYJG9CCjMEYb",
        '__LASTFOCUS':"",
        '__EVENTARGUMENT':"",
        '__EVENTTARGET':"",
        'ctl00_MainContent_ToolkitScriptManager1_HiddenField':";;AjaxControlToolkit,+Version=4.1.51116.0,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:fd384f95-1b49-47cf-9b47-2fa2a921a36a:475a4ef5:addc6819:5546a2b:d2e10b12:effe2a26:37e2e5c9:5a682656:c7029a2:e9e598a9"},method='POST',cookies = cookies1)

    def parse1(self, response):
        path1 = "id('Panel1')"
        value1 = response.xpath(path1).extract_first()[:574]
        print(value1)
</code>```

Title: For loop while using scrapy

Body:
I am trying to crawl a website. I want to do it for different dates. So i am storing date in a list. But while trying to access items of list, crawler works only for 1st value in list. Please help. following is my code:

class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'retail_price'

    def start_requests(self):
        print "start request"
        urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"

        yield scrapy.Request(url=urls, callback=self.parse)

    def parse(self, response):
        dated = ["05/03/2017","04/03/2017"]
        urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"
        #frmdata =
        cookies1 ={}
        val = response.headers.getlist('Set-Cookie')
        print "login session values" ,response.headers.getlist('Set-Cookie')
        if(len(val) != 0):
            cookies1['ASP.NET_SessionId'] = str(response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")[1])
            cookies1['path'] = str(response.headers.getlist('Set-Cookie')[0].split(";")[1].split("=")[1])
        print cookies1;
        for i in range(len(dated)):
            yield scrapy.FormRequest(url=urls, callback=self.parse1, formdata={'ctl00$MainContent$btn_getdata1':"Get Data",
            'ctl00$MainContent$Txt_FrmDate':dated[i],
            'ctl00$MainContent$Ddl_Rpt_Option0':"Daily Prices",
            'ctl00$MainContent$Rbl_Rpt_type':"Price report",
            'ctl00$MainContent$ddl_Language':"English",
            'ctl00$MainContent$Ddl_Rpt_type':"Retail",
            '__EVENTVALIDATION':"IwZyKgfTXVzxiHxiPXGk/W8XQZBDb0EOPxJh6s8hofq0ffqOpiHSH77CafcxySF3PbkYgSMNFCJhLM2cGnL6SxT0PJuGDCJtV0V8Y4a94UErUCiSANiin+4uKckk9v9Ux8JqTVeaipppmlH+wyks2U9SgPfkNUsqw4eHCkDyB5akNNZImRIixOHHVY3JSXGkwXn7ueK9w+AgnqJzpXaWdMr9J1++M4VAFImSNF8brFSfPHe5kb/qzkGIwUr/KRouaRYK8WLWZh/Mbl9xwREwhDSxWJSOdihSE0WWoaqSMtpaR99rDDCsD3mdJqfu0aPIlREupTZRzlrmztXU0eS3949YW+ywdTRvykaMNgOW2Q4saYP5j/niKbRW6GiDnaLV2A38X/HW80+trrsjwJr9tjTKVFyikf6s/3gzyiTp11ivSkwIY2b3hutjYn7OfTDo",
            #'__EVENTVALIDATION':"HqVo2xHk04clYwnBposXbZGhbIr181A7RbyeZv74Cia7rXSKmpOpbeSnn3XXnoDJKRxMK0W9nxKZFfkNje+P/K7gE5HVjHJr9Gr0Gs46TntzKDsvzyii8jZ7e0fdZgQCJKoXxQNgR2vNkWqChKcEldBuMHCOgJRqCNCF/JPFKpdKZoIWr7GU8rhzwLijf/Gkm+FuTULs/fl2HHK6Z1QQEozzEHFsDwzl0G4IiN//eNYfHuUBXKZ3wdZzPqG0s53WHEuSBzhqBC9AtCJOs4ZZhdtwFh8iyTJ4PlsLP9DLHYHRCOAd72UO0UH8gT7gAkKVo1I4L540DilowOR9SttH7MM/oOs9qhKlnG61FgqkYGW8zGzF/yNEXO+beVAK1RVvuO+FDnuq/g36TRnUieei5GpAZ+96CSoCIxykdvHx8R+smTNF/5erlowV4ci+tcI7",
            '__VIEWSTATEENCRYPTED':"",
            '__VIEWSTATEGENERATOR':"85862B00",
            '__VIEWSTATE':"+a+3jrBEKxDdkPOzx2wXwKaTMWvCB60WPaHRfJUAZQrdFIpxSqFr5VseTclpGzeHXdxaFnxJe/PkxDKYa7sj3Wiv/os1bNeX0IEB3s45eFsHYWGiU8cvsXCGa5z7rrGRDL5hotg7k/MuUWj8w27xXZO423MN5OsHS+wh+tC/5/Xix+w3zxuQhi8jR5DnreimHbhGZn1sYaKYIGCc8mDIDRNl+w1OZ058F+3LAx96QUu5BYiMYOmrlyxrb9b2yPTmmIrI4NtC4ClBQlxuST5wMDP3vUqqWMhn4auk8ev5gHyPestCRrsAXWs07wDNnikemMwo/4wPiTEbnZQV6SLcDUw0gZpXjXwLI7mhsVjEyVNaQnJp6+Wi6FLsAEEMlFYmQut3JecpVIUkjF9uYSN2GLIbXHPs37AiEXPeQ8E/GyBMx3z1X5l8sw/xSNmFgYQC3riajn8V0+SdkuV2PbNbYKtc+uoSCNLppLYCqiOv5eWanGvAQro2Q67FBA4w2xY+V/K8mzHaGMLoDBxJxLslWyJpL5cX0C6qoXVUu8B028auAQM4eVzH1YPF5qrJiCDo",
            #'__VIEWSTATE':"W+m8kNAS6QHiRPo+zFj00EDs/Dbq+y/XvtCmSNwOIkGKlikAlphT8HBAWQDskSm1vdNterBuo0Hy7m4xPbXMOnyEm6IlseXO3jPw+ofnI2WHAKknLil+GeS0IfMWGeoD5aNyiz3zh1jZkKU7R7hQsxwARoHRyjhf8UCooFbkVvL6ddHVYZbH5LcocmCF1BTOCqYN5y5yzfDfYbp3KNW9kH53pdmwCsjiEirdxxUGDoG1Ke3JBEXfSl+4XubirHSR8z+VlFmPPXZGU8mMogwq9Eg822RYjvbwvZG74djcf7kdfB9KXCPO9u6cWIjLiW+cfXHSXD+1XYFVf9ATU2/NV4YbUzsI4PJRwoGD4BryUNIm2JFeT4c8F4REYTA16shxz5mDTFQ6rbmg6SmqP8G9gAc2Hr9ABD8+2BUNabGhNZ8wDIZArfYS4pl5DNrlPlpqeCjhmvv0znKAJSOac3pCUej8G90ZGwQKOPORWbNVzQShoH7QvrXV8pCklcia6psuAGO+Oj72oDWPxedE4DjdjX5TbLoW4bzsk/YNfUv4JpjGR8DWpG8IFYJG9CCjMEYb",
            '__LASTFOCUS':"",
            '__EVENTARGUMENT':"",
            '__EVENTTARGET':"",
            'ctl00_MainContent_ToolkitScriptManager1_HiddenField':";;AjaxControlToolkit,+Version=4.1.51116.0,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:fd384f95-1b49-47cf-9b47-2fa2a921a36a:475a4ef5:addc6819:5546a2b:d2e10b12:effe2a26:37e2e5c9:5a682656:c7029a2:e9e598a9"},method='POST',cookies = cookies1)

    def parse1(self, response):
        path1 = "id('Panel1')"
        value1 = response.xpath(path1).extract_first()
        print value1

Body:
First of all, you are sending the spider more time on the same site, though with different form parameters. You have therefore to use dont_filter=True in the request, otherwise Scrapy blocks duplicate calls.

Then it seems to me that the site you are scraping don't allow you to make more than one request during the same session. Try for example to go to http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx with your browser, compile the form, get the data and than to go back to the initial page: It's impossible. So you have to modify your spider. Here's a very rough code just to give an idea. It works for me, but please don't use it in production!

class SpidyQuotesViewStateSpider(scrapy.Spider):
    name = 'retail_price'
    urls = "http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx"

    def start_requests(self):
        dated = ["01/03/2017","05/03/2017","04/03/2017"]
        for i in dated:
            request = scrapy.Request(url=self.urls, dont_filter=True, callback=self.parse)
            request.meta['question'] = i
            yield request

    def parse(self, response):
        thedate = response.meta['question']
        cookies1 ={}
        val = response.headers.getlist('Set-Cookie')
        print("login session values" ,response.headers.getlist('Set-Cookie'))
        if(len(val) != 0):
            cookies1['ASP.NET_SessionId'] = str(str(response.headers.getlist('Set-Cookie')[0]).split(";")[0].split("=")[1])
            cookies1['path'] = str(str(response.headers.getlist('Set-Cookie')[0]).split(";")[1].split("=")[1])

        yield scrapy.FormRequest(url=self.urls, dont_filter=True, callback=self.parse1, formdata={'ctl00$MainContent$btn_getdata1':"Get Data",
        'ctl00$MainContent$Txt_FrmDate': thedate,
        'ctl00$MainContent$Ddl_Rpt_Option0':"Daily Prices",
        'ctl00$MainContent$Rbl_Rpt_type':"Price report",
        'ctl00$MainContent$ddl_Language':"English",
        'ctl00$MainContent$Ddl_Rpt_type':"Retail",
        '__EVENTVALIDATION':"IwZyKgfTXVzxiHxiPXGk/W8XQZBDb0EOPxJh6s8hofq0ffqOpiHSH77CafcxySF3PbkYgSMNFCJhLM2cGnL6SxT0PJuGDCJtV0V8Y4a94UErUCiSANiin+4uKckk9v9Ux8JqTVeaipppmlH+wyks2U9SgPfkNUsqw4eHCkDyB5akNNZImRIixOHHVY3JSXGkwXn7ueK9w+AgnqJzpXaWdMr9J1++M4VAFImSNF8brFSfPHe5kb/qzkGIwUr/KRouaRYK8WLWZh/Mbl9xwREwhDSxWJSOdihSE0WWoaqSMtpaR99rDDCsD3mdJqfu0aPIlREupTZRzlrmztXU0eS3949YW+ywdTRvykaMNgOW2Q4saYP5j/niKbRW6GiDnaLV2A38X/HW80+trrsjwJr9tjTKVFyikf6s/3gzyiTp11ivSkwIY2b3hutjYn7OfTDo",
        #'__EVENTVALIDATION':"HqVo2xHk04clYwnBposXbZGhbIr181A7RbyeZv74Cia7rXSKmpOpbeSnn3XXnoDJKRxMK0W9nxKZFfkNje+P/K7gE5HVjHJr9Gr0Gs46TntzKDsvzyii8jZ7e0fdZgQCJKoXxQNgR2vNkWqChKcEldBuMHCOgJRqCNCF/JPFKpdKZoIWr7GU8rhzwLijf/Gkm+FuTULs/fl2HHK6Z1QQEozzEHFsDwzl0G4IiN//eNYfHuUBXKZ3wdZzPqG0s53WHEuSBzhqBC9AtCJOs4ZZhdtwFh8iyTJ4PlsLP9DLHYHRCOAd72UO0UH8gT7gAkKVo1I4L540DilowOR9SttH7MM/oOs9qhKlnG61FgqkYGW8zGzF/yNEXO+beVAK1RVvuO+FDnuq/g36TRnUieei5GpAZ+96CSoCIxykdvHx8R+smTNF/5erlowV4ci+tcI7",
        '__VIEWSTATEENCRYPTED':"",
        '__VIEWSTATEGENERATOR':"85862B00",
        '__VIEWSTATE':"+a+3jrBEKxDdkPOzx2wXwKaTMWvCB60WPaHRfJUAZQrdFIpxSqFr5VseTclpGzeHXdxaFnxJe/PkxDKYa7sj3Wiv/os1bNeX0IEB3s45eFsHYWGiU8cvsXCGa5z7rrGRDL5hotg7k/MuUWj8w27xXZO423MN5OsHS+wh+tC/5/Xix+w3zxuQhi8jR5DnreimHbhGZn1sYaKYIGCc8mDIDRNl+w1OZ058F+3LAx96QUu5BYiMYOmrlyxrb9b2yPTmmIrI4NtC4ClBQlxuST5wMDP3vUqqWMhn4auk8ev5gHyPestCRrsAXWs07wDNnikemMwo/4wPiTEbnZQV6SLcDUw0gZpXjXwLI7mhsVjEyVNaQnJp6+Wi6FLsAEEMlFYmQut3JecpVIUkjF9uYSN2GLIbXHPs37AiEXPeQ8E/GyBMx3z1X5l8sw/xSNmFgYQC3riajn8V0+SdkuV2PbNbYKtc+uoSCNLppLYCqiOv5eWanGvAQro2Q67FBA4w2xY+V/K8mzHaGMLoDBxJxLslWyJpL5cX0C6qoXVUu8B028auAQM4eVzH1YPF5qrJiCDo",
        #'__VIEWSTATE':"W+m8kNAS6QHiRPo+zFj00EDs/Dbq+y/XvtCmSNwOIkGKlikAlphT8HBAWQDskSm1vdNterBuo0Hy7m4xPbXMOnyEm6IlseXO3jPw+ofnI2WHAKknLil+GeS0IfMWGeoD5aNyiz3zh1jZkKU7R7hQsxwARoHRyjhf8UCooFbkVvL6ddHVYZbH5LcocmCF1BTOCqYN5y5yzfDfYbp3KNW9kH53pdmwCsjiEirdxxUGDoG1Ke3JBEXfSl+4XubirHSR8z+VlFmPPXZGU8mMogwq9Eg822RYjvbwvZG74djcf7kdfB9KXCPO9u6cWIjLiW+cfXHSXD+1XYFVf9ATU2/NV4YbUzsI4PJRwoGD4BryUNIm2JFeT4c8F4REYTA16shxz5mDTFQ6rbmg6SmqP8G9gAc2Hr9ABD8+2BUNabGhNZ8wDIZArfYS4pl5DNrlPlpqeCjhmvv0znKAJSOac3pCUej8G90ZGwQKOPORWbNVzQShoH7QvrXV8pCklcia6psuAGO+Oj72oDWPxedE4DjdjX5TbLoW4bzsk/YNfUv4JpjGR8DWpG8IFYJG9CCjMEYb",
        '__LASTFOCUS':"",
        '__EVENTARGUMENT':"",
        '__EVENTTARGET':"",
        'ctl00_MainContent_ToolkitScriptManager1_HiddenField':";;AjaxControlToolkit,+Version=4.1.51116.0,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:fd384f95-1b49-47cf-9b47-2fa2a921a36a:475a4ef5:addc6819:5546a2b:d2e10b12:effe2a26:37e2e5c9:5a682656:c7029a2:e9e598a9"},method='POST',cookies = cookies1)

    def parse1(self, response):
        path1 = "id('Panel1')"
        value1 = response.xpath(path1).extract_first()[:574]
        print(value1)


问:
Data To Munge: Stock Trading, Exchange Trading
I know that a lot of this information is probably entirely privatized, but does anyone know of a good source of real time information on what kind of trading activity is where in the market?  It doesn't need to be fast enough to actually make informed trading decisions based on it, I'm more looking to aggregate it into some beautiful graphics.  For fun.  Because I have personal problems.

I'd be grateful for any help!

答:
Not sure, but I was of the opinion that Google Finance API was better than Yahoo:

http://code.google.com/apis/finance/