问:
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?

答:
If you are talking about connecting to your Websocket using Php, then YES, it is doable. There are a few libraries like Php WebSocket client or Websocket php that can connect to your websocket as a Client.

You can also check out this Websocket Client for an example.

Another Working Example without using any library and implementing the  hybi10 frame encoding as per the specification:

```<code>$host = 'www.host.com';  // your websocket server
$port = 443;
$local = "http://localhost";  // url where this script runs | 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>```

Lastly, you can send your byte data as a JSON object by encoding it to base64 first.
Check this SO Post to see how to do that. Hope this helps.

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?

Body:
If you are talking about connecting to your Websocket using Php, then YES, it is doable. There are a few libraries like Php WebSocket client or Websocket php that can connect to your websocket as a Client.

You can also check out this Websocket Client for an example.

Another Working Example without using any library and implementing the  hybi10 frame encoding as per the specification:

$host = 'www.host.com';  // your websocket server
$port = 443;
$local = "http://localhost";  // url where this script runs | 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;
}

Lastly, you can send your byte data as a JSON object by encoding it to base64 first.
Check this SO Post to see how to do that. Hope this helps.


来源: stackexchange

问:
Why doesnt this xPath (c#) work?
Got this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

And this xpath:

```<code>videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;
</code>```

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

答:
/video/title would return a title element with no namespace, from within a video element with no namespace.

You need to either remove xmlns="UploadXSD" from your xml, or set an appropriate selection namespace in your C#

ContentLicense: CC BY-SA 2.5

Title: Why doesnt this xPath (c#) work?

Body:
Got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

And this xpath:

videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...


问:
Creating url with locale doesn't work in Twig
I am creating a language switcher in Symfony, using the following code:

```<code><select title="Change Language" onChange="window.location.href=this.value">
   <option value="{{ path(app.request.attributes.get('_route'), {'_locale':'en'}) }}" {% if  app.request.locale == 'en'  %} selected="selected" {% endif %}>English                                </option>
  <option value="{{ path(app.request.attributes.get('_route'), {'_locale':'it'}) }}" {% if  app.request.locale == 'it'  %} selected="selected" {% endif %}>Italiano                                </option>
</select>
</code>```

When I go to http://localhost:8000/app_dev.php/en/about the links in the option are correct, i.e: /app_dev.php/en/about and /app_dev.php/it/about but if I go to the same page without specifying the locale, http://localhost:8000/app_dev.php/about incorrect links are created in the option like this: /app_dev.php/about?_locale=it and /app_dev.php/about?_locale=en

The about action in my controller looks like this:

```<code> /**
 * @Route("/{_locale}/about", name="aboutUs", defaults={"_locale" = "en"}, requirements={"_locale" = "en|de|fr|es|it"})
 * @Route("/about")
 */

public  function aboutAction(){
    return $this->render('default/frontend/about.html.twig');
}
</code>```

How can I correct this?

答:
First, delete your second @Route.

After, install https://github.com/schmittjoh/JMSI18nRoutingBundle
With this bundle, you can do the system URLs like you want.

down you have an example of config that do it.

```<code>jms_i18n_routing:
    default_locale: en
    locales: [es, it, fr, pl, pt, en, de, ca]
    strategy: prefix_except_default
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a language switcher in Symfony, using the following code:

<select title="Change Language" onChange="window.location.href=this.value">
   <option value="{{ path(app.request.attributes.get('_route'), {'_locale':'en'}) }}" {% if  app.request.locale == 'en'  %} selected="selected" {% endif %}>English                                </option>
  <option value="{{ path(app.request.attributes.get('_route'), {'_locale':'it'}) }}" {% if  app.request.locale == 'it'  %} selected="selected" {% endif %}>Italiano                                </option>
</select>

When I go to http://localhost:8000/app_dev.php/en/about the links in the option are correct, i.e: /app_dev.php/en/about and /app_dev.php/it/about but if I go to the same page without specifying the locale, http://localhost:8000/app_dev.php/about incorrect links are created in the option like this: /app_dev.php/about?_locale=it and /app_dev.php/about?_locale=en

The about action in my controller looks like this:

 /**
 * @Route("/{_locale}/about", name="aboutUs", defaults={"_locale" = "en"}, requirements={"_locale" = "en|de|fr|es|it"})
 * @Route("/about")
 */

public  function aboutAction(){
    return $this->render('default/frontend/about.html.twig');
}

How can I correct this?

Body:
First, delete your second @Route.

After, install https://github.com/schmittjoh/JMSI18nRoutingBundle
With this bundle, you can do the system URLs like you want.

down you have an example of config that do it.

jms_i18n_routing:
    default_locale: en
    locales: [es, it, fr, pl, pt, en, de, ca]
    strategy: prefix_except_default


问:
How to run Elasticsearch 2.1.1 as root user in Linux machine
I am trying to run Elasticsearch 2.1.1 in my Linux machine which I am the root user of it.

When I tried to execute the Elasticsearch.I am getting the following error:

```<code>Exception in thread "main" java.lang.RuntimeException: don't run elasticsearch as root.
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:93)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:144)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:285)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)
Refer to the log for complete error details.
</code>```

I referred some suggestion available in internet, they mentioned to run it as different user. My scenario is to run as root user only. How to overcome this problem without running as different user.

答: You should change the owner and group of the elasticsearch-X.X.X and run as that user. It works in elasticsearch-5.3.0</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run Elasticsearch 2.1.1 in my Linux machine which I am the root user of it.

When I tried to execute the Elasticsearch.I am getting the following error:

Exception in thread "main" java.lang.RuntimeException: don't run elasticsearch as root.
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:93)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:144)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:285)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)
Refer to the log for complete error details.

I referred some suggestion available in internet, they mentioned to run it as different user. My scenario is to run as root user only. How to overcome this problem without running as different user.


问:
Jenkins Weblogic Server Deployment weblogic.management.home.localhome
Scenario:
I try to deploy web services to weblogic server by Jenkins + weblogic deployer.
I successfully get war files after build.
While deploying war files I get below error in console.

Additional descriptions:
This is enterprise environment. Jenkins and Weblogic server are running on different servers but connetions are ok. On weblogic server there 4 applications
my web services running on a cluster.

Question: What is the meaning of this error? How to fix it or at least where should I concentrate? :)

Reason: javax.naming.NameNotFoundException: While trying to lookup
  'weblogic.management.home.localhome' didn't find subcontext 'home'.
  Resolved 'weblogic.management' [Root exception is
  javax.naming.NameNotFoundException: While trying to lookup
  'weblogic.management.home.localhome' didn't find subcontext 'home'.
  Resolved 'weblogic.management']; remaining name 'home/localhome'

答:
You're getting a NameNotFoundException when trying to lookup a resource (weblogic.management.home.localhome) using JNDI. The exception says that part of the name is resolved (weblogic.management) but that it cannot resolve the remainder (home.localhome).

In the Javadoc for NameNotFoundException, you'll see:

This exception is thrown when a component of the name cannot be resolved because it is not bound.

That means that, either the subcontext information for the JNDI resourcs (home.localhome) is incorrect, or the subcontext (home.localhome) is not registered with the JNDI naming service.

See http://docs.oracle.com/javase/7/docs/api/javax/naming/NamingException.html (superclass of the NameNotFoundException) for the exception and review the JNDI info here for configuration help: http://docs.oracle.com/middleware/1221/wls/WLACH/core/index.html


问:
column "new" of relation "publications" does not exist
I want to develop a trigger that updates a trigger after an insert or update.

I follow this tutorial and created a function that is called by the trigger after an insertion. I tried with both after and before.

```<code>DROP TRIGGER IF EXISTS answer_update_question_timestamp ON public.publications;

CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    UPDATE publications SET new.last_edit_date = now() WHERE publicationid = new.publicationid;
    RETURN NULL;
END;
$func$  LANGUAGE plpgsql;

CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();

CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP,
    CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
    CONSTRAINT "FK_publications_users"
        FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);
</code>```

I noticed that NEW doesn't work with operations such as FOR EACH STATEMENT but I haven't found anything wrong with FOR EACH ROW

Does anyone kno what I'm doing wrong?

Kind regards

答:
If you want last_edit_date to be set to now() on insert or delete, just set default to now():

```<code>CREATE TABLE publications
(
 ...
    last_edit_date TIMESTAMP DEFAULT now(),
....
);
</code>```

If you still want to go there,instead of updating itself and returning null assign a new value to NEW:

```<code>NEW.last_edit_date := now();
RETURN NEW;
</code>```

Endless loop pozs is talking about happens when you assign a function that updates a table to a trigger on that table that fires on update

Update - working example for OP:

```<code>t=# CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP
);
CREATE TABLE
t=# CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    new.last_edit_date := now();
    RETURN NEW;
END;
$func$  LANGUAGE plpgsql;
CREATE FUNCTION
t=# CREATE TRIGGER answer_update_question_timestamp BEFORE INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();
CREATE TRIGGER
t=# insert into publications select 1,'2',now(),3,null;
INSERT 0 1
t=# select * from publications;
 publicationid | body |       creation_date        | userid |       last_edit_date
---------------+------+----------------------------+--------+----------------------------
             1 | 2    | 2017-03-30 15:28:10.897846 |      3 | 2017-03-30 15:28:10.897846
(1 row)
</code>```

Body:
I want to develop a trigger that updates a trigger after an insert or update.

I follow this tutorial and created a function that is called by the trigger after an insertion. I tried with both after and before.

DROP TRIGGER IF EXISTS answer_update_question_timestamp ON public.publications;

CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    UPDATE publications SET new.last_edit_date = now() WHERE publicationid = new.publicationid;
    RETURN NULL;
END;
$func$  LANGUAGE plpgsql;

CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();

CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP,
    CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
    CONSTRAINT "FK_publications_users"
        FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);

I noticed that NEW doesn't work with operations such as FOR EACH STATEMENT but I haven't found anything wrong with FOR EACH ROW

Does anyone kno what I'm doing wrong?

Kind regards

Body:
If you want last_edit_date to be set to now() on insert or delete, just set default to now():

CREATE TABLE publications
(
 ...
    last_edit_date TIMESTAMP DEFAULT now(),
....
);

If you still want to go there,instead of updating itself and returning null assign a new value to NEW:

NEW.last_edit_date := now();
RETURN NEW;

Endless loop pozs is talking about happens when you assign a function that updates a table to a trigger on that table that fires on update

Update - working example for OP:

t=# CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP
);
CREATE TABLE
t=# CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    new.last_edit_date := now();
    RETURN NEW;
END;
$func$  LANGUAGE plpgsql;
CREATE FUNCTION
t=# CREATE TRIGGER answer_update_question_timestamp BEFORE INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();
CREATE TRIGGER
t=# insert into publications select 1,'2',now(),3,null;
INSERT 0 1
t=# select * from publications;
 publicationid | body |       creation_date        | userid |       last_edit_date
---------------+------+----------------------------+--------+----------------------------
             1 | 2    | 2017-03-30 15:28:10.897846 |      3 | 2017-03-30 15:28:10.897846
(1 row)


问:
solving St Peterburg Paradox in R
St Petersburg paradox is a gambling game where you pay a fixed amount to enter the game. You flip a coin repeatedly until a tails is thrown. Your payoff is the sum from 1 to n of 2^n where n is the number of heads before the first tails. If that doesn't make sense try the wikipedia article

I was doing a paper on Expected Utility theory and was writing on the St Petersburg paradox and thought it would be neat(although not relevant to my paper) to try and do a monte carlo in R for how much you would expect to win after 10000 trials

I basically want to do http://www.mathematik.com/Petersburg/Petersburg.html in R with 10,000 trials

答:
This is easy in R. The game follows the geometric distribution with p=1/2:

```<code>N <- 1e+4
out <- replicate(N, mean(2^rgeom(1000, .5)))
</code>```

Because the expected payoff of the game is infinity, you will get an extremely skewed empirical distribution which you won't even be able to depict properly:

```<code>hist(out)
</code>```

Log scale might be a better idea.

```<code>hist(log(out))
</code>```

Title: solving St Peterburg Paradox in R

Body:
This is easy in R. The game follows the geometric distribution with p=1/2:

N <- 1e+4
out <- replicate(N, mean(2^rgeom(1000, .5)))

Because the expected payoff of the game is infinity, you will get an extremely skewed empirical distribution which you won't even be able to depict properly:

hist(out)

Log scale might be a better idea.

hist(log(out))


问:
how to merge two array objects in javascript
Just wondering what is my best approach to merge these two arrays together.

example

```<code>var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]
</code>```

Looking to merge them into:

```<code>var c = ["ID":11021, ASSET_NAME:"panda", service_name: ['open requests','open tickets']]
</code>```

any help would be great.

Thanks

答:
You can utilize the map method of arrays, like so:

```<code>var a = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open tickets'}];
var b = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open requests'}];
var c = a.map((obj, i) => {
    for (key in obj) {
    if(obj[key] !== b[i][key]) {
        obj[key] = [obj[key], b[i][key]]
    }
    return obj;
  }
})

