答:
Catch the events of start moving and finish moving with your preferred method (onMouseDown and onMouseUp are fine). Add a CSS class to specify the moving state when the action starts. Remove the CSS class when the action finishes.

In your case, you may try the followings:

Add a new CSS class:

```<code>.moving {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
</code>```

Extend your handMd() and handMu() functions:

```<code>function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
    document.getElementById('article').classList.toggle('moving', true);  // Add this line. 'article' is the id of the element where you don't want the selection to occur.
}
function handMu(e) {
    moving = false;
    document.getElementById('article').classList.toggle('moving', false);  // Add this line. 'article' is the id of the element where you don't want the selection to occur.
}
</code>```

Title: How to prevent text selection from obstructing onMouseMove event?

Body:
I'm implementing a "resize handle" to change the width of my left navigation panel. It is a div that receives an onMouseDown() event, calculates the necessary widths and applies them to the right elements in the subsequent calls to onMouseMove(). But I'm having some problems.

1) The article element, to the right of the navigation panel and handle, does not activate the onMouseUp() if I release the mouse there. Is this because the onMouseDown() was activated in other element?

2) If I move the mouse fast to the right, I can't prevent the text in the article from being selected, even calling methods like preventDefault() and stopPropagation().

3) Even if there's no text in the article, the resizing only works if I move the mouse very slowly. If the mouse moves fast over the article element, the resize stops, unless I release the mouse button - in this case the resize goes smoothly (suggesting it was the text-selecting that was stopping the resize, even with no text at all). But if I release the mouse button, the resize should stop (see point 1).

I've seen some solutions using CSS user-select: none, but this would prevent any text from being selected inside article, which is obviously an overkill.

So, how can I make the resizing smooth, without selecting any text, when I move the mouse over any element in my document? (After pressing the button in the right div, of course.)

That's my HTML:

<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS Template</title>

Header

nav 1

nav 2

Footer

That's my CSS:

html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#CCC;
    width:auto;
    overflow:auto;
    padding:10px;
    flex-grow:1;
}
nav {
    width:300px;
    height:auto;
    overflow: hidden;
    display:flex;
}
.navcont {
    background:#8C8;
    width:auto;
    flex-grow:1;
}
.handle {
    background:#333;
    right:0px;
    width:30px;
    cursor:col-resize;
}
footer {
    text-align:center;
}

That's my Javascript:

var mx,px,moving=false;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
}
function handMm(e) {
    if (moving) {
        e.preventDefault();
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        var diff = e.pageX - mx;
        document.getElementById('nav').style.width = (px + diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    moving = false;
}

And here is a working example: https://jsfiddle.net/45h7vq7u/

Another example, including Ryan Tsui's answer: https://jsfiddle.net/v1cmk2f6/1/ (the text-selection is gone, but the div still won't move smoothly, but only when moving fast to the right).

Body:
Catch the events of start moving and finish moving with your preferred method (onMouseDown and onMouseUp are fine). Add a CSS class to specify the moving state when the action starts. Remove the CSS class when the action finishes.

In your case, you may try the followings:

Add a new CSS class:

.moving {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}

Extend your handMd() and handMu() functions:

function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
    document.getElementById('article').classList.toggle('moving', true);  // Add this line. 'article' is the id of the element where you don't want the selection to occur.
}
function handMu(e) {
    moving = false;
    document.getElementById('article').classList.toggle('moving', false);  // Add this line. 'article' is the id of the element where you don't want the selection to occur.
}


来源: stackexchange

问:
Google Maps GMSMaker iconView - iOS SDK
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

```<code>        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView
</code>```

答:
Make sure that you're using the latest Google Maps SDK v2.3.0 and above.

Try this:

```<code>    marker.icon = UIImage(named: "<Your Image>")
</code>```

EDIT:

Or you can set UIImageView to iconView

```<code>    marker.iconView = UIImageView(image: UIImage(named: "<Your Image>"))
</code>```

Output:

Hope it helps.

ContentLicense: CC BY-SA 4.0

Title: Google Maps GMSMaker iconView - iOS SDK

Body:
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView

Body:
Make sure that you're using the latest Google Maps SDK v2.3.0 and above.

Try this:

    marker.icon = UIImage(named: "<Your Image>")

EDIT:

Or you can set UIImageView to iconView

    marker.iconView = UIImageView(image: UIImage(named: "<Your Image>"))

Output:

Hope it helps.

ContentLicense: CC BY-SA 3.0


问:
cakephp - create new directory inside webroot
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

```<code>$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}
</code>```

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

答:
try this</p>

```<code>$path = 'files' . DS . 'pathtofolder';
$folder = new Folder($path, true, 0755);
if ($folder->path) {
    echo "Exists";
}
else{
    echo "Doesnt exist";
}
</code>```

Body:
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

Body:
try this

$path = 'files' . DS . 'pathtofolder';
$folder = new Folder($path, true, 0755);
if ($folder->path) {
    echo "Exists";
}
else{
    echo "Doesnt exist";
}


问:
Yahoo Fantasy Sports API routing/post errors
As a quick background: I've already successfully set up a small application that will connect to Yahoo's API and set my lineups on a daily basis using PUT requests on my team's roster per the Yahoo Developer's Guide.

Specifically, where I'm having problems now:

POST

Using POST, players can be added and/or dropped from a team, or trades
  can be proposed. The URI for POSTing to transactions collection is:

http://fantasysports.yahooapis.com/fantasy/v2/league//transactions

The input XML format for a POST request to the transactions API for
  replacing one player with another player in a team is:

```<code><fantasy_content>
  <transaction>
    <type>add/drop</type>
    <players>
      <player>
        <player_key>{player_key}</player_key>
        <transaction_data>
          <type>add</type>
          <destination_team_key>{team_key}</destination_team_key>
        </transaction_data>
      </player>
      <player>
        <player_key>{player_key}</player_key>
        <transaction_data>
          <type>drop</type>
          <source_team_key>{team_key}</source_team_key>
        </transaction_data>
      </player>
    </players>
  </transaction>
</fantasy_content>
</code>```

My method for making a request is as follows:

```<code>  def self.make_signed_request(address, method, user_id, input_file=nil )

    # format http method and return false if not accepted API method
    method = method.upcase
    return false if ( method != "GET" ) && ( method != "POST" ) && ( method != "PUT")

    # find user
    user = User.find(user_id)

    if ( user.yahoo_access_token_expiration.nil? || user.yahoo_access_token_expiration < Time.now )
      # expired token, so renew
      YahooOAuth.renew_token(user_id)
      user.reload
    end

    # normalize text HMAC-SHA1
    digest = OpenSSL::Digest.new('sha1')
    nonce = rand(10 ** 30).to_s.rjust(30,'0')
    timestamp = Time.now.to_i
    text = method + "&" + CGI.escape("#{address}") + "&" + CGI.escape("oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0")

    # create key for HMAC-SHA1
    key = CGI.escape("#{YAHOO_OAUTH_API[:CLIENT_SECRET]}")+ "&" + CGI.escape("#{user.yahoo_access_token_secret}")

    # create HMAC-SHA1 signature for api request
    hmac = OpenSSL::HMAC.digest(digest, key, text)
    signature_sha1 = CGI.escape(Base64.strict_encode64(hmac))

    # make API request
    response = nil
    if method == "GET"
      response = Curl.get("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}")
    elsif method == "POST"
      # return "Not implemented"
      response = Curl.post("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}", input_file) do |http|
        http.headers['Accept'] = 'application/xml'
        http.headers['Content-Type'] = 'application/xml'
      end
    elsif method == "PUT"
      response = Curl.put("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}", input_file) do |http|
        http.headers['Accept'] = 'application/xml'
        http.headers['Content-Type'] = 'application/xml'
      end
    end

    # return raw XML result
    return response.body

  end
</code>```

When I make my request --

```<code>def add_drop(players)
    # players are added in [{player_key}, {add/drop}, {faab_bid (or nil if not FAAB)}] form
    url = "http://fantasysports.yahooapis.com/fantasy/v2/league/#{self.league.league_key}/transactions"
    builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
      xml.fantasy_content {
        xml.transaction {
          xml.type "add/drop"
          xml.faab_bid players[0][2] unless players[0][2].nil?
          xml.players {
            players.each do |player|
              xml.player {
                xml.player_key player[0]
                xml.transaction_data {
                  xml.type player[1] # this will be "add" or "drop"
                  # adds use "destination_team_key," drops use "source_team_key"
                  if player[1] == "add"
                    xml.destination_team_key self.team_key
                  else
                    xml.source_team_key self.team_key
                  end
                } # transaction_data
              } # player
            end
          } # players
        } # transaction
      } # fantasy_content
    end # builder
    xml_input = builder.to_xml
    YahooOAuth.make_signed_request(url, 'put', self.user.id, xml_input)
  end
</code>```

--the XML generated is shown below --

