问:
How to rewrite qi parsers with inherited attributes in x3?
If the inherited attributes are used in semantic actions, we can use x3::with directive.

What if we want to use the attributes as part of the parser? For example a simple parser matches 1 or more alphabet characters except the character is from a parameter char set.

```<code>qi::rule<std::string::const_iterator, qi::unused_type(char const*)> rule =
    +(qi::alpha - qi::char_(qi::_r1));
</code>```

Or the parameter char set could be used as a lazy parser.

```<code>qi::rule<std::string::const_iterator, qi::unused_type(char const*)> rule =
    +(qi::alpha - qi::lazy(qi::_r1));
</code>```

x3::with directive put this local value in the context. I'm not sure if we could use this context outside a semantic action and eventually generate a parser.

答:
Simply let go of the old habit of rule-ifying everything.

```<code>#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace x3 = boost::spirit::x3;

template <typename... Args>
auto negate(Args&&... p) {
    return +(x3::char_ - x3::char_(std::forward<Args>(p)...));
};

int main() {
    std::string input("all the king's men and all the king's horses"), parsed;
    if (parse(input.begin(), input.end(), negate("horse"), parsed))
        std::cout << "'" << input << "' -> '" << parsed << "'\n";
}
</code>```

Live On Coliru, prints:

'all the king's men and all the king's horses' -> 'all t'

Second flavour:

```<code>#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace x3 = boost::spirit::x3;

template <typename Sub>
auto negate(Sub p) {
    return +(x3::char_ - x3::as_parser(p));
};

int main() {
    std::string input("all the king's men and all the king's horses"), parsed;
    if (parse(input.begin(), input.end(), negate("horse"), parsed))
        std::cout << "'" << input << "' -> '" << parsed << "'\n";
}
</code>```

Live On Coliru, prints:

'all the king's men and all the king's horses' -> 'all the king's men and all the king's '

More complicated stuff

You can also aggregate sub parsers in a custom parser:

Spirit-Qi: How can I write a nonterminal parser?

If you need resursive rules with passing around, I'd suggest x3::with<> (although I'm not sure the contexts build re-entrant state for the with<>, you need to test the precise semantics unless you can find documentation for it)

Body:
If the inherited attributes are used in semantic actions, we can use x3::with directive.

What if we want to use the attributes as part of the parser? For example a simple parser matches 1 or more alphabet characters except the character is from a parameter char set.

qi::rule<std::string::const_iterator, qi::unused_type(char const*)> rule =
    +(qi::alpha - qi::char_(qi::_r1));

Or the parameter char set could be used as a lazy parser.

qi::rule<std::string::const_iterator, qi::unused_type(char const*)> rule =
    +(qi::alpha - qi::lazy(qi::_r1));

x3::with directive put this local value in the context. I'm not sure if we could use this context outside a semantic action and eventually generate a parser.

Body:
Simply let go of the old habit of rule-ifying everything.

#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace x3 = boost::spirit::x3;

template <typename... Args>
auto negate(Args&&... p) {
    return +(x3::char_ - x3::char_(std::forward<Args>(p)...));
};

int main() {
    std::string input("all the king's men and all the king's horses"), parsed;
    if (parse(input.begin(), input.end(), negate("horse"), parsed))
        std::cout << "'" << input << "' -> '" << parsed << "'\n";
}

Live On Coliru, prints:

'all the king's men and all the king's horses' -> 'all t'

Second flavour:

#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace x3 = boost::spirit::x3;

template <typename Sub>
auto negate(Sub p) {
    return +(x3::char_ - x3::as_parser(p));
};

int main() {
    std::string input("all the king's men and all the king's horses"), parsed;
    if (parse(input.begin(), input.end(), negate("horse"), parsed))
        std::cout << "'" << input << "' -> '" << parsed << "'\n";
}

Live On Coliru, prints:

'all the king's men and all the king's horses' -> 'all the king's men and all the king's '

More complicated stuff

You can also aggregate sub parsers in a custom parser:

Spirit-Qi: How can I write a nonterminal parser?

If you need resursive rules with passing around, I'd suggest x3::with<> (although I'm not sure the contexts build re-entrant state for the with<>, you need to test the precise semantics unless you can find documentation for it)


来源: stackexchange

问:
C++ Method Override and Overloading (Compiler level)
I know what the difference between the two. Overriding basically lets you "redefine" your a method in a child class and overloading basically lets you "redefine" your method with different arguments or parameters. I'm a little confused on what's going on under the hood though. I read that when you overload a method, the compiler will have all the overloaded methods and find the best match or report an error if none exists. This is obviously done during compile time but I'm confused on how Override works. I've read that handling overrides is extremely hard because you'll have to check if the return type matches with the class hierarchy and there can be a lot of class levels to check

(ie. class Living is the super class of Human and Animal. Human and Animal can have many derived classes which means we will have a deep level of classes).

Without getting too detailed, how does overriding work at the compiler level and why is it that overriding is done during run time and not compile time?

答:
It depends on if the overridden method is virtual or not. If the overridden method is not virtual, then under the hood it usually works in the same way as overloading, the compiler looks at the static type of the object and calls the correct function based on that.

For objects with virtual methods a vtable is usually used. This is a collection of function pointers to the virtual methods. The reason this is done at run time is to allow for runtime polymorphism. The usual way that a vtable is generate is the compilier will generate a single vtable for each class and populate it with the required pointers at compile time and include this in the executable. The constructor will then set a hidden pointer in the class to point to the correct vtable. When looking up methods it first dereferences the hidden pointer to find the vtable then dereferences the correct slot from the vtable.

ContentLicense: CC BY-SA 3.0


问:
Get value of comboboxitem contentcontrol in wpf
I am new to WPF.
I want to know how can i get the selectedtext if the text that i want is placed inside a control inside comboboxitem and not directly inside comboboxitem.
I know this is very basic,but would appreciate if someone could provide me a simple and quick solution

My simple combobox code is as follows:

```<code><ComboBox x:Name="cmdTest">
    <ComboBoxItem>
        <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Grid Width="250">
            <TextBlock Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
        </Grid>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
</ComboBox>
</code>```

答:
First change your xaml code:<ComboBox x:Name="cmdTest"  HorizontalContentAlignment="Stretch" SelectedValuePath="Text">
            <ComboBoxItem Padding="0" >
                <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
            </ComboBoxItem>
            <ComboBoxItem Padding="0">
                <TextBlock  Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
            </ComboBoxItem>
            <ComboBoxItem Padding="0">
                <TextBlock  Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
            </ComboBoxItem>
        </ComboBox>