console.log(c) // [{'eprid':112}, {'asset_name':'panda'}, {'service_name': ['open ticket', 'open requests']}]
</code>```

Body:
Just wondering what is my best approach to merge these two arrays together.

example

var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]

Looking to merge them into:

var c = ["ID":11021, ASSET_NAME:"panda", service_name: ['open requests','open tickets']]

any help would be great.

Thanks

Body:
You can utilize the map method of arrays, like so:

var a = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open tickets'}];
var b = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open requests'}];
var c = a.map((obj, i) => {
    for (key in obj) {
    if(obj[key] !== b[i][key]) {
        obj[key] = [obj[key], b[i][key]]
    }
    return obj;
  }
})

console.log(c) // [{'eprid':112}, {'asset_name':'panda'}, {'service_name': ['open ticket', 'open requests']}]


问:
Tool to convert (translate) C to Go?
What tool to use to convert C source code into Go source code?

For example, if the C code contains:

```<code>struct Node {
    struct Node *left, *right;
    void        *data;
};

char charAt(char *s, int i) {
    return s[i];
}
</code>```

the corresponding Go code generated by the tool should be:

```<code>type Node struct {
    left, right *Node
    data        interface{}
}

func charAt(s string, i int) byte {
    return s[i]
}
</code>```

The tool does not need to be perfect. It is OK if some parts of the generated Go code need to be corrected by hand.

答:
Check out this project

https://github.com/elliotchance/c2go

The detailed description is in this article

Update: August 6, 2021

Also check this one

https://github.com/gotranspile/cxgo

Title: Tool to convert (translate) C to Go?

Body:
What tool to use to convert C source code into Go source code?

For example, if the C code contains:

struct Node {
    struct Node *left, *right;
    void        *data;
};

char charAt(char *s, int i) {
    return s[i];
}

the corresponding Go code generated by the tool should be:

type Node struct {
    left, right *Node
    data        interface{}
}

func charAt(s string, i int) byte {
    return s[i]
}

The tool does not need to be perfect. It is OK if some parts of the generated Go code need to be corrected by hand.


问:
how to get from Linux command inside shell a string or value to JAVA?
it's possible to get the output of a command inside linux shell to a JAVA app? if it's possible how? I see the chance to  execute from JAVA a shell command i wish the opposite result : SHELL COMMANDS OUTPUT  --->to---> Java VARIABLE or STRING.  thanks for reply</p>

答:
Ok lets assume you want to run X command in linux.

then in the terminal type:

```<code>x > "myfilename"
</code>```

Just to give an example:

```<code>netstat > "xyz"
</code>```

This will create a file 'xyz' and transfer all the output to it.

This will put all the output to the 'myfilename'.

Now you can read all the contents of the file from a java application.

Alternative:

You can run shell command from java and collect the output for later processing.

Body:
Ok lets assume you want to run X command in linux.

then in the terminal type:

x > "myfilename"

Just to give an example:

netstat > "xyz"

This will create a file 'xyz' and transfer all the output to it.

This will put all the output to the 'myfilename'.

Now you can read all the contents of the file from a java application.

Alternative:

You can run shell command from java and collect the output for later processing.


问:
Reading specific column from file when last few rows are not equivalent in python
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

```<code>def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp
</code>```

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

```<code>#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407
</code>```

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range
</code>```

How can I get rid of the last lines in the line variable?

Thanks to all

答:
There are many ways to handle this, one such way can be to handle the indexError by surrounding the erroneous code by try and except, something like this :

```<code>try :
    total_sp.append(int(t[4]))
except IndexError :
    pass
</code>```

This will only append to the total_sp when index exits otherwise not. Also, this will handle whenever you do not have the data present corresponding to that particular index.

Alternatively, if you are interested in removing just the last two rows (elements), you can use the slice operator such as by replacing line = list(f.readlines()[1:]) with line = f.readlines()[1:-2].

Body:
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range

How can I get rid of the last lines in the line variable?

Thanks to all

Body:
There are many ways to handle this, one such way can be to handle the indexError by surrounding the erroneous code by try and except, something like this :

try :
    total_sp.append(int(t[4]))
except IndexError :
    pass

This will only append to the total_sp when index exits otherwise not. Also, this will handle whenever you do not have the data present corresponding to that particular index.

Alternatively, if you are interested in removing just the last two rows (elements), you can use the slice operator such as by replacing line = list(f.readlines()[1:]) with line = f.readlines()[1:-2].


问:
What is the earliest callback one can hook in the Rails Framework?
I have found the before_dispatch and after_dispatch in dispatcher.rb but I need to access something earlier. Like around when Rails.public_path is defined.</p>

答: If it's needed for Mongrel or Apache, are You sure it can not be done by configuration?</p>

OwnerDisplayName: aivarsak


答:
Is it possible that the doc variable points to the <video> element? In that case you would need to write either

```<code>videoToAdd.Title = doc.SelectSingleNode(@"./title").InnerXml;
</code>```

or

```<code>videoToAdd.Title = doc.SelectSingleNode(@"//video/title").InnerXml;
</code>```