```<code>"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<fantasy_content>\n  <transaction>\n    <type>add/drop</type>\n    <players>\n      <player>\n        <player_key>357.p.10171</player_key>\n        <transaction_data>\n          <type>add</type>\n          <destination_team_key>370.l.4801.t.7</destination_team_key>\n        </transaction_data>\n      </player>\n      <player>\n        <player_key>357.p.9317</player_key>\n        <transaction_data>\n          <type>drop</type>\n          <source_team_key>370.l.4801.t.7</source_team_key>\n        </transaction_data>\n      </player>\n    </players>\n  </transaction>\n</fantasy_content>\n"
</code>```

-- and the two responses I'll get from Yahoo are:

```<code>> <?xml version="1.0" encoding="UTF-8"?> <error xml:lang="en-us"
> yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/370.l.4801/transactions/?oauth_consumer_key=dj0yJmk9dHBIa0h4ekhTSVBnJmQ9WVdrOVlUZHFkMnhMTXpJbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lNQ--&oauth_nonce=892057444475304460343340318332&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1492097395&oauth_token=A%3D2.86iTDxtT4nQ.wxTcn33mgnA8dm3AeME87YRjNthVjxiwfhqKr_oWt0HBgbBeS2DC_dNObN72m0ucgi7CsSFaRjpc5IcnZ_bpJNTC3pUXc37bgH8f0S4irpyXLz8s9ONAYYB.LIDT0sOUvdTgk_lPDnlr1GlPhCe7u54Sq.m_vwq1JQlNUzEVrEs3kOW9wiXk17BditA9OGaVE.tuepvpthDRVBhOye8qjb_ic7UZtT.lvccoGEdgvcShHSyg.YYcnShl7ks23G01hAcXrfGveEk0UncWKNmma42cYbg7bzSOY9ZZj3_hvU5rK3SjB1ADPe8bsIEe_Ba9KBhYxlWd9iyyAR_bloL9n0eeL_OQ6PoR4uGJ6VMUDn9n_ovDGvfgAfvtJs15pCcXPhYusuo1S7SJF1O3fLtR8TitmU1qW88x3SenY2U50dlRG9Y73iNUdnyYBpIHLg._pPkms26QhnuxSFfqpXcGleGXOuZ0.TNOE3Cp8VbLEOEIg6QkavgGLKyFetYhSQ879T4rfhfeEoWvwkjsO1BL2Y3n4Hp9cgfU4y3wZvT.b8qhP7QY0UTYtZkyYH.sydFUXUCec.yVGm29S.s.2N96tfr4qWaI0qntRE.X5MVdwfbhz94n9JshmduqurjKRLlMYVWnLZ_Yderm0HDvT7dnowjyUwBx2UxUKJooauQnNU67QQECmh.HZqcm_OBysLABvdtTtaPhnvJ1QViN_UUjslToVPOs1oyxoTNRbL0VL8yxJc&oauth_version=1.0&oauth_signature=UVmcj2S8c5vqkRgAxsdQ3MQZI54%3D"
> xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
> xmlns="http://www.yahooapis.com/v1/base.rng">
> <description>subresource 'transactions' not supported.</description>
> <detail/> </error>
</code>```

and

```<code>> <?xml version="1.0" encoding="UTF-8"?> <error xml:lang="en-us"
> yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/370.l.4801/transactions?oauth_consumer_key=dj0yJmk9dHBIa0h4ekhTSVBnJmQ9WVdrOVlUZHFkMnhMTXpJbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lNQ--&oauth_nonce=503128074504907304111221170641&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1492097198&oauth_token=A%3D2.86iTDxtT4nQ.wxTcn33mgnA8dm3AeME87YRjNthVjxiwfhqKr_oWt0HBgbBeS2DC_dNObN72m0ucgi7CsSFaRjpc5IcnZ_bpJNTC3pUXc37bgH8f0S4irpyXLz8s9ONAYYB.LIDT0sOUvdTgk_lPDnlr1GlPhCe7u54Sq.m_vwq1JQlNUzEVrEs3kOW9wiXk17BditA9OGaVE.tuepvpthDRVBhOye8qjb_ic7UZtT.lvccoGEdgvcShHSyg.YYcnShl7ks23G01hAcXrfGveEk0UncWKNmma42cYbg7bzSOY9ZZj3_hvU5rK3SjB1ADPe8bsIEe_Ba9KBhYxlWd9iyyAR_bloL9n0eeL_OQ6PoR4uGJ6VMUDn9n_ovDGvfgAfvtJs15pCcXPhYusuo1S7SJF1O3fLtR8TitmU1qW88x3SenY2U50dlRG9Y73iNUdnyYBpIHLg._pPkms26QhnuxSFfqpXcGleGXOuZ0.TNOE3Cp8VbLEOEIg6QkavgGLKyFetYhSQ879T4rfhfeEoWvwkjsO1BL2Y3n4Hp9cgfU4y3wZvT.b8qhP7QY0UTYtZkyYH.sydFUXUCec.yVGm29S.s.2N96tfr4qWaI0qntRE.X5MVdwfbhz94n9JshmduqurjKRLlMYVWnLZ_Yderm0HDvT7dnowjyUwBx2UxUKJooauQnNU67QQECmh.HZqcm_OBysLABvdtTtaPhnvJ1QViN_UUjslToVPOs1oyxoTNRbL0VL8yxJc&oauth_version=1.0&oauth_signature=oNaLute5djkIryUEKq0zF6prVFU%3D"
> xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
> xmlns="http://www.yahooapis.com/v1/base.rng">
> <description>Invalid XML POSTed. Error code 25 at line 3, column 0 of input XML.</description>
> <detail/> </error>
</code>```

I'm honestly not sure what differentiates between the two responses, as I've gotten both responses with what I'm pretty sure are the same XML inputs and POST parameters.

Does anybody have any insight?

答:
Just ran into the same issue, and this Stack Overflow article was the only relevant link I found on the web.  Decided it was time I gave back to this community...

The problem is that one of the sample XMLs on Yahoo's transaction page is wrong.  The sample with the { } placeholders and without the <faab_bid> node is correct, but the FAAB example below it has <destination_team_key> instead of <source_team_key> as part of the "drop" transaction.  When I made sure to use "source_team_key" instead of "destination_team_key" for the drop set of nodes, the transaction started working.

I'm guessing that Error Code 25 is a generic error indicating that some part of the XML is wrong or unexpected.  If this doesn't resolve your issue, try starting with the first add/drop sample XML and filling in values one by one.

Hope this helps.

-Igor

Body:
As a quick background: I've already successfully set up a small application that will connect to Yahoo's API and set my lineups on a daily basis using PUT requests on my team's roster per the Yahoo Developer's Guide.

Specifically, where I'm having problems now:

POST

Using POST, players can be added and/or dropped from a team, or trades
  can be proposed. The URI for POSTing to transactions collection is:

http://fantasysports.yahooapis.com/fantasy/v2/league//transactions

The input XML format for a POST request to the transactions API for
  replacing one player with another player in a team is:

<fantasy_content>
  <transaction>
    <type>add/drop</type>
    <players>
      <player>
        <player_key>{player_key}</player_key>
        <transaction_data>
          <type>add</type>
          <destination_team_key>{team_key}</destination_team_key>
        </transaction_data>
      </player>
      <player>
        <player_key>{player_key}</player_key>
        <transaction_data>
          <type>drop</type>
          <source_team_key>{team_key}</source_team_key>
        </transaction_data>
      </player>
    </players>
  </transaction>
</fantasy_content>

My method for making a request is as follows:

  def self.make_signed_request(address, method, user_id, input_file=nil )

    # format http method and return false if not accepted API method
    method = method.upcase
    return false if ( method != "GET" ) && ( method != "POST" ) && ( method != "PUT")

    # find user
    user = User.find(user_id)

    if ( user.yahoo_access_token_expiration.nil? || user.yahoo_access_token_expiration < Time.now )
      # expired token, so renew
      YahooOAuth.renew_token(user_id)
      user.reload
    end

    # normalize text HMAC-SHA1
    digest = OpenSSL::Digest.new('sha1')
    nonce = rand(10 ** 30).to_s.rjust(30,'0')
    timestamp = Time.now.to_i
    text = method + "&" + CGI.escape("#{address}") + "&" + CGI.escape("oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0")

    # create key for HMAC-SHA1
    key = CGI.escape("#{YAHOO_OAUTH_API[:CLIENT_SECRET]}")+ "&" + CGI.escape("#{user.yahoo_access_token_secret}")

    # create HMAC-SHA1 signature for api request
    hmac = OpenSSL::HMAC.digest(digest, key, text)
    signature_sha1 = CGI.escape(Base64.strict_encode64(hmac))

    # make API request
    response = nil
    if method == "GET"
      response = Curl.get("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}")
    elsif method == "POST"
      # return "Not implemented"
      response = Curl.post("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}", input_file) do |http|
        http.headers['Accept'] = 'application/xml'
        http.headers['Content-Type'] = 'application/xml'
      end
    elsif method == "PUT"
      response = Curl.put("#{address}?oauth_consumer_key=#{YAHOO_OAUTH_API[:CLIENT_ID]}&oauth_nonce=#{nonce}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{timestamp}&oauth_token=#{CGI.escape(user.yahoo_access_token)}&oauth_version=1.0&oauth_signature=#{signature_sha1}", input_file) do |http|
        http.headers['Accept'] = 'application/xml'
        http.headers['Content-Type'] = 'application/xml'
      end
    end

    # return raw XML result
    return response.body

  end