After for get text value use:

```<code> var z = cmdTest.Text.ToString();
            MessageBox.Show(z);
</code>```

Body:
I am new to WPF.
I want to know how can i get the selectedtext if the text that i want is placed inside a control inside comboboxitem and not directly inside comboboxitem.
I know this is very basic,but would appreciate if someone could provide me a simple and quick solution

My simple combobox code is as follows:

<ComboBox x:Name="cmdTest">
    <ComboBoxItem>
        <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Grid Width="250">
            <TextBlock Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
        </Grid>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
    </ComboBoxItem>
</ComboBox>

Body:
First change your xaml code:<ComboBox x:Name="cmdTest"  HorizontalContentAlignment="Stretch" SelectedValuePath="Text">
            <ComboBoxItem Padding="0" >
                <TextBlock Text="RED" Background="RED" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
            </ComboBoxItem>
            <ComboBoxItem Padding="0">
                <TextBlock  Text="GREEN" Background="GREEN" Foreground="White" FontFamily="Sans Serif" FontSize="14" Height="15"/>
            </ComboBoxItem>
            <ComboBoxItem Padding="0">
                <TextBlock  Text="BLUE" Background="Blue" Foreground="White" FontFamily="Sans Serif" FontSize="14"/>
            </ComboBoxItem>
        </ComboBox>

After for get text value use:

 var z = cmdTest.Text.ToString();
            MessageBox.Show(z);


Title: Removing the last 2 elements in an array - Ruby

Body: If I have this array - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1, 18, 21] how can I get this return - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1] I've tried this and it doesn't work. array.size - 2..

Body:
The pop method removes (and returns) the last element from an array. It takes an optional argument:

a = [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1, 18, 21]

a.pop(2)

p a # => [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1]


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
qBasic, when I was around 10 - 12 i started making a copy of that "The doctor asks you weird questions"-game. Which ended up as a lot of nasty questions. That's when i knew I wanted to work with computers.

A couple of years later i started playing with HTML and PHP, giving me a couple of customers and i started a company, that's when i knew i could get bloody rich on this :)

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: Filip Ekberg


问:
FacebookApiException needs to apply security to a method it doesn't override?
I'm building a very crude facebook application as a school project and I've come across the most interesting error. When attempting to make any call to FacebookApp.Api() involving "me" I get the following exception:

System.TypeLoadException: Inheritance
  security rules violated while
  overriding member:
  Facebook.FacebookApiException.GetObjectData(System.Runtime.Serialization.SerializationInfo,
  System.Runtime.Serialization.StreamingContext)'.
  Security accessibility of the
  overriding  method must match the
  security accessibility of the method
  being overriden.

Stack Trace:

```<code>[TypeLoadException: Inheritance security rules violated while overriding member: 'Facebook.FacebookApiException.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.]
   Facebook.FacebookApp.WithMirrorRetry(Func`1 body) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:758
   Facebook.FacebookApp.OAuthRequest(Uri uri, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:545
   Facebook.FacebookApp.Graph(String path, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:529
   Facebook.FacebookAppBase.Api(String path, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookAppBase.cs:415
   Facebook.FacebookAppBase.Api(String path) in d:\Projects\facebooksdk\src\Facebook\FacebookAppBase.cs:350
   Callback.Page_Load(Object sender, EventArgs e) +622
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
</code>```

As far as I can tell, the error comes from the fact that FacebookApiException is overriding Exception's getDataObject and not doing so with the correct security. However, I don't see FacebookApiException overriding the method at all in the source.

Any help would be appreciated.

答: This is a known bug in version 4.0.2 of the Facebook C# SDK. The bug is fixed in code and will be fixed in the next release. The fix is to run the App in full trust or to use the most recent build from source control.</p>

Body:
I'm building a very crude facebook application as a school project and I've come across the most interesting error. When attempting to make any call to FacebookApp.Api() involving "me" I get the following exception:

System.TypeLoadException: Inheritance
  security rules violated while
  overriding member:
  Facebook.FacebookApiException.GetObjectData(System.Runtime.Serialization.SerializationInfo,
  System.Runtime.Serialization.StreamingContext)'.
  Security accessibility of the
  overriding  method must match the
  security accessibility of the method
  being overriden.

Stack Trace:

[TypeLoadException: Inheritance security rules violated while overriding member: 'Facebook.FacebookApiException.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.]
   Facebook.FacebookApp.WithMirrorRetry(Func`1 body) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:758
   Facebook.FacebookApp.OAuthRequest(Uri uri, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:545
   Facebook.FacebookApp.Graph(String path, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookApp.cs:529
   Facebook.FacebookAppBase.Api(String path, IDictionary`2 parameters, HttpMethod httpMethod) in d:\Projects\facebooksdk\src\Facebook\FacebookAppBase.cs:415
   Facebook.FacebookAppBase.Api(String path) in d:\Projects\facebooksdk\src\Facebook\FacebookAppBase.cs:350
   Callback.Page_Load(Object sender, EventArgs e) +622
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

As far as I can tell, the error comes from the fact that FacebookApiException is overriding Exception's getDataObject and not doing so with the correct security. However, I don't see FacebookApiException overriding the method at all in the source.

Any help would be appreciated.


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

答:
It's not what you want but could help. You can use Redis as a middleware. Use Redis publish/subscribe message system.
Redis publish/subscribe message system</p>

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?


问:
MvvmCross fragment backstack not restored properly
Hi Xamarin/MvvmCross devs,

I am having a problem with the MvxCachingFragmentCompatActivity, or I think it's a problem. I don't know if it's expected behaviour or not.

In my app I use fragments inside a container view. I'm having a problem with the FragmentBackStack when the activity is being restored after destruction. If I go three levels in from my initial fragment, go into the background and come back to the foreground only the last two views are restored. Note this is with "Don't keep activities" switched on in developer options.

Is there any specific setup/indication I have to give to MvvmCross to indicate too them that I want them to handle my viewmodel save/restore functionality. I don't see any in the samples I went through.

I use to use a manual approach with older versions of MvvmCross where I stored a reference to all my viewmodels in the ContainerViewModel and then just read that up when it's restored. But this doesn't work particularly well when you can have multiple of the same view on the backstack.

I have nothing special in the app, it's base usage of MvxFragment for all the views. I do have a custom presenter, but I only override ShowFragment so I can show popup views instead of replacing. None of the views not being restored uses this functionality, so it's not interfering with anything.

Any help would be grately appreciated.
Dane

Update 1

Keep in mind that views in this case are MvxFragments.

while researching this I found some weird backstack behaviour associated with the MvxCachingFragmentActivity. While doing the restore functionality I got fragment tag not found in cache errors, so I added this

```<code>FragmentCacheConfiguration.RegisterFragmentToCache<View, ViewModel>(typeof(ViewModel).FullName);
</code>```

When I add this for my view that's displayed second (after the first view), the first view is never added too the backstack. Causing a weird back navigation bug where back would close on the second view even if AddToBackstack is set too true for the first view we navigated from.

When I remove that line the navigation works completely fine. I have no idea why that is.

答:
There were two reasons the MvxCachingFragment was not restoring the fragment backstack properly and had the weird navigation issues after coming back from the backgroun.

I did not set RetainInstance = true; for the fragments. Since I had many I created a base fragment using MvxFragment and set Retain Instance true in the constructor.

I did not have MvvmCross-Json-Plugin installed. Which is used for deserializing the stored viewmodel information from the Bundle.

Body:
Hi Xamarin/MvvmCross devs,

I am having a problem with the MvxCachingFragmentCompatActivity, or I think it's a problem. I don't know if it's expected behaviour or not.

In my app I use fragments inside a container view. I'm having a problem with the FragmentBackStack when the activity is being restored after destruction. If I go three levels in from my initial fragment, go into the background and come back to the foreground only the last two views are restored. Note this is with "Don't keep activities" switched on in developer options.

Is there any specific setup/indication I have to give to MvvmCross to indicate too them that I want them to handle my viewmodel save/restore functionality. I don't see any in the samples I went through.

I use to use a manual approach with older versions of MvvmCross where I stored a reference to all my viewmodels in the ContainerViewModel and then just read that up when it's restored. But this doesn't work particularly well when you can have multiple of the same view on the backstack.

I have nothing special in the app, it's base usage of MvxFragment for all the views. I do have a custom presenter, but I only override ShowFragment so I can show popup views instead of replacing. None of the views not being restored uses this functionality, so it's not interfering with anything.

Any help would be grately appreciated.
Dane

Update 1

Keep in mind that views in this case are MvxFragments.

while researching this I found some weird backstack behaviour associated with the MvxCachingFragmentActivity. While doing the restore functionality I got fragment tag not found in cache errors, so I added this

FragmentCacheConfiguration.RegisterFragmentToCache<View, ViewModel>(typeof(ViewModel).FullName);

When I add this for my view that's displayed second (after the first view), the first view is never added too the backstack. Causing a weird back navigation bug where back would close on the second view even if AddToBackstack is set too true for the first view we navigated from.

When I remove that line the navigation works completely fine. I have no idea why that is.


问:
How can I change the case of a hash key?
I am writing a script which is likely to be modified by users. Currently I am storing the configuration settings inside the script. It exists in the form of a hash-of-hashes.

I would like to guard against people accidentally using lowercase characters in the hash keys, because that will break my script.

It would be simple to inspect the hash keys and merely issue warnings for any keys with lowercase characters, but I would rather fix the case sensitivity automatically.

In other words, I want to convert all the hash keys in the top-level hash to uppercase.

答:
This will convert multi level hash to lowercase</p>

```<code>my $lowercaseghash = convertmaptolowercase(\%hash);

sub convertmaptolowercase(){
    my $output=$_[0];
    while(my($key,$value) = each(%$output)){
        my $ref;
        if(ref($value) eq "HASH"){
            $ref=convertmaptolowercase($value);
        } else {
           $ref=$value;
        }
        delete $output->{$key}; #Removing the existing key
        $key = lc $key;
        $output->{$key}=$ref; #Adding new key
    }
    return $output;
}
</code>```

OwnerDisplayName: mseery

LastEditorDisplayName: brian d foy

Body:
This will convert multi level hash to lowercase

my $lowercaseghash = convertmaptolowercase(\%hash);

sub convertmaptolowercase(){
    my $output=$_[0];
    while(my($key,$value) = each(%$output)){
        my $ref;
        if(ref($value) eq "HASH"){
            $ref=convertmaptolowercase($value);
        } else {
           $ref=$value;
        }
        delete $output->{$key}; #Removing the existing key
        $key = lc $key;
        $output->{$key}=$ref; #Adding new key
    }
    return $output;
}


问:
Tableau Calculated Field error
I am trying to create a calculated field in tableau. Below is my code:

IF MONTH(date)=1 THEN CP*0.1
ELSEIF MONTH(date)=2 THEN CP*0.2
ELSE CP
ENDIF

but i keep getting an error message "expected END to match IF at character 0"

答:
You should use END instead of ENDIF...

```<code>IF MONTH(date)=1 THEN CP*0.1
ELSEIF MONTH(date)=2 THEN CP*0.2
ELSE CP
END
</code>```

Title: Tableau Calculated Field error

Body:
You should use END instead of ENDIF...

IF MONTH(date)=1 THEN CP*0.1
ELSEIF MONTH(date)=2 THEN CP*0.2
ELSE CP
END


问:
cs50 initials error with printed output
I am working on Cs50 pset2 initials. When I run the program it printed out the first 2 letters of the first name and the 2nd, 4th, and 6th letter of the last name. I am wondering if my increment is wrong? Thank you

here is my code..

```<code>#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    // variables
    string urName;
    char init;
    int i;

    // get user input
    printf("Please state your full name:\n");

    do
    {
        urName = get_string();
    }
    while (urName == NULL);

    printf("%c", toupper(urName[0]));

    for (i = 0, init = strlen(urName); i < init; i++)
    {
        if ((urName[i]) != '\0')
        {
            printf("%c", toupper(urName[i+1]));
            i++;
        }
    }

    return 0;
}
</code>```

And here is the example output..

```<code>Please state your full name:
den nguyen
DE GYN~/workspace/pset2/ $
</code>```

答:
Just as DYZ mentioned, you increment your counter at 2 instances inside your for-loop:

```<code>for (i = 0, init = strlen(urName); i < init; i++) // "i" is incremented here
{
    if ((urName[i]) != '\0')
    {
        printf("%c", toupper(urName[i+1]));
        i++; // "i" is also incremented here
    }
}
</code>```

By incrementing i twice, the compiler skips one letter for every iteration of the for-loop. To fix it, you need to remove the i++ that is inside the for-loop so that only the counter incremental within the for-loop condition is working:

```<code>for (i = 0, init = strlen(urName); i < init; i++) // "i" only needs to be incremented here
{
    if ((urName[i]) != '\0')
        printf("%c", toupper(urName[i+1]));
}
</code>```

Title: cs50 initials error with printed output

Body:
I am working on Cs50 pset2 initials. When I run the program it printed out the first 2 letters of the first name and the 2nd, 4th, and 6th letter of the last name. I am wondering if my increment is wrong? Thank you

here is my code..

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    // variables
    string urName;
    char init;
    int i;

    // get user input
    printf("Please state your full name:\n");

    do
    {
        urName = get_string();
    }
    while (urName == NULL);

    printf("%c", toupper(urName[0]));

    for (i = 0, init = strlen(urName); i < init; i++)
    {
        if ((urName[i]) != '\0')
        {
            printf("%c", toupper(urName[i+1]));
            i++;
        }
    }

    return 0;
}

And here is the example output..

Please state your full name:
den nguyen
DE GYN~/workspace/pset2/ $

Body:
Just as DYZ mentioned, you increment your counter at 2 instances inside your for-loop:

for (i = 0, init = strlen(urName); i < init; i++) // "i" is incremented here
{
    if ((urName[i]) != '\0')
    {
        printf("%c", toupper(urName[i+1]));
        i++; // "i" is also incremented here
    }
}

By incrementing i twice, the compiler skips one letter for every iteration of the for-loop. To fix it, you need to remove the i++ that is inside the for-loop so that only the counter incremental within the for-loop condition is working:

for (i = 0, init = strlen(urName); i < init; i++) // "i" only needs to be incremented here
{
    if ((urName[i]) != '\0')
        printf("%c", toupper(urName[i+1]));
}


问:
Reverting a specific old commit
Hi I have a repository on Bitbucket. I am working with a partner on a project and he pushed some updates few commits ago, working on a file, I realized that he did wrong code. I want to revert that commit, particularly that file only so I can get back code of that file only. cartitems.blade.php

Is this possible?

Attached is the image of SourceTree tool. Uncommited changes are my new changes. I want to keep these and recover that specific file only.

答: If you already pushed it to your respository and you're working in a large team, be careful, since your mates might get some frustrating merge-conflicts by doing that.</p>

Title: Reverting a specific old commit


问:
c# dot operator overhead: What is more efficient
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

```<code>public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}
</code>```

And the following two examples of usage is where I want the insight.

Example 1:

```<code>public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}
</code>```

Example 2:

```<code>public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}
</code>```

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?

答:
You will notice absolutely no optimization between the two. In fact, I suspect the compiler would optimize both types of statement into the same IL. </p>

<p>The latter example is more readable, however, so I'd opt for that approach. </p>

Body:
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}

And the following two examples of usage is where I want the insight.

Example 1:

public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}

Example 2:

public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?

Body:
You will notice absolutely no optimization between the two. In fact, I suspect the compiler would optimize both types of statement into the same IL.

The latter example is more readable, however, so I'd opt for that approach.


问:
Vim alternatives file
```<code>:[range]s/{pattern}/{string}/[flags] [count]
            For each line in [range] replace a match of {pattern}
            with {string}.

The "or" operator in a pattern is "\|".  Example:
    /foo\|bar
This matches "foo" or "bar".  More alternatives can be concatenated:
    /one\|two\|three
Matches "one", "two" and "three".
</code>```

Can we use a pattern/alternatives file with 3 lines?

one

two

three

答:
The following command works on my system:

let @a = system('cat repl.vim | tr "\n" "|"') | exe '%s/\v'.@a.'<bs>/x/g'

Here, I have a list of words in the file repl.vim. The first part of the command uses let to save the list of words in registry a replacing every newline \n with an or operator |. In the second part exe %s performs the substitution.

In practice, if repl.vim contains:

```pattern1
pattern2
pattern3```

Running the command will result in:

```%s/\vpattern1|pattern2|pattern3/x/g```

Title: Vim alternatives file

Body:
:[range]s/{pattern}/{string}/[flags] [count]
            For each line in [range] replace a match of {pattern}
            with {string}.

The "or" operator in a pattern is "\|".  Example:
    /foo\|bar
This matches "foo" or "bar".  More alternatives can be concatenated:
    /one\|two\|three
Matches "one", "two" and "three".

Can we use a pattern/alternatives file with 3 lines?

one

two

three

Body:
The following command works on my system:

let @a = system('cat repl.vim | tr "\n" "|"') | exe '%s/\v'.@a.'<bs>/x/g'

Here, I have a list of words in the file repl.vim. The first part of the command uses let to save the list of words in registry a replacing every newline \n with an or operator |. In the second part exe %s performs the substitution.

In practice, if repl.vim contains:

pattern1
pattern2
pattern3

Running the command will result in:

%s/\vpattern1|pattern2|pattern3/x/g


问:
How can I shorten a URL?
How can I shorten a URL, so even when it is clicked on it will still show the short version and not the full version of the URL? I want to have a website or an app where I can shorten the url and the full one won't be shown when users click on it. The browser will still show the shortened version, without expanding it.

Thank you.

答:
What you are asking for is generally only possible if you are using a 3rd party URL shortening service that supports cloaking, or you are implementing your own URL shortening server.

You can certainly put a short URL in your HTML, and the user will only see the short URL when hovering over the link.  But, as soon as the link is clicked, the browser is going to navigate to the short URL.

If you are using a 3rd party shortening service without cloaking, it is just going to redirect the browser to the long URL, and then the browser will display that URL in its address bar.

If you are using a shortening service with cloaking, the typical implementation will simply return an HTML frame that refers to the long URL.  Visually, the user won't see any difference, and the browser will display the short URL in the address bar since that is the URL actually being displayed, but the frame will then pull in content from the long URL.  The user can easily determine the long URL by simply looking at the HTML source of the frame, or at the properties of the page the frame is displaying.

To truly hide the long URL completely, the service that processes the short URL navigation will have to retrieve the actual content located at the long URL and then send it back to the browser as if it were the content of the short URL.  Most shortening services will not do that, but you could try setting up your own server that does.

Title: How can I shorten a URL?


问:
how to use jwplatform api using python
I am going to create search api for Android and iOS developers.
Our client have setup a lambda function in AWS.
Now we need to fetch data using jwplatform Api based on search keyword passed as parameter. For this, I have to install jwplatform module in Lambda function or upload zip file of code with dependencies. So that i want to run python script locally and after getting appropriate result i will upload zip in AWS Lambda.
I want to use the videos/list (jwplatform Api) class to search the video library using python but i don't know much about Python. So i want to know how to run python script? and where should i put the pyhton script ?</p>

答: There are a handful of useful Python script examples here: https://github.com/jwplayer/jwplatform-py</p>

Title: how to use jwplatform api using python


问:
Jekyll For Loop to include all of a directory
I am using Jekyll to create a static page on GitHub, I've setup my default layout and index.html page.

I want to create a folder called 'sections' and store a load of .html files which are basically different sections to a guide that I'm making. The purpose of this is so that I can then include the whole of 'sections' into my main index.html using a Jekyll for loop. I want to keep all of my sections inside the section folder to make it more manageable.

Is this possible?

答:
The directory structure of Jekyll is not something you can change according to your convenience. If you want to have each of the html pages as a separate page in your website, you have do is put your html pages in the _posts directory in your project and use the for loop like this to include their links in index.html:

```<code>{% for post in site.posts %}
    <!-- link to each post in index.html -->
    <a href="{{ site.url }}{{ post.url }}">{{ post.title }}</a>
{% endfor %}
</code>```

If you want to put the contents of each html file in index.html, then you cannot use _posts for that. In that case, you need to use the _includes directory, and do something like:

```<code>...
{% include page1.html %}
{% include page2.html %}
{% include page3.html %}
...
</code>```

See the Jekyll directory structure doc.

Body:
The directory structure of Jekyll is not something you can change according to your convenience. If you want to have each of the html pages as a separate page in your website, you have do is put your html pages in the _posts directory in your project and use the for loop like this to include their links in index.html:

{% for post in site.posts %}
    <!-- link to each post in index.html -->
    <a href="{{ site.url }}{{ post.url }}">{{ post.title }}</a>
{% endfor %}

If you want to put the contents of each html file in index.html, then you cannot use _posts for that. In that case, you need to use the _includes directory, and do something like:

...
{% include page1.html %}
{% include page2.html %}
{% include page3.html %}
...

See the Jekyll directory structure doc.


问:
Event when space is pressing, only one time
I have some issues: I have this : (in a function..)

var space = 0;

setInterval(space, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});

function space() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
                space++;
                console.log(space);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?

答:
What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.

var spaceCount = 0;
var running = false;
var keys = {}

$(document).keydown(function(e) {
  console.log("keycode", e.keyCode);
  keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
  console.log("keyup")
  delete keys[e.keyCode];
  running = false;
});

function space() {
  if(running) return;
  for (var direction in keys) {
    running = true;
    console.log(direction);
    if (!keys.hasOwnProperty(direction)) continue;
    if (direction == 32) {
      spaceCount++;
      console.log("count: " + spaceCount);
      console.log(keys);
    }
  }
}

setInterval(space, 20);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have some issues: I have this : (in a function..)

var space = 0;

setInterval(space, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});

function space() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
                space++;
                console.log(space);
            }

32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?

Body:
What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.

var spaceCount = 0;
var running = false;
var keys = {}

$(document).keydown(function(e) {
  console.log("keycode", e.keyCode);
  keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
  console.log("keyup")
  delete keys[e.keyCode];
  running = false;
});

function space() {
  if(running) return;
  for (var direction in keys) {
    running = true;
    console.log(direction);
    if (!keys.hasOwnProperty(direction)) continue;
    if (direction == 32) {
      spaceCount++;
      console.log("count: " + spaceCount);
      console.log(keys);
    }
  }
}

setInterval(space, 20);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
MySQL Moving table from varchar to int
I am moving an old Mantis table that had a varchar(64) category_id column to a new Mantis table that has a int(10) category_id column.

The simplified structure is as follows

bug_table (Old DB)

+----+-------------+-------------+--------+
| id | project_id  | category_id | report |
+----+-------------+-------------+--------+
|  1 |           0 | Server      | crash  |
|  2 |           0 | Database    | error  |
|  3 |           1 | Server      | bug    |
|  4 |           1 | Server      | crash  |
+----+-------------+-------------+--------+

category_table (New DB)

+----+------------+----------+
| id | project_id |   name   |
+----+------------+----------+
|  0 |          1 | Server   |
|  1 |          1 | Database |
|  2 |          2 | Server   |
|  3 |          2 | Database |
+----+------------+----------+

I need a magical query that will replace category_id in the bug_table with the numerical category_id in the category_table. Thankfully I am able to match rows by project_id and categories by name.

Here is the query I am working on but have gotten stuck in the complexity

UPDATE bug_table b SET b.category_id = c.id USING category_table WHERE b.category_id = c.name

答:
I like to approach such a task a little differently than you do for a new lookup/reference table.

To me, the new category table would only have id and name columns. There are only two rows based on the sample data: Server and Database. Yes, I realize there could be other names, but those can easily be added, and should be added, before proceeding to maximize the id matching that follows.

Next I would add a new column to the bug table that could be called 'category_new' with the data type that will store the new category id. Alternatively, you could rename the existing category_id column to category, and the new column for the id's could then be column_id.

After all that is done then you can update the new column by joining the category on names and set the id that matches: (note this assumes the non-alternative approach mentioned in step 2)

```<code>UPDATE bug_table JOIN category_table ON bug_table.category_id = category_table.name
SET bug_table.category_new = category_table.id
</code>```

After that runs, check the new column to verify the updated id's.

Finally, after successful update, now the old category_id column (with the names) from the bugs_table can be dropped, and the category_new column can be renamed as the category_id.

=====

Note that if you decide to go with the alternative column approach mentioned, of course the query will be similar but differ slightly. Then only a column drop is needed at the end

If there are other tables to apply the same category changes, the operation (basically steps 2 through 5) would be similar for those tables too.

Title: MySQL Moving table from varchar to int

Body:
I like to approach such a task a little differently than you do for a new lookup/reference table.

To me, the new category table would only have id and name columns. There are only two rows based on the sample data: Server and Database. Yes, I realize there could be other names, but those can easily be added, and should be added, before proceeding to maximize the id matching that follows.

Next I would add a new column to the bug table that could be called 'category_new' with the data type that will store the new category id. Alternatively, you could rename the existing category_id column to category, and the new column for the id's could then be column_id.

After all that is done then you can update the new column by joining the category on names and set the id that matches: (note this assumes the non-alternative approach mentioned in step 2)

UPDATE bug_table JOIN category_table ON bug_table.category_id = category_table.name
SET bug_table.category_new = category_table.id

After that runs, check the new column to verify the updated id's.

Finally, after successful update, now the old category_id column (with the names) from the bugs_table can be dropped, and the category_new column can be renamed as the category_id.

=====

Note that if you decide to go with the alternative column approach mentioned, of course the query will be similar but differ slightly. Then only a column drop is needed at the end

If there are other tables to apply the same category changes, the operation (basically steps 2 through 5) would be similar for those tables too.


问:
How to pass a full array in an array of pointers
I wrote a program that sorts the values of an array. It has 5 arrays,

```<code>    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };
</code>```

and an array of pointers that holds those 5 arrays,

```<code>int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };
</code>```

I want to sort the values of each array, but when I pass the arrays to the sorting function

```<code>sortArrValues(&pArr[i]);
</code>```

it sees the first index of each array (arr1,arr2...) as the element of that array (pArr[i]), so pArr[i] is (3,2,0,1,4).

But I want pArr[i] to be the full array it meant to be, so in the first iteration pArr[i] will be (3,9,6,7).

Notes: the first index of each array indicates the length of that array (not including that index).

The sorting will skip the first index.

There are two additional functions,they're not used (you can skip them).

Here's the full code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int** arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (*arr[i] > *arr[i+1])
        {
            tmp = *arr[i];
            *arr[i] = *arr[i + 1];
            *arr[i + 1] = tmp;
        }
    }
}
</code>```