Title: Why doesnt this xPath (c#) work?

Body:
Is it possible that the doc variable points to the <video> element? In that case you would need to write either

videoToAdd.Title = doc.SelectSingleNode(@"./title").InnerXml;

or

videoToAdd.Title = doc.SelectSingleNode(@"//video/title").InnerXml;


问:
Bash - how to format a time-stamp variable to human readable format
At the beginning of my script I set a variable DATE, which I need to use in different parts of the script and in different formats.

My issue is to use the same variable but format it in different ways:

```<code>#!/bin/bash
DATE=$(date +%s)
echo "date in timestamp format: $DATE"
echo "..."
# some other actions that need time...
echo "date start at: $(date $(DATE +%Y-%m-%d:%H:%M))"
</code>```

this runs but outputs an error (DATE: command not found):

```<code>date in timestamp format: 1490884719
...
<script>.sh: line 6: DATE: command not found
date start at: Thu Mar 30 16:38:40 CEST 2017
</code>```

how do I get rid of the error?

答:
Using the $(...) is trying to execute the DATE command, without success. Coincidentally, date is running anyway, with no arguments, returning the current time (looking similar to the original).

Try replacing the whole line with something like:

echo "date start at: $(date --date=@${DATE} '+%Y-%m-%d:%H:%M')"

for GNU date (Linux and friends), and:

echo "date start at: $(date -j -f '%s' ${DATE} '+%Y-%m-%d:%H:%M')"

for BSD date (macOS and other BSDs).

Body:
At the beginning of my script I set a variable DATE, which I need to use in different parts of the script and in different formats.

My issue is to use the same variable but format it in different ways:

#!/bin/bash
DATE=$(date +%s)
echo "date in timestamp format: $DATE"
echo "..."
# some other actions that need time...
echo "date start at: $(date $(DATE +%Y-%m-%d:%H:%M))"

this runs but outputs an error (DATE: command not found):

date in timestamp format: 1490884719
...


问:
Maven errors in eclipse and while running mvn clean install
When I imported a project as Maven project I got the below errors in the properties of the application. Can you please let me know why I am getting these errors. Thanks in advance

enter image description here

Added to it I get the below error when I run mvn clean install on my project. I have checked my settings.xml file in .m2 folder. Nothing appears to be wrong in it. May I know why this error is coming. Thanks in advance

enter image description here

答: It is an issue with Maven version. When I ran the same command with a different version (3.x) of maven, it worked :)</p>


问:
Why is this Django QuerySet returning no results?
I have this Class in a project, and I'm trying to get previous and next elements of current one.

```<code>def get_context(self, request, *args, **kwargs):
    context = super(GuidePage, self).get_context(request, *args, **kwargs)
    context = get_article_context(context)

    all_guides = GuidePage.objects.all().order_by("-date")

    context['all_guides'] = all_guides

    context['next_guide'] = all_guides.filter(date__lt=self.date)

    context['prev_guide'] = all_guides.filter(date__gt=self.date)

    print context['next_guide']
    print context['prev_guide']

    return context
</code>```

These two lines:

```<code>context['prev_guide'] = all_guides.filter(date__lt=self.date)
context['next_guide'] = all_guides.filter(date__gt=self.date)
</code>```

are returning empty results as printed in the console:

```<code>(QuerySet[])
(QuerySet[])
</code>```

What am I missing?

EDIT:

I changed lt and gt to lte and gte. As I understand that will include results that are also equal in date.

In this case I got ALL elements. All elements were created the same day, but, of course, at different times, so they should be different by minutes. Is this difference not taking into account when filtering for greater/lesser ?

答:
If you want to filter not only by date, but time also, you must change the relevant field in your model to be of DateTimeField instead of DateField.

Like this:

```<code>from django.db import models

class MyModel(models.Model):
    date_time = models.DateTimeField()
</code>```

Now, you can do stuff like all_guides.filter(date_time__lte=self.date_time) or all_guides.filter(date_time__gte=self.date_time).

Carefull of the two underscores __.

Body:
I have this Class in a project, and I'm trying to get previous and next elements of current one.

def get_context(self, request, *args, **kwargs):
    context = super(GuidePage, self).get_context(request, *args, **kwargs)
    context = get_article_context(context)

    all_guides = GuidePage.objects.all().order_by("-date")

    context['all_guides'] = all_guides

    context['next_guide'] = all_guides.filter(date__lt=self.date)

    context['prev_guide'] = all_guides.filter(date__gt=self.date)

    print context['next_guide']
    print context['prev_guide']

    return context

These two lines:

context['prev_guide'] = all_guides.filter(date__lt=self.date)
context['next_guide'] = all_guides.filter(date__gt=self.date)

are returning empty results as printed in the console:

(QuerySet[])
(QuerySet[])

What am I missing?

EDIT:

I changed lt and gt to lte and gte. As I understand that will include results that are also equal in date.

In this case I got ALL elements. All elements were created the same day, but, of course, at different times, so they should be different by minutes. Is this difference not taking into account when filtering for greater/lesser ?

Body:
If you want to filter not only by date, but time also, you must change the relevant field in your model to be of DateTimeField instead of DateField.

Like this:

from django.db import models

class MyModel(models.Model):
    date_time = models.DateTimeField()

Now, you can do stuff like all_guides.filter(date_time__lte=self.date_time) or all_guides.filter(date_time__gte=self.date_time).

Carefull of the two underscores __.


问:
Adding to local storage
I am using local storage to add json data as favorites. for some reason when i add more that one favorite it removes the one already in local storage. </p>

```<code> $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));
</code>```

答:
put the line var favArray = []; out of click event</p>

```<code>var favArray = []; //here
 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));

        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));
</code>```

Title: Adding to local storage

Body:
I am using local storage to add json data as favorites. for some reason when i add more that one favorite it removes the one already in local storage.

 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

Body:
put the line var favArray = []; out of click event

var favArray = []; //here
 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));

        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));


问:
In Redux, replace dispatch in action creator
Given my action creator:

```<code>export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'
export const CHANGE_PAGE = 'CHANGE_PAGE'

export const changePage = (currentPage) => ({
    type: CHANGE_PAGE,
    currentPage,
})

export const requestArticles = () => ({
    type: REQUEST_ARTICLES,
})

export const receiveArticles = json => ({
    type: RECEIVE_ARTICLES,
    posts: json.hits,
})

export const fetchArticles = () => async (dispatch) => {
    try {
        await dispatch(requestArticles())
        let response = await fetch('www.abc.com')
        let json = await response.json()
        await dispatch(receiveArticles(json))
    } catch (e) {
        console.log('error:', e)
    }
}
</code>```

So I am using dispatch inside action creator. But if I have to dispatch multiple actions, then my code would be

```<code>        try {
            await dispatch(requestArticles1())
            await dispatch(requestArticles2())
            await dispatch(requestArticles3())
            await dispatch(requestArticles4())
            await dispatch(requestArticles5())
            let response = await fetch('www.abc.com')
            let json = await response.json()
            await dispatch(receiveArticles(json))
        } catch (e) {
            console.log('error:', e)
        }
</code>```