When I make my request --

def add_drop(players)
    # players are added in [{player_key}, {add/drop}, {faab_bid (or nil if not FAAB)}] form
    url = "http://fantasysports.yahooapis.com/fantasy/v2/league/#{self.league.league_key}/transactions"
    builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
      xml.fantasy_content {
        xml.transaction {
          xml.type "add/drop"
          xml.faab_bid players[0][2] unless players[0][2].nil?
          xml.players {
            players.each do |player|
              xml.player {
                xml.player_key player[0]
                xml.transaction_data {
                  xml.type player[1] # this will be "add" or "drop"
                  # adds use "destination_team_key," drops use "source_team_key"
                  if player[1] == "add"
                    xml.destination_team_key self.team_key
                  else
                    xml.source_team_key self.team_key
                  end
                } # transaction_data
              } # player
            end
          } # players
        } # transaction
      } # fantasy_content
    end # builder
    xml_input = builder.to_xml
    YahooOAuth.make_signed_request(url, 'put', self.user.id, xml_input)
  end

--the XML generated is shown below --

"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<fantasy_content>\n  <transaction>\n    <type>add/drop</type>\n    <players>\n      <player>\n        <player_key>357.p.10171</player_key>\n        <transaction_data>\n          <type>add</type>\n          <destination_team_key>370.l.4801.t.7</destination_team_key>\n        </transaction_data>\n      </player>\n      <player>\n        <player_key>357.p.9317</player_key>\n        <transaction_data>\n          <type>drop</type>\n          <source_team_key>370.l.4801.t.7</source_team_key>\n        </transaction_data>\n      </player>\n    </players>\n  </transaction>\n</fantasy_content>\n"

-- and the two responses I'll get from Yahoo are:

> <?xml version="1.0" encoding="UTF-8"?> <error xml:lang="en-us"
> yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/370.l.4801/transactions/?oauth_consumer_key=dj0yJmk9dHBIa0h4ekhTSVBnJmQ9WVdrOVlUZHFkMnhMTXpJbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lNQ--&amp;oauth_nonce=892057444475304460343340318332&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_timestamp=1492097395&amp;oauth_token=A%3D2.86iTDxtT4nQ.wxTcn33mgnA8dm3AeME87YRjNthVjxiwfhqKr_oWt0HBgbBeS2DC_dNObN72m0ucgi7CsSFaRjpc5IcnZ_bpJNTC3pUXc37bgH8f0S4irpyXLz8s9ONAYYB.LIDT0sOUvdTgk_lPDnlr1GlPhCe7u54Sq.m_vwq1JQlNUzEVrEs3kOW9wiXk17BditA9OGaVE.tuepvpthDRVBhOye8qjb_ic7UZtT.lvccoGEdgvcShHSyg.YYcnShl7ks23G01hAcXrfGveEk0UncWKNmma42cYbg7bzSOY9ZZj3_hvU5rK3SjB1ADPe8bsIEe_Ba9KBhYxlWd9iyyAR_bloL9n0eeL_OQ6PoR4uGJ6VMUDn9n_ovDGvfgAfvtJs15pCcXPhYusuo1S7SJF1O3fLtR8TitmU1qW88x3SenY2U50dlRG9Y73iNUdnyYBpIHLg._pPkms26QhnuxSFfqpXcGleGXOuZ0.TNOE3Cp8VbLEOEIg6QkavgGLKyFetYhSQ879T4rfhfeEoWvwkjsO1BL2Y3n4Hp9cgfU4y3wZvT.b8qhP7QY0UTYtZkyYH.sydFUXUCec.yVGm29S.s.2N96tfr4qWaI0qntRE.X5MVdwfbhz94n9JshmduqurjKRLlMYVWnLZ_Yderm0HDvT7dnowjyUwBx2UxUKJooauQnNU67QQECmh.HZqcm_OBysLABvdtTtaPhnvJ1QViN_UUjslToVPOs1oyxoTNRbL0VL8yxJc&amp;oauth_version=1.0&amp;oauth_signature=UVmcj2S8c5vqkRgAxsdQ3MQZI54%3D"
> xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
> xmlns="http://www.yahooapis.com/v1/base.rng">
> <description>subresource 'transactions' not supported.</description>
> <detail/> </error>

and

> <?xml version="1.0" encoding="UTF-8"?> <error xml:lang="en-us"
> yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/370.l.4801/transactions?oauth_consumer_key=dj0yJmk9dHBIa0h4ekhTSVBnJmQ9WVdrOVlUZHFkMnhMTXpJbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lNQ--&amp;oauth_nonce=503128074504907304111221170641&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_timestamp=1492097198&amp;oauth_token=A%3D2.86iTDxtT4nQ.wxTcn33mgnA8dm3AeME87YRjNthVjxiwfhqKr_oWt0HBgbBeS2DC_dNObN72m0ucgi7CsSFaRjpc5IcnZ_bpJNTC3pUXc37bgH8f0S4irpyXLz8s9ONAYYB.LIDT0sOUvdTgk_lPDnlr1GlPhCe7u54Sq.m_vwq1JQlNUzEVrEs3kOW9wiXk17BditA9OGaVE.tuepvpthDRVBhOye8qjb_ic7UZtT.lvccoGEdgvcShHSyg.YYcnShl7ks23G01hAcXrfGveEk0UncWKNmma42cYbg7bzSOY9ZZj3_hvU5rK3SjB1ADPe8bsIEe_Ba9KBhYxlWd9iyyAR_bloL9n0eeL_OQ6PoR4uGJ6VMUDn9n_ovDGvfgAfvtJs15pCcXPhYusuo1S7SJF1O3fLtR8TitmU1qW88x3SenY2U50dlRG9Y73iNUdnyYBpIHLg._pPkms26QhnuxSFfqpXcGleGXOuZ0.TNOE3Cp8VbLEOEIg6QkavgGLKyFetYhSQ879T4rfhfeEoWvwkjsO1BL2Y3n4Hp9cgfU4y3wZvT.b8qhP7QY0UTYtZkyYH.sydFUXUCec.yVGm29S.s.2N96tfr4qWaI0qntRE.X5MVdwfbhz94n9JshmduqurjKRLlMYVWnLZ_Yderm0HDvT7dnowjyUwBx2UxUKJooauQnNU67QQECmh.HZqcm_OBysLABvdtTtaPhnvJ1QViN_UUjslToVPOs1oyxoTNRbL0VL8yxJc&amp;oauth_version=1.0&amp;oauth_signature=oNaLute5djkIryUEKq0zF6prVFU%3D"
> xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
> xmlns="http://www.yahooapis.com/v1/base.rng">
> <description>Invalid XML POSTed. Error code 25 at line 3, column 0 of input XML.</description>
> <detail/> </error>

I'm honestly not sure what differentiates between the two responses, as I've gotten both responses with what I'm pretty sure are the same XML inputs and POST parameters.

Does anybody have any insight?


问:
How to get protected property of object in PHP
I have a object having some protected property that I want to get and set. The object looks like

```<code>Fields_Form_Element_Location Object
(
[helper] => formText
[_allowEmpty:protected] => 1
[_autoInsertNotEmptyValidator:protected] => 1
[_belongsTo:protected] =>

[_description:protected] =>
[_disableLoadDefaultDecorators:protected] =>
[_errorMessages:protected] => Array
    (
    )

[_errors:protected] => Array
    (
    )
[_isErrorForced:protected] =>
[_label:protected] => Current City

[_value:protected] => 93399
[class] => field_container field_19 option_1 parent_1
)
</code>```

I want to get value property of the object. When I try $obj->_value or $obj->value it generates error. I searched and found the solution to use PHP Reflection Class. It worked on my local but on server PHP version is 5.2.17 So I cannot use this function there. So any solution how to get such property?

答:
If you want to tinker with a class without adding getters and setters....

PHP 7 adds a call($obj) method (faster than old bindTo) on closures allowing you to call a function so the $this variable will act just as it would within a class -with full permissions.

```<code> //test class with restricted properties
 class test{
    protected $bar="protected bar";
    private $foo="private foo";
    public function printProperties(){
        echo $this->bar."::".$this->foo;
     }
 }

$testInstance=new test();
//we can change or read the restricted properties by doing this...
$change=function(){
    $this->bar="I changed bar";
    $this->foo="I changed foo";
};
$change->call($testInstance);
$testInstance->printProperties();
//outputs I changed bar::I changed foo in php 7.0
</code>```

Body:
I have a object having some protected property that I want to get and set. The object looks like

Fields_Form_Element_Location Object
(
[helper] => formText
[_allowEmpty:protected] => 1
[_autoInsertNotEmptyValidator:protected] => 1
[_belongsTo:protected] =>

[_description:protected] =>
[_disableLoadDefaultDecorators:protected] =>
[_errorMessages:protected] => Array
    (
    )

[_errors:protected] => Array
    (
    )
[_isErrorForced:protected] =>
[_label:protected] => Current City

[_value:protected] => 93399
[class] => field_container field_19 option_1 parent_1
)