答:
I tried to modify your program to fix issues. Some of these issues are already highlighted by others. There were some there were not. Here is the working snippet. Let me know if you need more explanation on any modification. Note that I have only modified your sort function. The idea is not to give you the fastest sorting algorithm, but a working one.

```<code>int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }
}

void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0, j = 0;

    for (i = 0; i < (**arr) - 1; i++)
    {
        for(j=i+1; j < (**arr) - 1; j++) {
           if ((*arr)[i+1] > (*arr)[j+1])
           {
               tmp = (*arr)[i+1];
               (*arr)[i+1] = (*arr)[j + 1];
               (*arr)[j+1] = tmp;
           }
        }
        printf("%d ", (*arr)[i+1]);
    }
    printf("%d\n", (*arr)[i+1]);
}
</code>```

Body:
I wrote a program that sorts the values of an array. It has 5 arrays,

    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

and an array of pointers that holds those 5 arrays,

int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

I want to sort the values of each array, but when I pass the arrays to the sorting function

sortArrValues(&pArr[i]);

it sees the first index of each array (arr1,arr2...) as the element of that array (pArr[i]), so pArr[i] is (3,2,0,1,4).

But I want pArr[i] to be the full array it meant to be, so in the first iteration pArr[i] will be (3,9,6,7).