I already use mapDispatchToProps in the component. Is there any similar way/method I can use in action creator so that I don't have to dispatch actions manually one by one?

答:
redux's store.dispatch() is not an asynchronous function, so there is no need to await its return.  It will still work because awaiting non-async functions casts them to an immediately-resolving promise.

With regard to dispatching multiple actions, you will need to manually dispatch every action that you need.  The question becomes: why do you need to dispatch so many actions?  In general for an ajax-calling thunk you will use a started, succeeded and failed action, and not many more.

```<code>export const fetchArticles = () => async (dispatch) => {
    try {
        dispatch(requestArticlesStarted())
        const response = await fetch('www.abc.com')
        const json = await response.json()
        dispatch(requestArticlesSucceeded(json))
    } catch (e) {
        console.log('error:', e);
        dispatch(requestArticlesFailed(e));
    }
}
</code>```

Body:
Given my action creator:

export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'
export const CHANGE_PAGE = 'CHANGE_PAGE'

export const changePage = (currentPage) => ({
    type: CHANGE_PAGE,
    currentPage,
})

export const requestArticles = () => ({
    type: REQUEST_ARTICLES,
})

export const receiveArticles = json => ({
    type: RECEIVE_ARTICLES,
    posts: json.hits,
})

export const fetchArticles = () => async (dispatch) => {
    try {
        await dispatch(requestArticles())
        let response = await fetch('www.abc.com')
        let json = await response.json()
        await dispatch(receiveArticles(json))
    } catch (e) {
        console.log('error:', e)
    }
}

So I am using dispatch inside action creator. But if I have to dispatch multiple actions, then my code would be

        try {
            await dispatch(requestArticles1())
            await dispatch(requestArticles2())
            await dispatch(requestArticles3())
            await dispatch(requestArticles4())
            await dispatch(requestArticles5())
            let response = await fetch('www.abc.com')
            let json = await response.json()
            await dispatch(receiveArticles(json))
        } catch (e) {
            console.log('error:', e)
        }

I already use mapDispatchToProps in the component. Is there any similar way/method I can use in action creator so that I don't have to dispatch actions manually one by one?

Body:
redux's store.dispatch() is not an asynchronous function, so there is no need to await its return.  It will still work because awaiting non-async functions casts them to an immediately-resolving promise.

With regard to dispatching multiple actions, you will need to manually dispatch every action that you need.  The question becomes: why do you need to dispatch so many actions?  In general for an ajax-calling thunk you will use a started, succeeded and failed action, and not many more.

export const fetchArticles = () => async (dispatch) => {
    try {
        dispatch(requestArticlesStarted())
        const response = await fetch('www.abc.com')
        const json = await response.json()
        dispatch(requestArticlesSucceeded(json))
    } catch (e) {
        console.log('error:', e);
        dispatch(requestArticlesFailed(e));
    }
}


问:
MySQL INNER JOIN returns zero results if all values are not found
I have the following query that works great when all of the INNER JOIN criteria is met.  Unfortunately, this query returns zero results when for example INNER JOIN TableSample6 ON TableSample1.Field4 = TableSample6.Field6 is not found.

Can I restructure this query to return results even if some of the INNER JOIN values do not have a match in some cases?

```<code>SELECT DISTINCT
    TableSample1.Field4,
    TableSample.Field2,
    TableSample2.Field2,
    TableSample3.Field3,
    TableSample4.Field4,
    TableSample5.Field1,
    TableSample.Field3,
    TableSample6.Field1,
    TableSample6.Field2,
    TableSample7.Field7,
    TableSample3.Field4,
    TableSample4.Field2,
    TableSample5.Field4
FROM TableSample1
        INNER JOIN TableSample2 ON TableSample1.Field2 = TableSample2.Field4
        INNER JOIN TableSample ON TableSample1.Field6 = TableSample.Field4
        INNER JOIN TableSample3 ON TableSample1.Field3 = TableSample3.Field2
        INNER JOIN TableSample4 ON TableSample1.Field7 = TableSample4.Field3
        INNER JOIN TableSample5 ON TableSample1.Field8 = TableSample5.Field2
        INNER JOIN TableSample6 ON TableSample1.Field4 = TableSample6.Field6
WHERE (((TableSample1.Field4)="xxxxxx" AND (TableSample.Field2)="xxxxxx"))
    ORDER BY TableSample1.Field2;
</code>```

答:
You could use LEFT JOIN:

```<code>SELECT DISTINCT
    t1.Field4,
    t.Field2,
    t2.Field2,
    t3.Field3,
    t4.Field4,
    t5.Field1,
    t.Field3,
    t6.Field1,
    t6.Field2,
    t7.Field7,     -- PROBLEM: you never join to TableSample7
    t3.Field4,
    t4.Field2,
    t5.Field4
FROM TableSample1 t1
LEFT JOIN TableSample2 t2
    ON t1.Field2 = t2.Field4
LEFT JOIN TableSample t
    ON t1.Field6 = t.Field4
LEFT JOIN TableSample3 t3
    ON t1.Field3 = t3.Field2
LEFT JOIN TableSample4 t4
    ON t1.Field7 = t4.Field3
LEFT JOIN TableSample5 t5
    ON t1.Field8 = t5.Field2
LEFT JOIN TableSample6 t6
    ON t1.Field4 = t6.Field6
WHERE t1.Field4 = "xxxxxx" AND
      t.Field2 = "xxxxxx"
ORDER BY t1.Field2;
</code>```

You could also use COALESCE() to handle records which do not match to all of the tables.  For example, if TableSample2.Field2 were varchar, you could use COALESCE(t2.Field2, 'NA') to show NA instead of NULL.

Body:
I have the following query that works great when all of the INNER JOIN criteria is met.  Unfortunately, this query returns zero results when for example INNER JOIN TableSample6 ON TableSample1.Field4 = TableSample6.Field6 is not found.

Can I restructure this query to return results even if some of the INNER JOIN values do not have a match in some cases?

SELECT DISTINCT
    TableSample1.Field4,
    TableSample.Field2,
    TableSample2.Field2,
    TableSample3.Field3,
    TableSample4.Field4,
    TableSample5.Field1,
    TableSample.Field3,
    TableSample6.Field1,
    TableSample6.Field2,
    TableSample7.Field7,
    TableSample3.Field4,
    TableSample4.Field2,
    TableSample5.Field4