I want to get value property of the object. When I try $obj->_value or $obj->value it generates error. I searched and found the solution to use PHP Reflection Class. It worked on my local but on server PHP version is 5.2.17 So I cannot use this function there. So any solution how to get such property?

Body:
If you want to tinker with a class without adding getters and setters....

PHP 7 adds a call($obj) method (faster than old bindTo) on closures allowing you to call a function so the $this variable will act just as it would within a class -with full permissions.

 //test class with restricted properties
 class test{
    protected $bar="protected bar";
    private $foo="private foo";
    public function printProperties(){
        echo $this->bar."::".$this->foo;
     }
 }

$testInstance=new test();
//we can change or read the restricted properties by doing this...
$change=function(){
    $this->bar="I changed bar";
    $this->foo="I changed foo";
};
$change->call($testInstance);
$testInstance->printProperties();
//outputs I changed bar::I changed foo in php 7.0


问:
PHP simultaneous TCP connections from same browser
I have a PHP script which opens a socket connection(using fsockopen) and takes about 15secs to complete/return the result to the browser. Mean while, if the browser sends a second request it is serialized. This is giving a bad user experience because if the user clicks 3 times, then the third request which gets sent after 30sec is the one that gets the response -- the first 2 requests from browser prespective are getting lost.

I do not have any session in my script, but tried putting session_write_close() at the beginning of my script which didnt help.

Also session.auto_start in the php.ini = 0.

Any ideas as to how to make the client requests from the same browser parallel??

Thanks
Gary

答:
1) Download and install Firefox

2) Download and install Firebug

3) Add a sleep(10) to your PHP script so that it pauses for a few seconds before returning its response

4) Open up your webpage, and watch the outbound connections with Firebug. You should see several that are open and do not yet have a response. They should all return at about the same time, when each one finishes the 10 second delay.

If you do not see multiple connections open at the same time, and return at approximately the same time, then you need to look at your front end code. AJAX requests are asynchronous and can run in parallel. If you are seeing them run serially instead, then it means you need to fix your JavaScript code, not anything on the server.

Parallel asynchronous Ajax requests using jQuery

ContentLicense: CC BY-SA 2.5


问:
How to check a Float variable is empty or null IN JAVA
I have a Float variable which is initialised from a function returning the Float value, and there can be chance to return null in some cases. So I need to check the value in the variable is null or empty. If the value is empty I need to initialise variable wb1 with value 1. I am using Java Spring. This is the code currently I amusing,

```<code>Float wb1 = !StringUtils.isEmpty(getArea())?getArea() : 1.0f;
</code>```

What is the correct way to check and initilize with value 1.0f

答:
First: Float is an object and float is the primitive type.

null check is used for objects. For primitives you should use the default values check. For float the default value is 0.0f.

Body:
I have a Float variable which is initialised from a function returning the Float value, and there can be chance to return null in some cases. So I need to check the value in the variable is null or empty. If the value is empty I need to initialise variable wb1 with value 1. I am using Java Spring. This is the code currently I amusing,

Float wb1 = !StringUtils.isEmpty(getArea())?getArea() : 1.0f;

What is the correct way to check and initilize with value 1.0f


问:
exploding multiple csv fields in python
I have an excel file with 200 rows, 2 of which have comma separated values in them. If I output them to tab-separated, it would look like this:

```<code>col1  col2    col3
a     b,c     d,e
f     g,h     i,j
</code>```

I need to explode to get a dataframe like this, exploding 200 rows into ~4,000:

```<code>col1  col2  col3
a     b     d
a     b     e
a     c     d
a     c     e
f     g     i
f     g     j
f     h     i
f     h     j
</code>```

I don't see any explode functionality in pandas and haven't been able to figure out how to do this having the columns of comma-separated values uneven in length - not sure how split would work here.

Help me stack-overflow, you're my only hope. Thanks!

答:
Use itertools.product to get all combinations between col2 and col3, and then convert them into separate columns</p>

```<code>from itertools import product
df.set_index('col1')\
  .apply(lambda x: pd.Series(list(product(x.col2.split(','),x.col3.split(',')))),axis=1)\
  .stack()\
  .reset_index(1,drop=True)\
  .apply(pd.Series)\
  .reset_index().rename(columns={0:'col1',1:'col3'})

Out[466]:
  col1 col1 col3
0    a    b    d
1    a    b    e
2    a    c    d
3    a    c    e
4    f    g    i
5    f    g    j
6    f    h    i
7    f    h    j
</code>```

Title: exploding multiple csv fields in python

Body:
I have an excel file with 200 rows, 2 of which have comma separated values in them. If I output them to tab-separated, it would look like this:

col1  col2    col3
a     b,c     d,e
f     g,h     i,j

I need to explode to get a dataframe like this, exploding 200 rows into ~4,000:

col1  col2  col3
a     b     d
a     b     e
a     c     d
a     c     e
f     g     i
f     g     j
f     h     i
f     h     j

I don't see any explode functionality in pandas and haven't been able to figure out how to do this having the columns of comma-separated values uneven in length - not sure how split would work here.

Help me stack-overflow, you're my only hope. Thanks!

Body:
Use itertools.product to get all combinations between col2 and col3, and then convert them into separate columns

from itertools import product
df.set_index('col1')\
  .apply(lambda x: pd.Series(list(product(x.col2.split(','),x.col3.split(',')))),axis=1)\
  .stack()\
  .reset_index(1,drop=True)\
  .apply(pd.Series)\
  .reset_index().rename(columns={0:'col1',1:'col3'})

Out[466]:
  col1 col1 col3
0    a    b    d
1    a    b    e
2    a    c    d
3    a    c    e
4    f    g    i
5    f    g    j
6    f    h    i
7    f    h    j


问:
divs height and width are not fixed in carousel slider
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

```<code><html lang="en">

<head>

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

</head>

<body>
    <section id="projects">
        <div class="content-box">
            <div class="content-title wow animated fadeInDown" data-wow-duration="1s" data-wow-delay=".5s">
                <h3>My Projects</h3>
                <div class="content-title-underline"></div>
            </div>
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div id="my-projects" class="owl-carousel owl-theme">
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTp1-NNfLpNtsFQY25z7A4u9pp2D_vJHTNU70RDupydx4i7BrMKYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit Website</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>

                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur . </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" target="_blank">visit site</a>

                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQAOoZwRkgQ3KDjCJ2-GRtjKDc88iUqU6mJva17ym63D2W0XwnYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,  </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit site</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.</p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#projects" role="button">Visit site</a>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <body>
</code>```

css

```<code>    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}
</code>```

js

```<code>$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});
</code>```

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.

答:
Just simply use a fixed height for images: </p>

```<code>.project-image img {
    width: 100%;
    max-width: 480px;
    height: 480px;
    margin: 0 auto;
}
</code>```

Body:
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

My Projects

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                                        Visit Website

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur .

                                        visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,

                                        Visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.

                                        Visit site

css

    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}

js

$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.

Body:
Just simply use a fixed height for images:

.project-image img {
    width: 100%;
    max-width: 480px;
    height: 480px;
    margin: 0 auto;
}


问:
Does Visual Studio Community 2017 require sign in with microsoft account?
The question pretty much is self explanatory. I just want to know if I can use Visual Studio without signing into my Microsoft account.</p>

答: No, if you just want to try it for 30 days. but later on you have to sign-in with you Microsoft account to use it further.</p>


问:
Sorry, this action is not available in simulation
My test invocation name is "Mrs Tang", so i input "Talk to Mrs Tang", but it responds "Sorry, this action is not available in simulation"...

Does anybody know How can I resolve this error?

答: I think sometimes I run into the same error. I get past it by toggling the Active switch off and on.


问:
Unit testing memory leaks
I have an application in which a lot of memory leaks are present. For example if a open a view and close it 10 times my memory consumption rises becauses the views are not completely cleaned up. These are my memory leaks. From a testdriven perspective i would like to write a test proving my leaks and (after I fixed the leak) asserting I fixed it. That way my code won't be broken later on. So in short:

Is there a way to assert that my code is not leaking memory from a unit test?

e.g. Can i do something like this:

```<code>objectsThatShouldNotBeThereCount = MemAssertion.GetObjects<MyView>().Count;
Assert.AreEqual(0, objectsThatShouldNotBeThereCount);
</code>```

I am not interested in profiling. I use Ants profiler (which I like a lot) but would also like to write tests to make sure the 'leaks' don't come back

I am using C# / Nunit but am interesed in anyone having a philosophy on this...

答:
How about something like:</p>

```<code>long originalByteCount = GC.GetTotalMemory(true);
SomeOperationThatMayLeakMemory();
long finalByteCount = GC.GetTotalMemory(true);
Assert.AreEqual(originalByteCount, finalByteCount);
</code>```

Title: Unit testing memory leaks

Body:
I have an application in which a lot of memory leaks are present. For example if a open a view and close it 10 times my memory consumption rises becauses the views are not completely cleaned up. These are my memory leaks. From a testdriven perspective i would like to write a test proving my leaks and (after I fixed the leak) asserting I fixed it. That way my code won't be broken later on. So in short:

Is there a way to assert that my code is not leaking memory from a unit test?