Notes: the first index of each array indicates the length of that array (not including that index).

The sorting will skip the first index.

There are two additional functions,they're not used (you can skip them).

Here's the full code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int** arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (*arr[i] > *arr[i+1])
        {
            tmp = *arr[i];
            *arr[i] = *arr[i + 1];
            *arr[i + 1] = tmp;
        }
    }
}

Body:
I tried to modify your program to fix issues. Some of these issues are already highlighted by others. There were some there were not. Here is the working snippet. Let me know if you need more explanation on any modification. Note that I have only modified your sort function. The idea is not to give you the fastest sorting algorithm, but a working one.

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }
}

void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0, j = 0;

    for (i = 0; i < (**arr) - 1; i++)
    {
        for(j=i+1; j < (**arr) - 1; j++) {
           if ((*arr)[i+1] > (*arr)[j+1])
           {
               tmp = (*arr)[i+1];
               (*arr)[i+1] = (*arr)[j + 1];
               (*arr)[j+1] = tmp;
           }
        }
        printf("%d ", (*arr)[i+1]);
    }
    printf("%d\n", (*arr)[i+1]);
}


问:
Getting Error : moment.duration is not a function
I am trying to convert seconds in HH:MM:SS format. I am getting an error moment.duration is not a function.

var moment = require("moment-duration-format");