FROM TableSample1
        INNER JOIN TableSample2 ON TableSample1.Field2 = TableSample2.Field4
        INNER JOIN TableSample ON TableSample1.Field6 = TableSample.Field4
        INNER JOIN TableSample3 ON TableSample1.Field3 = TableSample3.Field2
        INNER JOIN TableSample4 ON TableSample1.Field7 = TableSample4.Field3
        INNER JOIN TableSample5 ON TableSample1.Field8 = TableSample5.Field2
        INNER JOIN TableSample6 ON TableSample1.Field4 = TableSample6.Field6
WHERE (((TableSample1.Field4)="xxxxxx" AND (TableSample.Field2)="xxxxxx"))
    ORDER BY TableSample1.Field2;

Body:
You could use LEFT JOIN:

SELECT DISTINCT
    t1.Field4,
    t.Field2,
    t2.Field2,
    t3.Field3,
    t4.Field4,
    t5.Field1,
    t.Field3,
    t6.Field1,
    t6.Field2,
    t7.Field7,     -- PROBLEM: you never join to TableSample7
    t3.Field4,
    t4.Field2,
    t5.Field4
FROM TableSample1 t1
LEFT JOIN TableSample2 t2
    ON t1.Field2 = t2.Field4
LEFT JOIN TableSample t
    ON t1.Field6 = t.Field4
LEFT JOIN TableSample3 t3
    ON t1.Field3 = t3.Field2
LEFT JOIN TableSample4 t4
    ON t1.Field7 = t4.Field3
LEFT JOIN TableSample5 t5
    ON t1.Field8 = t5.Field2
LEFT JOIN TableSample6 t6
    ON t1.Field4 = t6.Field6
WHERE t1.Field4 = "xxxxxx" AND
      t.Field2 = "xxxxxx"
ORDER BY t1.Field2;

You could also use COALESCE() to handle records which do not match to all of the tables.  For example, if TableSample2.Field2 were varchar, you could use COALESCE(t2.Field2, 'NA') to show NA instead of NULL.


问:
DHGEX failing with 2048-bit key under Java 8, but succeeding with 1024-bit key
I'm using JSCH 0.1.53 to connect to a remote SSH server, which uses a 1024-bit RSA key.  We are able to connect successfully to the remote server when we also use a 1024-bit RSA key, but when we generated stronger 2048-bit keys we stopped being able to connect.  We got an error message that reads "prime size must be multiple of 64, and can only range from 512 to 2048" and that originates from a call to DHGEX.java (Diffie-Hellman Group EXchange).

We're running Java 1.8, and the error message correctly specifies a max bit size of 2048, so the problem is not the JCE key limitation of 1024 bits in Java 1.6 and 1.7.  And we've confirmed that both our private and our public key are in fact 2048 bits, via openssl rsa -text -noout -in id_rsa and ssh-keygen -lf id_rsa.pub.

Since everything looked fine on our end, I started adding debugging lines to the JSCH code and recompiling the JAR, and I was eventually able to determine that the modulus being passed to us during the key exchange was in fact 2047 bits long.  Now, 2047 bits in length doesn't inherently mean that you didn't generate a 2048-bit key or that it's any less strong than a key that actually contains 2048 bits, it just means that you happened to get two primes that multiplied together to something whose first bit was a 0. So it's expected behavior (some of the time) and the JCE check should probably be (n % 64 == 0 || n % 64 == 63).  But JCE is a stickler on the point, so it rejects this key for not being of a length it considers valid.

Based on that, I thought I'd found the problem: the remote server had generated a 2048-bit key that only contained 2047 bits, so they just needed to generate a new one (and keep doing it till they got one that really was 2048 bits).  But when I asked their administrators about it, they were insistent that they were using a 1024-bit key, and indeed that's what you get in the known_hosts file when you SSH over.  So that doesn't appear to be the cause after all.

So I started logging the contents of the buffer that contained what they sent us and pulling out the p and g values (modulus and group), and I discovered that in just a few short periods of testing over a couple of days, there were 33 different modulus values, and all of them differed by only the last few characters when encoded in either base 64 or base 10.  Modulii values were reused, sometimes only once and sometimes a dozen times, but there were lots of distinct values, so the keys are neither generated for one-time use nor generated once and reused forever.

Is this (having the server send many different keys that are very close numerically, with some reuse but many unique values) expected behavior under any conditions, and especially is this expected behavior when the client uses a 2048-bit key but the server uses a 1024-bit key?  I know nothing about Diffie-Hellman group exchange besides what I've read since I started investigating last week, so maybe this is just how it works, but it seems strange to me.

Also, does the SSH standard specify anything about how keys should be generated in cases like these?  I haven't yet found out what SSH server the far side is using (I suspect OpenSSH, but don't know for sure and don't know what version), but I'm hopeful that there might be some standard that forces the use of keys that are of the same size as was requested (between 1^(n-1) and 1^n - 1), and that the remote server might have an option to force this or that I can submit a bug against them to get them to change the behavior.  I'll probably also submit a bug against the JDK to allow keys of n-1 bits, with 0-padding for the first bit.

Any guidance that anyone can give would be greatly appreciated.

I've also posted this question to the JSCH mailing list: https://sourceforge.net/p/jsch/mailman/message/35042955/

UPDATE:

After further reading, I believe that Diffie-Hellman's forward secrecy characteristic means that different primes (often from a pre-generated set stored somewhere like /etc/ssl/moduli) would be used for each session (source: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Forward_secrecy) and that the prime used is not actually the RSA key (source: https://stackoverflow.com/a/23346185/1247705), so the fact that many different p values are seen no longer seems like a concern.  I'm still surprised that they're so close in value, but maybe that's expected as well.

The far side is using Solaris SSH 1.1.4 (which as I understand it is based on OpenSSH) as the SSH daemon.  Is it expected that that daemon would pass 2047-bit primes as part of the Diffie-Hellman key exchange, and is there anything that can be done to get it to send 2048-bit primes instead?

答:
We fixed similar symptoms with:

```<code>Security.insertProviderAt(new BouncyCastleProvider(), 1)
</code>```

we were using Jsch 0.1.54 and saw:

java.security.InvalidAlgorithmParameterException: DH key size must be multiple of 64, and can only range from 512 to 4096 (inclusive). The specific key size 2047 is not supported