e.g. Can i do something like this:

objectsThatShouldNotBeThereCount = MemAssertion.GetObjects<MyView>().Count;
Assert.AreEqual(0, objectsThatShouldNotBeThereCount);

I am not interested in profiling. I use Ants profiler (which I like a lot) but would also like to write tests to make sure the 'leaks' don't come back

I am using C# / Nunit but am interesed in anyone having a philosophy on this...

Body:
How about something like:

long originalByteCount = GC.GetTotalMemory(true);
SomeOperationThatMayLeakMemory();
long finalByteCount = GC.GetTotalMemory(true);
Assert.AreEqual(originalByteCount, finalByteCount);


问:
Running a Simple Falcon App
I've a simple falcon app straight from the getting started example

```<code>import falcon
import json

class QuoteResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        quote = {
            'quote': 'I\'ve always been more interested in the future than in the past.',
            'author': 'Grace Hopper'
        }

        resp.body = json.dumps(quote)

api = falcon.API()
api.add_route('/quote', QuoteResource())
</code>```

The code is in a file called manage.py

When I try to run gunicorn manage:app
This is what I get

```<code>2017-06-04 20:47:18 -0700] [2370] [INFO] Starting gunicorn 19.7.1
[2017-06-04 20:47:18 -0700] [2370] [INFO] Listening at: http://127.0.0.1:8000 (2370)
[2017-06-04 20:47:18 -0700] [2370] [INFO] Using worker: sync
[2017-06-04 20:47:18 -0700] [2373] [INFO] Booting worker with pid: 2373
Failed to find application: 'manage'
[2017-06-04 20:47:18 -0700] [2373] [INFO] Worker exiting (pid: 2373)
[2017-06-04 20:47:18 -0700] [2370] [INFO] Shutting down: Master
[2017-06-04 20:47:18 -0700] [2370] [INFO] Reason: App failed to load.
</code>```

What am I doing wrong here?

答:
Not sure whether it is a typo or because of misunderstanding but you should start the application this way:

```<code>gunicorn manage:api
</code>```

But not gunicorn manage:app

The manage:api option tells to invoke the api object defined in your manage.py module. Otherwise you need to rename api variable to app in your code.

Then you can check that application is running by accessing the following url:

```<code>http://localhost:8000/quote
</code>```

By default the port should 8000 but you need to check it when gunicorn starts. It should be something like this:

```<code>[INFO] Listening at: http://127.0.0.1:8000
</code>```

Title: Running a Simple Falcon App

Body:
I've a simple falcon app straight from the getting started example

import falcon
import json

class QuoteResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        quote = {
            'quote': 'I\'ve always been more interested in the future than in the past.',
            'author': 'Grace Hopper'
        }

        resp.body = json.dumps(quote)

api = falcon.API()
api.add_route('/quote', QuoteResource())

The code is in a file called manage.py

When I try to run gunicorn manage:app
This is what I get

2017-06-04 20:47:18 -0700] [2370] [INFO] Starting gunicorn 19.7.1
[2017-06-04 20:47:18 -0700] [2370] [INFO] Listening at: http://127.0.0.1:8000 (2370)
[2017-06-04 20:47:18 -0700] [2370] [INFO] Using worker: sync
[2017-06-04 20:47:18 -0700] [2373] [INFO] Booting worker with pid: 2373
Failed to find application: 'manage'
[2017-06-04 20:47:18 -0700] [2373] [INFO] Worker exiting (pid: 2373)
[2017-06-04 20:47:18 -0700] [2370] [INFO] Shutting down: Master
[2017-06-04 20:47:18 -0700] [2370] [INFO] Reason: App failed to load.

What am I doing wrong here?

Body:
Not sure whether it is a typo or because of misunderstanding but you should start the application this way:

gunicorn manage:api

But not gunicorn manage:app

The manage:api option tells to invoke the api object defined in your manage.py module. Otherwise you need to rename api variable to app in your code.

Then you can check that application is running by accessing the following url:

http://localhost:8000/quote

By default the port should 8000 but you need to check it when gunicorn starts. It should be something like this:

[INFO] Listening at: http://127.0.0.1:8000


问:
Set properties on an array, funky array returned in chrome/node/canary?
From the function below should the array returned from the chrome console be displayed like this?

```<code>[ name: 'Mike', age: 60, role: 'director' ]
</code>```

When I type the array in the chrome console I get an expected syntax error returned. I understand I'm setting properties on an empty array but I thought the array wouldn't be display like this
[ name: 'Mike', age: 60, role: 'director' ]

Is this chrome trying to help me out by telling me the properties?

Entering the function in jsfiddle, firefox and safari returns an empty array but chrome displays the properties on an array.

var object = {
  name: 'Mike',
  age: 60,
  role: 'director'
}
var array = []

function test_reduce(object) {
  return Object.keys(object).reduce(function(array, key) {
    array[key] = object[key]
    return array;
  }, array)
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)

function test_Loop(object) {
  for (var key in object) {
    array[key] = object[key]
  }
  return array;
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)
console.log(test_Loop(object))```
</div>
</div>
</p>

<p>I'm using </p>

```Chrome Version 61.0.3119.0 (Official Build) canary (64-bit)
Chrome Version 58.0.3029.110 (64-bit)
Node.js v7.7.4
Safari Version 10.1.1 (12603.2.4)
Firefox 53.0.3 (64-bit)
```

答: Array returned is same in all the cases, although while other browsers do not list the properties of an array by default, chrome does (Specific to scenarios when empty array is used as an map). For example if you click on the empty array returned on Firefox console, it will list down the properties you have added.</p>

Body:
From the function below should the array returned from the chrome console be displayed like this?

[ name: 'Mike', age: 60, role: 'director' ]

When I type the array in the chrome console I get an expected syntax error returned. I understand I'm setting properties on an empty array but I thought the array wouldn't be display like this
[ name: 'Mike', age: 60, role: 'director' ]

Is this chrome trying to help me out by telling me the properties?

Entering the function in jsfiddle, firefox and safari returns an empty array but chrome displays the properties on an array.

var object = {
  name: 'Mike',
  age: 60,
  role: 'director'
}
var array = []

function test_reduce(object) {
  return Object.keys(object).reduce(function(array, key) {
    array[key] = object[key]
    return array;
  }, array)
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)

function test_Loop(object) {
  for (var key in object) {
    array[key] = object[key]
  }
  return array;
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)
console.log(test_Loop(object))

I'm using

Chrome Version 61.0.3119.0 (Official Build) canary (64-bit)
Chrome Version 58.0.3029.110 (64-bit)
Node.js v7.7.4
Safari Version 10.1.1 (12603.2.4)
Firefox 53.0.3 (64-bit)


问:
find and return a pointer to a object in a vector
New to c++, not really sure where I'm going wrong. Still wrapping my head around ptrs.

I have a vector of profile objects. I want to find a particular object based on one of it's properties. Then I want to return that object. I don't want to make copies or anything of the object so I guess I will need to return a pointer to the particular object?

Here is my code:

```<code>Profile* profileManager::getProfile(const std::string& name)
{
    std::vector<Profile>::iterator it = std::find_if(allProfiles.begin(), allProfiles.end(), [name](Profile &p) { return p.getName() == name; });
    return it != allProfiles.end() ? *it : nullptr;
}
</code>```

There's a few things wrong that I don't know how to fix up. I want to return null if there isn't a match found and let the caller handle it, how would I do this? I'm getting a incompatible type at the moment and I've tried to change the return it around a bit but had no luck. It also says it isn't of the right type. How do I get it to return a pointer to the profile if it is found?

Any help/advice appreciated. Thanks.

答:
```<code>return it != allProfiles.end() ? *it : nullptr;
</code>```

This almost does what you want. The type of *it is a Profile. To get a pointer to it, just take the address: &*it

Also, some recommended changes.

<s>Make getProfile a constant method. It doesn't (and shouldn't) modify anything</s>.

Having a constant overload of getProfile is a good idea, but you'll want to keep the mutable one too.

Have the lambda parameter be a constant reference (const Profile &p). This is also necessary if you make the above change.

You don't need to capture name by value. Capturing it by reference saves copying. [&name]

Body:
New to c++, not really sure where I'm going wrong. Still wrapping my head around ptrs.

I have a vector of profile objects. I want to find a particular object based on one of it's properties. Then I want to return that object. I don't want to make copies or anything of the object so I guess I will need to return a pointer to the particular object?

Here is my code:

Profile* profileManager::getProfile(const std::string& name)
{
    std::vector<Profile>::iterator it = std::find_if(allProfiles.begin(), allProfiles.end(), [name](Profile &p) { return p.getName() == name; });
    return it != allProfiles.end() ? *it : nullptr;
}

There's a few things wrong that I don't know how to fix up. I want to return null if there isn't a match found and let the caller handle it, how would I do this? I'm getting a incompatible type at the moment and I've tried to change the return it around a bit but had no luck. It also says it isn't of the right type. How do I get it to return a pointer to the profile if it is found?

Any help/advice appreciated. Thanks.

Body:
return it != allProfiles.end() ? *it : nullptr;

This almost does what you want. The type of *it is a Profile. To get a pointer to it, just take the address: &*it

Also, some recommended changes.

<s>Make getProfile a constant method. It doesn't (and shouldn't) modify anything</s>.

Having a constant overload of getProfile is a good idea, but you'll want to keep the mutable one too.

Have the lambda parameter be a constant reference (const Profile &p). This is also necessary if you make the above change.

You don't need to capture name by value. Capturing it by reference saves copying. [&name]


问:
How to write automated unit tests for java annotation processor?
I'm experimenting with java annotation processors. I'm able to write integration tests using the "JavaCompiler" (in fact I'm using "hickory" at the moment). I can run the compile process and analyse the output. The Problem: a single test runs for about half a second even without any code in my annotation processor. This is way too long to using it in TDD style.

Mocking away the dependencies seems very hard for me (I would have to mock out the entire "javax.lang.model.element" package). Have someone succeed to write unit tests for an annotation processor (Java 6)? If not ... what would be your approach?

答:
I was in a similar situation, so I created the Avatar library. It won't give you the performance of a pure unit test with no compilation, but if used correctly you shouldn't see much of a performance hit.

Avatar lets you write a source file, annotate it, and convert it to elements in a unit test. This allows you to unit test methods and classes which consume Element objects, without manually invoking javac.


答:
Try this, set fixed height to your images.

$(document).ready(function () {
  $("#my-projects").owlCarousel({
    items: 1,
    autoplay: true,
    smartSpeed: 700,
    loop: true,
    autoplayHoverPause: true
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#projects {
  background-color: #f65d52;
  /*background-color: #2098D1;*/
}

#projects .content-title h3 {
  color: #fff;
}

.project-info {
  padding: 25px 0 25px 0;
  color: #fff;
}

.project-info h5 {
  font-size: 25px;
  font-weight: 700;
}

.project-image img {
  max-width: 480px !important;
  max-height: 480px !important;
  margin: 0 auto;
  object-fit: contain;
  height: 340px;
}

.project-info-text {
  line-height: 170%;
  letter-spacing: 1px;
  color: #fff !important;
  font-weight: 500;
  width: 70%;
  margin: 0 auto;
}

.project-btn {
  padding-top: 30px;
}</code>```

  <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
  <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