moment.duration(123, "seconds").format("hh:mm:ss");

答:
The moment-duration-format plugin depends on moment, so you should import/require it first:

```<code>var moment = require("moment")
require("moment-duration-format");

moment.duration(123, "seconds").format("hh:mm:ss");
</code>```

Body:
The moment-duration-format plugin depends on moment, so you should import/require it first:

var moment = require("moment")
require("moment-duration-format");

moment.duration(123, "seconds").format("hh:mm:ss");

ContentLicense: CC BY-SA 4.0


问:
Is there a way to allow browserify modules access to the global scope (window object)?
The Scenario

I'm using Browserify (or NodeJS/CommonJS like imports) to require some JavaScript libraries. However, I'm having trouble getting them to play nice since apparently Browserify by default denies global scope access to all modules. For example, doing this doesn't work;

file1.js

```<code>require('moment');
</code>```

file2.js

```<code>moment(new Date()); // throws moment is undefined
</code>```

But this works by changing the contents of file1.js to the following;

```<code>window.moment = require('moment');
</code>```

The Problem

This has worked well enough so far, however now I'm having trouble loading the moment timezone library (an extension of MomentJS). Moment Timezone's docs imply both scripts should run on the window global scope by adding them as script tags like so;

```<code><script src="moment.js"></script>
<script src="moment-timezone-with-data.js"></script>
</code>```

So they can be used like this;

```<code>moment().tz("America/Los_Angeles").format();
</code>```

This however, seems very hard to achieve, since if I try the following;

```<code>window.moment = require('moment');
require('./../../node_modules/moment-timezone/builds/moment-timezone-with-data-2010-2020'); // the location of my moment-timezone library
</code>```