possibly related is JDK-8164963: InvalidAlgorithmParameterException prime size issue after JDK upgrade with JSCH libraries

Body:
We fixed similar symptoms with:

Security.insertProviderAt(new BouncyCastleProvider(), 1)

we were using Jsch 0.1.54 and saw:

java.security.InvalidAlgorithmParameterException: DH key size must be multiple of 64, and can only range from 512 to 4096 (inclusive). The specific key size 2047 is not supported

possibly related is JDK-8164963: InvalidAlgorithmParameterException prime size issue after JDK upgrade with JSCH libraries


问:
Access Microsoft sql database from Folder
I have MS sql database in folder on my computer and i am trying to connect to that database from asp.net(c#) application but it is throwing errors. Any help please.

My Web.config

```<code><connectionStrings>
<add
<add name="con" connectionString="Server=kuldeep;Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\jambtjh.mdf;
Initial Catalog=jambtjh;Integrated Security=True; ID=sa;Password=123;" providerName="System.Data.SqlClient" />
<connectionStrings>
</code>```

c# Code-

```<code>public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["con2"].ConnectionString);
    SqlCommand cmd,cmd1;
    SqlDataReader dr,dr1;
    con.Open();
    string str = "select * from testtable";
    cmd = new SqlCommand(str, con);
}
</code>```

答:
Thanks you @Vandita for you help. You are right id and password is not required.
I have added few things to your answer and it is working for me.
Just sharing the line here :</p>

```<code><add name="con" connectionString="Data Source=(LocalDb)\MSSQLLocalDB   AttachDbFilename=|DataDirectory|\jambtjh.mdf;
        Initial Catalog=jambtjh;Integrated Security=True" providerName="System.Data.SqlClient" />
</code>```

Body:
I have MS sql database in folder on my computer and i am trying to connect to that database from asp.net(c#) application but it is throwing errors. Any help please.

My Web.config

<connectionStrings>
<add
<add name="con" connectionString="Server=kuldeep;Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\jambtjh.mdf;
Initial Catalog=jambtjh;Integrated Security=True; ID=sa;Password=123;" providerName="System.Data.SqlClient" />
<connectionStrings>

c# Code-

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["con2"].ConnectionString);
    SqlCommand cmd,cmd1;
    SqlDataReader dr,dr1;
    con.Open();
    string str = "select * from testtable";
    cmd = new SqlCommand(str, con);
}

Body:
Thanks you @Vandita for you help. You are right id and password is not required.
I have added few things to your answer and it is working for me.
Just sharing the line here :

<add name="con" connectionString="Data Source=(LocalDb)\MSSQLLocalDB   AttachDbFilename=|DataDirectory|\jambtjh.mdf;
        Initial Catalog=jambtjh;Integrated Security=True" providerName="System.Data.SqlClient" />


问:
Which is better, return value or out parameter?
If we want to get a value from a method, we can use either return value, like this:

```<code>public int GetValue();
</code>```

or:

```<code>public void GetValue(out int x);
</code>```

I don't really understand the differences between them, and so, don't know which is better. Can you explain me this?

Thank you.

答:
return value is the normal value which is returned by your method.

Where as out parameter, well out and ref are 2 key words of C# they allow to pass variables as reference.

The big difference between ref and out is, ref should be initialised before and out don't

Body:
If we want to get a value from a method, we can use either return value, like this:

public int GetValue();

or:

public void GetValue(out int x);

I don't really understand the differences between them, and so, don't know which is better. Can you explain me this?

Thank you.


问:
What is the difference between service and server?
It seems that both service and server refer to some web based application. But is there any precise definition of the two terms?</p>

答:
A server offers one or more services. Server is also a more technical term, whereas service is more a term off the problem domain.

You also need to distinguish between:

Server as hardware (see post from Dan D)

Server as software (eg. Apache HTTP server)

You can find more elaborate definiton on Wikipedia:

Service

Server


问:
populate GridLayoutManager first by row and then by column
I'm having an issue while populating a recycler view with a GridLayoutManager.

I need to fulfill the first row, and after this is complete, go to the second row. I did an algorithm that reorders the list so it's being shown properly and I can get the item clicked without doing any mapping-unmapping thing. This is working fine, but the trouble appears when all the items can be shown on the screen without scrolling.

For example, I have 4 items and I need to show them in a 2-row grid layout (horizontal layout). The screen has space for 3 items, so I need them to be in the first row, while the 4th item should be the only one in the second row.

To give you a picture of what I have by default:

```<code>0 2
1 3
</code>```

And what I need is:

```<code>0 1 2
3
</code>```

Any ideas?

Edit:
As requested, here is the code I'm using:

```<code>    GridLayoutManager layoutManager = new GridLayoutManager(getContext(),2,LinearLayoutManager.HORIZONTAL, false);
</code>```

答:
When you are defining your gridLayoutManager, you specify the number of columns

```<code>RecyclerView rView = new RecyclerView(this);
rView.setLayoutManager(new GridLayoutManager(context, <your number of columns>));
</code>```

Setting this value to 3 (in your case) would result in three columns, with two rows. Your array adapter populates the fields from left to right, then top to bottom.

Body:
I'm having an issue while populating a recycler view with a GridLayoutManager.

I need to fulfill the first row, and after this is complete, go to the second row. I did an algorithm that reorders the list so it's being shown properly and I can get the item clicked without doing any mapping-unmapping thing. This is working fine, but the trouble appears when all the items can be shown on the screen without scrolling.

For example, I have 4 items and I need to show them in a 2-row grid layout (horizontal layout). The screen has space for 3 items, so I need them to be in the first row, while the 4th item should be the only one in the second row.

To give you a picture of what I have by default:

0 2
1 3

And what I need is:

0 1 2
3

Any ideas?

Edit:
As requested, here is the code I'm using:

    GridLayoutManager layoutManager = new GridLayoutManager(getContext(),2,LinearLayoutManager.HORIZONTAL, false);

Body:
When you are defining your gridLayoutManager, you specify the number of columns

RecyclerView rView = new RecyclerView(this);
rView.setLayoutManager(new GridLayoutManager(context, <your number of columns>));

Setting this value to 3 (in your case) would result in three columns, with two rows. Your array adapter populates the fields from left to right, then top to bottom.