My Projects

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                                    Visit Website

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur .

                                    visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,

                                    Visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.

                                    Visit site

```

Title: divs height and width are not fixed in carousel slider

Body:
Try this, set fixed height to your images.

$(document).ready(function () {
  $("#my-projects").owlCarousel({
    items: 1,
    autoplay: true,
    smartSpeed: 700,
    loop: true,
    autoplayHoverPause: true
  });
});

#projects {
  background-color: #f65d52;
  /*background-color: #2098D1;*/
}

#projects .content-title h3 {
  color: #fff;
}

.project-info {
  padding: 25px 0 25px 0;
  color: #fff;
}

.project-info h5 {
  font-size: 25px;
  font-weight: 700;
}

.project-image img {
  max-width: 480px !important;
  max-height: 480px !important;
  margin: 0 auto;
  object-fit: contain;
  height: 340px;
}

.project-info-text {
  line-height: 170%;
  letter-spacing: 1px;
  color: #fff !important;
  font-weight: 500;
  width: 70%;
  margin: 0 auto;
}

.project-btn {
  padding-top: 30px;
}

<head>

  <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
  <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">
</head>

<body>
  <section id="projects">
    <div class="content-box">
        <div class="content-title wow animated fadeInDown" data-wow-duration="1s" data-wow-delay=".5s">
            <h3>My Projects</h3>
            <div class="content-title-underline"></div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div id="my-projects" class="owl-carousel owl-theme">
                        <div class="project-list">
                            <div class="project-image">
                                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTp1-NNfLpNtsFQY25z7A4u9pp2D_vJHTNU70RDupydx4i7BrMKYw" class="img-responsive" alt="project-image1">
                            </div>
                            <div class="project-info text-center">
                                <h5>Project Title</h5>
                                <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
                                <div class="project-btn">
                                    <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit Website</a>
                                </div>

                            </div>
                        </div>
                        <div class="project-list">
                            <div class="project-image">
                                <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                            </div>

                            <div class="project-info text-center">
                                <h5>Project Title</h5>
                                <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur . </p>
                                <div class="project-btn">
                                    <a class="btn btn-lg btn-general btn-white" href="#" target="_blank">visit site</a>

                                </div>

                            </div>
                        </div>
                        <div class="project-list">
                            <div class="project-image">
                                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQAOoZwRkgQ3KDjCJ2-GRtjKDc88iUqU6mJva17ym63D2W0XwnYw" class="img-responsive" alt="project-image1">
                            </div>
                            <div class="project-info text-center">
                                <h5>Project Title</h5>
                                <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,  </p>
                                <div class="project-btn">
                                    <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit site</a>
                                </div>

                            </div>
                        </div>
                        <div class="project-list">
                            <div class="project-image">
                                <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                            </div>
                            <div class="project-info text-center">
                                <h5>Project Title</h5>
                                <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.</p>
                                <div class="project-btn">
                                    <a class="btn btn-lg btn-general btn-white" href="#projects" role="button">Visit site</a>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
  </section>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>
</body>


问:
How can I integrate ion_auth library with CodeIgniter 3 HMVC on Linux?
I am coding a base application using codeigniter, hmvc and ion_auth. I have loaded ion_auth in application/modules/Users. Everything works on my windows development PC, but I am getting an error on my hosting server (linux) when the application starts:

```<code>  Message: Unable to locate the model you have specified: Ion_auth_model
</code>```

In the modules/Users/library/Ion_auth.php, I try to load the model as follows:

```<code>  $this->load->model('Users/Ion_auth_model', 'ion_auth_model');
</code>```

The model file is in modules/Users/models/Ion_auth_model.php.

I have tried many different combinations of file names. I know Linux is case sensitive. Any suggestions? Am I missing something simple?

答:
At first,  your folder names must be started with lowercase character.
....... keep Ion Auth in its own module folder... your modules folder must look like:</p>

```
 modules
   ∟ home
   ∟ admin
   ∟ auth
      ∟ controllers
      ∟ models
      ∟ views
      ∟ libraries
      ∟ config
      ∟ language
```

Body:
I am coding a base application using codeigniter, hmvc and ion_auth. I have loaded ion_auth in application/modules/Users. Everything works on my windows development PC, but I am getting an error on my hosting server (linux) when the application starts:

  Message: Unable to locate the model you have specified: Ion_auth_model

In the modules/Users/library/Ion_auth.php, I try to load the model as follows:

  $this->load->model('Users/Ion_auth_model', 'ion_auth_model');

The model file is in modules/Users/models/Ion_auth_model.php.

I have tried many different combinations of file names. I know Linux is case sensitive. Any suggestions? Am I missing something simple?

Body:
At first,  your folder names must be started with lowercase character.
....... keep Ion Auth in its own module folder... your modules folder must look like:

 modules
   ∟ home
   ∟ admin
   ∟ auth
      ∟ controllers
      ∟ models
      ∟ views
      ∟ libraries
      ∟ config
      ∟ language


答:
Assume you mean Float, the box of float, you can use

```<code>Optional.ofNullable(wbCalculation(area.getArea(), CitySizeByArea.SIZE1.value, area.getRate1(), task.getTaskId())).orElse(0f)
</code>```

Title: How to check a Float variable is empty or null IN JAVA

Body:
Assume you mean Float, the box of float, you can use

Optional.ofNullable(wbCalculation(area.getArea(), CitySizeByArea.SIZE1.value, area.getRate1(), task.getTaskId())).orElse(0f)


问:
Running untrusted code in Lua via loadstring
I'm working with a modding api for a game, for those curious it's factorio but it's not really relevant, and the Lua environment is HEAVILY limited, blocking functions like setfenv, it's a 5.1 environment and I do have access to loadstring, pcall, etc. My question is how would you recommend running 'unsafe' code that is provided by a user and limiting what functions they can access without access to environment modification functions? (Preferably whitelist functions/values instead of blacklist, but I'll take whatever I can get)

答:
In Lua 5.1 you need setfenv to create a secure sandbox (see this answer for a typical procedure). So if you don't have access to setfenv, then I don't think it can't be done.

Then again, if the environment you're working in has disabled setfenv and has put a wrapper around loadstring to avoid malicious bytecode loading (again, see the answer I linked) then you might be able to run the script without setting up a special environment for it. It really depends on the details of your current environment as to whether it's safe or not.


问:
How do I program using cat?
In this xkcd comic:

they mention that real programmers use cat. Well, I was asking myself: how could you program using the cat command?

Title: How do I program using cat?


问:
Unable to locate input element under div in Selenium
I am trying to located input element "mpcname" in js file which is under div and table elements.

The code I have written to locate the element is as follows but is not detecting the Input element with the name mpcName in it.

```<code>Driver.FindElement(By.XPath(".//input[contains(.,'mpcName')]"));
</code>```

The HTML code looks like below.

```<code><div enable-tooltips="" class="ng-scope">
<form name="InstanceDetailForm" ng-submit="doApply()" novalidate="" class="ng-pristine ng-invalid ng-invalid-required ng-valid-unnamed ng-valid-maxlength ng-valid-not-integer">
    <table class="table-condensed" style="width: 100%;">
        <tbody><tr>
            <td></td>
        </tr>
        <tr>
            <td>
                <table style="width: 100%;">
                    <tbody><tr>
                        <td class="pull-left">
                            <h4 class="ng-binding">Controller Configuration<b ng-show="InstanceIsDirty()" class="ng-hide"> *</b></h4>
                        </td>

                        <td class="pull-right">
                            <button id="btnApply" type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Save an APC instance">
                                <span class="glyphicon glyphicon-save"></span> Apply
                            </button>

                            <button id="btnExportConfig" type="button" class="btn btn-primary" ng-click="goToInstanceList()" data-toggle="tooltip" data-placement="bottom" title="Cancel save and redirect to APC instance list page.">
                                <span class="glyphicon glyphicon-remove"></span> Cancel
                            </button>
                        </td>
                    </tr>
                </tbody></table>
            </td>
        </tr>
        <tr>
            <td>
                <table style="width: 100%" class="table-condensed table-striped  table-bordered">
                    <tbody><tr>
                        <td>Name</td>
                        <td>
                            **<input id="mpcname" name="mpcname" ng-model="mpcname" value="" ng-required="true" is-named="" size="50" autocomplete="off" ng-disabled="!allowEditInstanceName(mpcname,state)" class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-unnamed ng-touched" required="required" type="text">**