I get a runtime error saying that moment.tz is undefined (meaning that the second library wasn't run with the global scope). And if I try to add the window.moment to the second line of code, I'll be rewriting the first instance of the full library.

So, in short;

Is there a way to allow certain Browserify imports to have global scope access, or to run with the window object as their scope?

I'm aware of the security implications this has, but selectively used, this would be immensely useful while requiring things like JavaScript libraries that need global access to set up themselves correctly. Any help would be greatly appreciated.

答:
Put tiny libraries into vendor.js, include that on your page with

        Open devtools and inspect the output

```

<p><strong>package.json</strong></p>

<pre class="lang-json prettyprint-override"><code>{
  "scripts": {
    "build": "cat vendor1.js vendor2.js > dist/vendor.js && cp index.html dist/index.html && browserify index.js -o dist/bundle.js"
  },
  "browserify-shim" : {
    "vendor1" : "global:vendor1",
    "vendor2" : "global:vendor2"
  },
  "browserify" : {
    "transform" : [ "browserify-shim" ]
  },
  "devDependencies": {
    "browserify": "^14.1.0",
    "browserify-shim": "^3.8.14"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "moment-timezone": "^0.5.11"
  }
}
</code>```

A couple of things to note about the above package.json:

build: it builds 'application' in dist folder, creating the following structure:

dist

index.html

bundle.js

vendor.js

"browserify" entry: it just adds browserify-shim

"browserify-shim" entry: it tells browserify that vendor1 and vendor2 are available as properties on window (global) object. Browserify won't attempt to bundle them, and require() will just return those properties. You need to make sure they are actually available (so index.html above includes them with

Body:
The Scenario

I'm using Browserify (or NodeJS/CommonJS like imports) to require some JavaScript libraries. However, I'm having trouble getting them to play nice since apparently Browserify by default denies global scope access to all modules. For example, doing this doesn't work;

file1.js

require('moment');

file2.js

moment(new Date()); // throws moment is undefined

But this works by changing the contents of file1.js to the following;

window.moment = require('moment');

The Problem

This has worked well enough so far, however now I'm having trouble loading the moment timezone library (an extension of MomentJS). Moment Timezone's docs imply both scripts should run on the window global scope by adding them as script tags like so;

So they can be used like this;

moment().tz("America/Los_Angeles").format();

This however, seems very hard to achieve, since if I try the following;

window.moment = require('moment');
require('./../../node_modules/moment-timezone/builds/moment-timezone-with-data-2010-2020'); // the location of my moment-timezone library

I get a runtime error saying that moment.tz is undefined (meaning that the second library wasn't run with the global scope). And if I try to add the window.moment to the second line of code, I'll be rewriting the first instance of the full library.

So, in short;

Is there a way to allow certain Browserify imports to have global scope access, or to run with the window object as their scope?

I'm aware of the security implications this has, but selectively used, this would be immensely useful while requiring things like JavaScript libraries that need global access to set up themselves correctly. Any help would be greatly appreciated.

Body:
Put tiny libraries into vendor.js, include that on your page with <script>, make them known to browserify with browserify-shim and use them with require('libname') in your modules.

Larger libraries may be included from, say, vendor CDNs, and also be made known to browserify with browserify-shim.

index.html

<html>
    <head>
        <script src="vendor.js"></script>
        <script src="bundle.js"></script>
    </head>
    <body>
        Open devtools and inspect the output
    </body>
</html>

package.json

{
  "scripts": {
    "build": "cat vendor1.js vendor2.js > dist/vendor.js && cp index.html dist/index.html && browserify index.js -o dist/bundle.js"
  },
  "browserify-shim" : {
    "vendor1" : "global:vendor1",
    "vendor2" : "global:vendor2"
  },
  "browserify" : {
    "transform" : [ "browserify-shim" ]
  },
  "devDependencies": {
    "browserify": "^14.1.0",
    "browserify-shim": "^3.8.14"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "moment-timezone": "^0.5.11"
  }
}

A couple of things to note about the above package.json:

build: it builds 'application' in dist folder, creating the following structure:

dist

index.html

bundle.js

vendor.js

"browserify" entry: it just adds browserify-shim

"browserify-shim" entry: it tells browserify that vendor1 and vendor2 are available as properties on window (global) object. Browserify won't attempt to bundle them, and require() will just return those properties. You need to make sure they are actually available (so index.html above includes them with <script src="vendor.js">

index.js

var momentfromnpm = require('moment-timezone');
var vendor1 = require('vendor1');
var vendor2 = require('vendor2');
console.log("Hello");
console.log("Using module from npm", momentfromnpm().tz("Europe/London").format());
console.log("using a function from vendor1.js (bundled into vendor.js)", vendor1());
console.log("using a 'module' from vendor2.js (bundled to vendor.js)", vendor2.doWork());

vendor1.js

window.vendor1 = function() { // could also be just `function vendor1()...`
    return "I'm a simple function, defined on a window";
};

vendor2.js

var vendor2 = { // could also be window.vendor2
    doWork: function() {
        console.log("vendor2 doing work");
    }
};


问:
HDF file not saving properly with h5py
I'm trying to save a numpy array in a HDF file with h5py as follows:

```<code>with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    # do stuff to create two numpy arrays, training_X and training_Y
    print(len(training_X)) # this returns the number of elements I expect in the the numpy arr
    aligned_f.create_dataset("train_X", data=training_X)
    aligned_f.create_dataset("train_Y", data=training_Y)
    # if I add a line here to access the datasets I just created, I see that aligned_f does indeed have two keys train_X and train_Y with the shapes I expect
</code>```

However, when the program ends and I check the file mfcc_aligned.hdf, it's exactly 800 bytes (much smaller than I expect), and there are no keys. I'm at a loss for what's going on here.

Thanks in advance for any insights!

答:
I have no problems with your code:</p>

```<code>In [59]: import h5py
In [60]: training_X = np.arange(12).reshape(3,4)
In [61]: training_Y = np.arange(3).reshape(3,1)
In [62]: with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    ...:     # do stuff to create two numpy arrays, training_X and training_Y
    ...:     print(len(training_X)) # this returns the number of elements I expe
    ...: ct in the the numpy arr
    ...:     aligned_f.create_dataset("train_X", data=training_X)
    ...:     aligned_f.create_dataset("train_Y", data=training_Y)
    ...:
3
In [63]: f = h5py.File("mfcc_aligned.hdf")
In [64]: list(f.keys())
Out[64]: ['train_X', 'train_Y']
In [66]: f['train_X'].value
Out[66]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [67]: f['train_Y'][:]
Out[67]:
array([[0],
       [1],
       [2]])
In [68]: ll mfcc_aligned.hdf
-rw-rw-r-- 1 paul 2204 Mar 31 14:10 mfcc_aligned.hdf
</code>```

Title: HDF file not saving properly with h5py

Body:
I'm trying to save a numpy array in a HDF file with h5py as follows:

with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    # do stuff to create two numpy arrays, training_X and training_Y
    print(len(training_X)) # this returns the number of elements I expect in the the numpy arr
    aligned_f.create_dataset("train_X", data=training_X)
    aligned_f.create_dataset("train_Y", data=training_Y)
    # if I add a line here to access the datasets I just created, I see that aligned_f does indeed have two keys train_X and train_Y with the shapes I expect

However, when the program ends and I check the file mfcc_aligned.hdf, it's exactly 800 bytes (much smaller than I expect), and there are no keys. I'm at a loss for what's going on here.

Thanks in advance for any insights!

Body:
I have no problems with your code:

In [59]: import h5py
In [60]: training_X = np.arange(12).reshape(3,4)
In [61]: training_Y = np.arange(3).reshape(3,1)
In [62]: with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    ...:     # do stuff to create two numpy arrays, training_X and training_Y
    ...:     print(len(training_X)) # this returns the number of elements I expe
    ...: ct in the the numpy arr
    ...:     aligned_f.create_dataset("train_X", data=training_X)
    ...:     aligned_f.create_dataset("train_Y", data=training_Y)
    ...:
3
In [63]: f = h5py.File("mfcc_aligned.hdf")
In [64]: list(f.keys())
Out[64]: ['train_X', 'train_Y']
In [66]: f['train_X'].value
Out[66]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [67]: f['train_Y'][:]
Out[67]:
array([[0],
       [1],
       [2]])
In [68]: ll mfcc_aligned.hdf
-rw-rw-r-- 1 paul 2204 Mar 31 14:10 mfcc_aligned.hdf


问:
Angular2: Directive loads, but does nothing
EDIT: I found the problem.  You know what it turned out to be?  A chrome caching issue. Chrome cached something, and until I turned off caching while the debugger was open and explicitly refreshed my page, I was getting nowhere.  Once I refreshed, I started getting events caught.

Original Post:
I have a custom Angular directive that's supposed to act on a control on any of three events: onload, onblur, or onfocus.  It's applied to an input control, which may or may not be disabled.  I know that onblur and onfocus are useless on a disabled control, but I suppose there'd be no harm in listening for events that never appear.  On the other hand, an enabled control will fire off those events, so I need to be listening.  This directive is designed to be fairly generic, so it needs to handle both a disabled and an enabled input control.

The problem is, it does nothing.  At the very least, it doesn't appear to do anything.  The directive is instantiated -- I've verified that the constructor fires off, and I've verified that elementRef points to an input control -- but that's about it.  None of the listeners work.

Usage:

```<code><input myDirective disabled id="someId" name="someName" [ngModel]="myValue" />
</code>```

Directive:

```<code>import { Directive, HostListener, ElementRef, Input } from "@angular/core";

@Directive({ selector: "[myDirective]" })
export class MyDirective {
    constructor(private elementRef: ElementRef) {
    }

    @HostListener("focus", ["$event.target.value"])
    onFocus(value: string) {
        console.log("MyDirective: Focus caught.");
    }

    @HostListener("blur", ["$event.target.value"])
    onBlur(value: number) {
        console.log("MyDirective: Blur caught.");
    }

    @HostListener("load", ["$event.target.value"])
    onLoad() {
        console.log("MyDirective: Load caught.");
    }
}
</code>```

When I run everything, it loads fine.  No issues with missing modules, missing components, etc.  No errors in the console.  As I mentioned earlier, even breaking into the code using the debugger verifies that the directive was instantiated.  But I get no console output, either.  I would at least expect it for the onload event.  Do disabled input controls not fire those or something?

答:
onLoad will not work because it is a window event and not a form event

Following are the list of events that can be handled for Form Elements

```<code>onblur
onchange
oncontextmenu
onfocus
oninput
oninvalid
onreset
onsearch
onselect
onsubmit
</code>```

You have refer to it from this documentation
Update based on comment

As you expected a MDN link to support the above answer here it is

Resource events refers to the resources in the internet such as a web url.

Body:
EDIT: I found the problem.  You know what it turned out to be?  A chrome caching issue. Chrome cached something, and until I turned off caching while the debugger was open and explicitly refreshed my page, I was getting nowhere.  Once I refreshed, I started getting events caught.

Original Post:
I have a custom Angular directive that's supposed to act on a control on any of three events: onload, onblur, or onfocus.  It's applied to an input control, which may or may not be disabled.  I know that onblur and onfocus are useless on a disabled control, but I suppose there'd be no harm in listening for events that never appear.  On the other hand, an enabled control will fire off those events, so I need to be listening.  This directive is designed to be fairly generic, so it needs to handle both a disabled and an enabled input control.

The problem is, it does nothing.  At the very least, it doesn't appear to do anything.  The directive is instantiated -- I've verified that the constructor fires off, and I've verified that elementRef points to an input control -- but that's about it.  None of the listeners work.

Usage:

<input myDirective disabled id="someId" name="someName" [ngModel]="myValue" />

Directive:

import { Directive, HostListener, ElementRef, Input } from "@angular/core";

@Directive({ selector: "[myDirective]" })
export class MyDirective {
    constructor(private elementRef: ElementRef) {
    }

    @HostListener("focus", ["$event.target.value"])
    onFocus(value: string) {
        console.log("MyDirective: Focus caught.");
    }

    @HostListener("blur", ["$event.target.value"])
    onBlur(value: number) {
        console.log("MyDirective: Blur caught.");
    }

    @HostListener("load", ["$event.target.value"])
    onLoad() {
        console.log("MyDirective: Load caught.");
    }
}

When I run everything, it loads fine.  No issues with missing modules, missing components, etc.  No errors in the console.  As I mentioned earlier, even breaking into the code using the debugger verifies that the directive was instantiated.  But I get no console output, either.  I would at least expect it for the onload event.  Do disabled input controls not fire those or something?

Body:
onLoad will not work because it is a window event and not a form event

Following are the list of events that can be handled for Form Elements

onblur
onchange
oncontextmenu
onfocus
oninput
oninvalid
onreset
onsearch
onselect
onsubmit

You have refer to it from this documentation
Update based on comment

As you expected a MDN link to support the above answer here it is

Resource events refers to the resources in the internet such as a web url.