问:
Axis wsdl2java maven plugin with xmlbeans doesn't include resources folder
I'm using axis2 to re-generate the client code for an updated webservice that I need to use, for a legacy application.

Being a legacy application I would like to avoid changing the code that has been already written, and re-generate the classes as they were generated who-know-how-many years ago by the eclipse plugin, but this time using maven instead of eclipse.

So I seen that they were generated using axis2 and xmlbeans, and I produced the configuration in the maven plugin:

```<code><plugin>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
    <version>1.5.6</version>
    <executions>
        <execution>
            <id>TheirsWs</id>
            <goals>
                <goal>wsdl2code</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <packageName>it.theirs.ws</packageName>
                <wsdlFile>${basedir}/src/main/resources/theirWs.wsdl</wsdlFile>
                <generateServerSide>false</generateServerSide>
                <databindingName>xmlbeans</databindingName>
                <unpackClasses>true</unpackClasses>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

What happen now is a very nice thing.
The plugin generate a .class file in the generated-sources / axis2 / wsdl2code / resource folder, However it is not added by maven to the final package, causing a ClassNotFoundException when calling the webservice.

答:
I solve the problem by adding the resource folder into the JAR using the maven default feature of including and excluding folder. The solution for your case will be:

```<code><build>
<!-- This will the MAVEN to copy the entire folder, you can copy only the .class files -->
<resources>
        <resource>
            <directory>${project.build.directory}/generated-src/resources</directory>
            <includes>
                 <include>**/*</include>
            </includes>
        </resource>
    </resources>
<plugin>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
    <version>1.5.6</version>
    <executions>
        <execution>
            <id>TheirsWs</id>
            <goals>
                <goal>wsdl2code</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <packageName>it.theirs.ws</packageName>
                <wsdlFile>${basedir}/src/main/resources/theirWs.wsdl</wsdlFile>
                <generateServerSide>false</generateServerSide>
                <databindingName>xmlbeans</databindingName>
                <!-- I add this line just to be easy to referenciate the souce -->
                <outputDirectory>${project.build.directory}/generated-src</outputDirectory>
                <unpackClasses>true</unpackClasses>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Body:
I'm using axis2 to re-generate the client code for an updated webservice that I need to use, for a legacy application.

Being a legacy application I would like to avoid changing the code that has been already written, and re-generate the classes as they were generated who-know-how-many years ago by the eclipse plugin, but this time using maven instead of eclipse.

So I seen that they were generated using axis2 and xmlbeans, and I produced the configuration in the maven plugin:

<plugin>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
    <version>1.5.6</version>
    <executions>
        <execution>
            <id>TheirsWs</id>
            <goals>
                <goal>wsdl2code</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <packageName>it.theirs.ws</packageName>
                <wsdlFile>${basedir}/src/main/resources/theirWs.wsdl</wsdlFile>
                <generateServerSide>false</generateServerSide>
                <databindingName>xmlbeans</databindingName>
                <unpackClasses>true</unpackClasses>
            </configuration>
        </execution>
    </executions>
</plugin>

What happen now is a very nice thing.
The plugin generate a .class file in the generated-sources / axis2 / wsdl2code / resource folder, However it is not added by maven to the final package, causing a ClassNotFoundException when calling the webservice.

Body:
I solve the problem by adding the resource folder into the JAR using the maven default feature of including and excluding folder. The solution for your case will be:

<build>
<!-- This will the MAVEN to copy the entire folder, you can copy only the .class files -->
<resources>
        <resource>
            <directory>${project.build.directory}/generated-src/resources</directory>
            <includes>
                 <include>**/*</include>
            </includes>
        </resource>
    </resources>
<plugin>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
    <version>1.5.6</version>
    <executions>
        <execution>
            <id>TheirsWs</id>
            <goals>
                <goal>wsdl2code</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <packageName>it.theirs.ws</packageName>
                <wsdlFile>${basedir}/src/main/resources/theirWs.wsdl</wsdlFile>
                <generateServerSide>false</generateServerSide>
                <databindingName>xmlbeans</databindingName>
                <!-- I add this line just to be easy to referenciate the souce -->
                <outputDirectory>${project.build.directory}/generated-src</outputDirectory>
                <unpackClasses>true</unpackClasses>
            </configuration>
        </execution>
    </executions>
</plugin>


答:
1 Command line argument

Assuming you're trying to pass the output of a linux command to java when starting the java program, this is simple to do in bash. Use back-ticks (`) to surround the linux command in the place where you put command line arguments. E.g.:

```<code>$ java [... java options, like -jar path/to/file.jar ...] -- `linux-command`
</code>```

(You may have to do some quotes or escaping of some sort if the output contains spaces.)

Then, in your java program, the value will be in the args array:

```<code>public static void main(String args[]) {
    String linuxCommandOutput = args[0];
    // rest of program...
}
</code>```

2 System Property

If you can't use args for some reason, you can try to use system properties. Again, use back-ticks (`) to surround the linux command and store it in a system property with -D. Like so:

```<code>$ java -Dvariable=`linux-command` [... java options ...]
</code>```

Then, in your java program, read the value of the system property:

```<code>public static void main(String args[]) {
    String linuxCommandOutput = System.getProperty("variable");
    // rest of program...
}
</code>```

Title: how to get from Linux command inside shell a string or value to JAVA?

Body: it's possible to get the output of a command inside linux shell to a JAVA app? if it's possible how? I see the chance to  execute from JAVA a shell command i wish the opposite result : SHELL COMMANDS OUTPUT  --->to---> Java VARIABLE or STRING.  thanks for reply

Body:
1 Command line argument

Assuming you're trying to pass the output of a linux command to java when starting the java program, this is simple to do in bash. Use back-ticks (`) to surround the linux command in the place where you put command line arguments. E.g.:

$ java [... java options, like -jar path/to/file.jar ...] -- `linux-command`

(You may have to do some quotes or escaping of some sort if the output contains spaces.)

Then, in your java program, the value will be in the args array:

public static void main(String args[]) {
    String linuxCommandOutput = args[0];
    // rest of program...
}

2 System Property

If you can't use args for some reason, you can try to use system properties. Again, use back-ticks (`) to surround the linux command and store it in a system property with -D. Like so:

$ java -Dvariable=`linux-command` [... java options ...]

Then, in your java program, read the value of the system property:

public static void main(String args[]) {
    String linuxCommandOutput = System.getProperty("variable");
    // rest of program...
}