</code>```

答:
With xpath ".//input[contains(.,'mpcName')]" you are actually looking for an <input> element with text mpcName. mpcName is actually the id (and name and ng-model) attribute. You can use

```<code>Driver.FindElement(By.Id("mpcName"));
</code>```

Or

```<code>Driver.FindElement(By.Name("mpcName"));
</code>```

Body:
I am trying to located input element "mpcname" in js file which is under div and table elements.

The code I have written to locate the element is as follows but is not detecting the Input element with the name mpcName in it.

Driver.FindElement(By.XPath(".//input[contains(.,'mpcName')]"));

The HTML code looks like below.

<form name="InstanceDetailForm" ng-submit="doApply()" novalidate="" class="ng-pristine ng-invalid ng-invalid-required ng-valid-unnamed ng-valid-maxlength ng-valid-not-integer">

Controller Configuration *

                            <button id="btnApply" type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Save an APC instance">
                                 Apply
                            </button>

                            <button id="btnExportConfig" type="button" class="btn btn-primary" ng-click="goToInstanceList()" data-toggle="tooltip" data-placement="bottom" title="Cancel save and redirect to APC instance list page.">
                                 Cancel
                            </button>

                        Name

                            **<input id="mpcname" name="mpcname" ng-model="mpcname" value="" ng-required="true" is-named="" size="50" autocomplete="off" ng-disabled="!allowEditInstanceName(mpcname,state)" class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-unnamed ng-touched" required="required" type="text">**

Body:
With xpath ".//input[contains(.,'mpcName')]" you are actually looking for an <input> element with text mpcName. mpcName is actually the id (and name and ng-model) attribute. You can use

Driver.FindElement(By.Id("mpcName"));

Or

Driver.FindElement(By.Name("mpcName"));


问:
Add text over images next to each other with react inline styles
I've lined up a set of equally sized images next to each other scaled by a percentage width. I'm fairly new to this and am hoping to get some help on figuring out how to now add text on top of each of the images.</p>

```<code>const style1 = {
  display: 'block'
}

const style2 = {
  float: "center",
  fontSize: '9pt',
  textAlign: 'center',
  width: '30%',
  marginRight: '1.6666665%',
  marginLeft: '1.6666665%',
  marginTop: '1%',
  marginBottom: '0.5em',
}
</code>```

```<code><div style={style1}>
  <a href="" className="icons"><img style={style2} src="https://ucarecdn.com/182bd14b-648e-478f-a4dc-b885a489a543/-/crop/3456x3456/864,0/-/resize/500x500/"/></a>
  <a href="" className="icons"><img style={style2} src="https://ucarecdn.com/209579d4-2c4e-4422-b633-5b23edd7bc99/-/crop/1600x1600/480,0/-/resize/500x500/"/></a>
  <a href="" className="icons"><img style={style2} src="https://ucarecdn.com/a7d04a85-431e-401f-b534-de23dd6442f7/-/crop/2304x2304/576,0/-/resize/500x500/"/></a>
</div>
</code>```

答:
I create an example for you :

HTML :

```<code><div class="image">
  <img src="http://lorempixel.com/400/400/sports/2" alt="" />
  <h2><span>Some Text</span></h2></div><br/>
</div>

<div class="image">
  <img src="http://lorempixel.com/400/400/food/5" alt="" />
  <h2><span>Some Other Text</span></h2></div><br/>
</div>
</code>```

CSS :

```<code>.image {
   position: relative;
   width: 100%; /* for IE 6 */
}

h2 {
  position: absolute;
  top: 300px;
  left: 0;
  width: 100%;
}

h2 span {
   color: white;
   font: bold 24px/45px Helvetica, Sans-Serif;
   letter-spacing: -1px;
   background: rgb(0, 0, 0); /* fallback color */
   background: rgba(0, 0, 0, 0.4);
   padding: 10px;
}
</code>```

https://jsfiddle.net/emilvr/f03m3Lks/1/

Body:
I've lined up a set of equally sized images next to each other scaled by a percentage width. I'm fairly new to this and am hoping to get some help on figuring out how to now add text on top of each of the images.

const style1 = {
  display: 'block'
}

const style2 = {
  float: "center",
  fontSize: '9pt',
  textAlign: 'center',
  width: '30%',
  marginRight: '1.6666665%',
  marginLeft: '1.6666665%',
  marginTop: '1%',
  marginBottom: '0.5em',
}

Body:
I create an example for you :

HTML :

<div class="image">
  <img src="http://lorempixel.com/400/400/sports/2" alt="" />
  <h2><span>Some Text</span></h2></div><br/>
</div>

<div class="image">
  <img src="http://lorempixel.com/400/400/food/5" alt="" />
  <h2><span>Some Other Text</span></h2></div><br/>
</div>

CSS :

.image {
   position: relative;
   width: 100%; /* for IE 6 */
}

h2 {
  position: absolute;
  top: 300px;
  left: 0;
  width: 100%;
}

h2 span {
   color: white;
   font: bold 24px/45px Helvetica, Sans-Serif;
   letter-spacing: -1px;
   background: rgb(0, 0, 0); /* fallback color */
   background: rgba(0, 0, 0, 0.4);
   padding: 10px;
}

https://jsfiddle.net/emilvr/f03m3Lks/1/


问:
SQL Server Nested transaction in Stored Procedure
I'm using SQL Server 2014; my stored procedure will be nested transaction procedure, whereby it will call few stored procedures that have transaction in them. If either one of the inner stored procedures hits an error, then will rollback all, such as

```<code>Begin Try
Begin Tran
   Exec Stored Proc 1 (with begin tran inside)
   Exec Stored Proc 2 (with begin tran inside)
   Exec Stored Proc 3 (with begin tran inside)
   Exec Stored Proc 4 (with begin tran inside)
   Exec Stored Proc 5 (with begin tran inside)
Commit Tran
End Try
Begin Catch
   Catch exception then roll back tran
End Catch
</code>```

The problem is the transaction count after execute the inner stored procedures are mismatched, however if I didn't open a transaction in the inner stored procedure, it won't rollback. Can anyone give me some suggestions?

答:
Committing inner transactions is ignored by the SQL Server Database Engine. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed.

Nesting Transactions

Body:
I'm using SQL Server 2014; my stored procedure will be nested transaction procedure, whereby it will call few stored procedures that have transaction in them. If either one of the inner stored procedures hits an error, then will rollback all, such as

Begin Try
Begin Tran
   Exec Stored Proc 1 (with begin tran inside)
   Exec Stored Proc 2 (with begin tran inside)
   Exec Stored Proc 3 (with begin tran inside)
   Exec Stored Proc 4 (with begin tran inside)
   Exec Stored Proc 5 (with begin tran inside)
Commit Tran
End Try
Begin Catch
   Catch exception then roll back tran
End Catch

The problem is the transaction count after execute the inner stored procedures are mismatched, however if I didn't open a transaction in the inner stored procedure, it won't rollback. Can anyone give me some suggestions?


问:
AWS - IdentityPool not found
I am writing an app to implement offline sync functionality using Amazon Web Services (AWS) I am following this out-dated tutorial and keeping getting an error when trying to run my code with my current identity pool id.

ap-southeast-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

I have set permissions for Auth and Non-Auth users using this JSON

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "sdb:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
</code>```

I have also allowed unauthenticated access:

What am I missing?

答:
In the tutorial code, you will see the function below

```<code>    public SimpleDBStorage()
    {
        var credentials = new CognitoAWSCredentials(
                              Constants.CognitoIdentityPoolId,
                              RegionEndpoint.<REGION>);
        var config = new AmazonSimpleDBConfig();
        config.RegionEndpoint = RegionEndpoint.<REGION>;
        client = new AmazonSimpleDBClient(credentials, config);

        Items = new List<TodoItem>();
        SetupDomain();
    }
</code>```

You must update these regions to the region you are using in AWS.

Title: AWS - IdentityPool not found

Body:
I am writing an app to implement offline sync functionality using Amazon Web Services (AWS) I am following this out-dated tutorial and keeping getting an error when trying to run my code with my current identity pool id.

ap-southeast-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

I have set permissions for Auth and Non-Auth users using this JSON

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "sdb:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

I have also allowed unauthenticated access:

What am I missing?

Body:
In the tutorial code, you will see the function below

    public SimpleDBStorage()
    {
        var credentials = new CognitoAWSCredentials(
                              Constants.CognitoIdentityPoolId,
                              RegionEndpoint.<REGION>);
        var config = new AmazonSimpleDBConfig();
        config.RegionEndpoint = RegionEndpoint.<REGION>;
        client = new AmazonSimpleDBClient(credentials, config);

        Items = new List<TodoItem>();
        SetupDomain();
    }

You must update these regions to the region you are using in AWS.


问:
Is there application Scope in spring?
I saw 'application' scope in the following blog. Is it true?

http://www.concretepage.com/spring/spring-bean-scope-example-using-scope-annotation-and-xml-for-singleton-prototype-request-session-global-session-and-application-scope-with-scoped-proxy

Because, as per my surfing, I got to know spring has only the below 5 scopes. Please correct me if I'm wrong.

Singleton

Prototype

Request

Session

Global Session

答:
application
Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

Follow the link for more details:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes

Title: Is there application Scope in spring?


问:
Post keyboard event
I'm trying to post a keyboard event to trigger a Space change.

By default you can change Spaces with the control key + the number key for the space you wish to change to, here's the code I'm using but isn't working:

```<code>int spaceToChangeTo = 3;
int keyCodeForSpace = space + 17; // keycode 18 = number 1 on the keyboard, and onwards.

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

CGEventRef spaceDownEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCodeForSpace, YES);
CGEventSetFlags(spaceDownEvent, kCGEventFlagMaskControl);

CGEventRef spaceUpEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCodeForSpace, NO);

CGEventPost(kCGAnnotatedSessionEventTap, spaceDownEvent);
CGEventPost(kCGAnnotatedSessionEventTap, spaceUpEvent);

CFRelease(spaceDownEvent);
CFRelease(spaceUpEvent);
CFRelease(source);
</code>```

答:
OK, found the solution, where posting the event the correct code is:</p>

```<code>CGEventPost(kCGHIDEventTap, spaceDownEvent);
</code>```

Title: Post keyboard event

Body:
I'm trying to post a keyboard event to trigger a Space change.

By default you can change Spaces with the control key + the number key for the space you wish to change to, here's the code I'm using but isn't working:

int spaceToChangeTo = 3;
int keyCodeForSpace = space + 17; // keycode 18 = number 1 on the keyboard, and onwards.

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

CGEventRef spaceDownEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCodeForSpace, YES);
CGEventSetFlags(spaceDownEvent, kCGEventFlagMaskControl);

CGEventRef spaceUpEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCodeForSpace, NO);

CGEventPost(kCGAnnotatedSessionEventTap, spaceDownEvent);
CGEventPost(kCGAnnotatedSessionEventTap, spaceUpEvent);

CFRelease(spaceDownEvent);
CFRelease(spaceUpEvent);
CFRelease(source);

Body:
OK, found the solution, where posting the event the correct code is:

CGEventPost(kCGHIDEventTap, spaceDownEvent);


问:
Why doesn't Javascript Dynamic HTML5 Table Not Appear on Page
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
    <meta charset="utf-8">

<script>
<!--
var product1 = 0;
var product2 = 0;
var product3 = 0;
var product4 = 0;
var product5 = 0;
var productNum = 0;
var productNumInt = 0;
var quantitySold = 0;
var quantitySoldInt = 0;

document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");
document.write("<tr><td>1</td><td>$" + product1 + "</td></tr>");
document.write("<tr><td>2</td><td>$" + product2 + "</td></tr>");
document.write("<tr><td>3</td><td>$" + product3 + "</td></tr>");
document.write("<tr><td>4</td><td>$" + product4 + "</td></tr>");
document.write("<tr><td>5</td><td>$" + product5 + "</td></tr>");
document.write("</table>");

while (true) {
  productNum = window.prompt("Please enter the product number");
  quantitySold = window.prompt("Please enter the quantity sold");
  productNumInt = parseInt(productNum);
  quantitySoldInt = parseInt(quantitySold);

  switch (productNumInt) {
    case 1:
      product1 += quantitySoldInt * 2.98;
      break;
    case 2:
      product2 += quantitySoldInt * 4.50;
      break;
    case 3:
      product3 += quantitySoldInt * 9.98;
      break;
    case 4:
      product4 += quantitySoldInt * 4.49;
      break;
    case 5:
      product5 += quantitySoldInt * 6.87;
      break;
  }
}
// -->
</script>
</head>

<body>
</body>

</html>
</code>```

答: I think you should put your script at the end of the body. Now it runs before your page appear on the screen.</p>

Body:
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.

    <!DOCTYPE html>

    <meta charset="utf-8">


问:
Drawable ID's come zero
```<code><integer-array name="ar_ex_1">
    <item>@drawable/ar_001_main</item>
    <item>@drawable/ar_001_1</item>
    <item>@drawable/ar_001_2</item>
    <item>@drawable/ar_001_3</item>
    <item>@drawable/ar_001_4</item>
    <item>@drawable/ar_001_5</item>
</integer-array>
</code>```

I have this integer array, and I load it into Java using:

```<code>int[] arr = getResources().getIntArray(R.array.ar_ex_1);
for(int i: arr) {
   Log.e("anindya", ""+i);
}
</code>```

The output is:

```<code>06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
</code>```

I was expecting integers, (the values for the drawables in R.java, but instead I get only zeroes. Is this not the way to load an array of drawables?

答: Use should use array instead of integer-array. Integer Array is An array of integers defined, it contains list of primitive integer. And array is an array of other resources, such as drawables. You can see in this

Title: Drawable ID's come zero

Body:
<integer-array name="ar_ex_1">
    <item>@drawable/ar_001_main</item>
    <item>@drawable/ar_001_1</item>
    <item>@drawable/ar_001_2</item>
    <item>@drawable/ar_001_3</item>
    <item>@drawable/ar_001_4</item>
    <item>@drawable/ar_001_5</item>
</integer-array>

I have this integer array, and I load it into Java using:

int[] arr = getResources().getIntArray(R.array.ar_ex_1);
for(int i: arr) {
   Log.e("anindya", ""+i);
}

The output is:

06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0

I was expecting integers, (the values for the drawables in R.java, but instead I get only zeroes. Is this not the way to load an array of drawables?


问:
Start, Pause and Stop a Node.js process/loop
I'm in the process of building a bot that basically fetches images based on a search query(simple string), this bot needs to run 24/7, however multiple bots must be 'spawned' for different accounts, I already have the bot done, it basically takes in a config file and starts looping, however what would be the best approach to pause and stop this process?

I have looked into Node's spawn child functions, i have looked into RxJs's scheduler, but I am not sure which is the best bet, to approach something like this. Any insight would be helpful, thank you!

答: You can run, pause and stop some function if you run it via sequential executor nsynjs. Please see this example (and corresponding .html) for how to start (via nsynjs.run), pause (via nsynWait) and stop (via ctx.stop) execution. </p>


问:
How to use WebApi ActionFilter Attribute
Here I wrote simple Actioon Filter As

```<code> public class ActionFilter:ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            Trace.WriteLine(string.Format("Action Method {0} executing at {1}",actionExecutedContext.ActionContext.ActionDescriptor, DateTime.Now.ToShortDateString()), "Web API Logs");
        }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            Trace.WriteLine(string.Format("Action Method {0} executed at {1}",actionContext.ActionDescriptor.ActionName,  DateTime.Now.ToShortDateString()));
        }
</code>```

In WebApi

```<code>[ActionFilter]
        public IHttpActionResult GetData()
        {
        }
</code>```

Here it working Before and after But im not Understanding Why this Filter Came into Picture

答:
Action Filters are basically used to execute some logic before and after of an Action execution.

Lets think about two scenerios:

If you have requirement to check if a user can access a particular Action, you can simply write the code to validate it in OnActionExecuting() function of the code.

Again if you want to modify th response of want to perform any activity after an Action is executed, you can use OnActionExecuted function filter for that.

For more information about Filters you can check following link:
Action Filters

Body:
Here I wrote simple Actioon Filter As

 public class ActionFilter:ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            Trace.WriteLine(string.Format("Action Method {0} executing at {1}",actionExecutedContext.ActionContext.ActionDescriptor, DateTime.Now.ToShortDateString()), "Web API Logs");
        }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            Trace.WriteLine(string.Format("Action Method {0} executed at {1}",actionContext.ActionDescriptor.ActionName,  DateTime.Now.ToShortDateString()));
        }

In WebApi

[ActionFilter]
        public IHttpActionResult GetData()
        {
        }

Here it working Before and after But im not Understanding Why this Filter Came into Picture