问:
How to define the AST for this boost spirit rule?
I have a more complex rule, but this one will suffice for this question (I hope). Consider the rule:

```<code>result = double_ >> *(char_ > int_);
</code>```

where result is declared in terms of a struct result in namespace ast:

```<code>qi::rule<Iterator, ast::result(), qi::space_type> result;
</code>```

Then how does ast::result have to look like?
According to the boost::spirit docs (http://www.boost.org/doc/libs/develop/libs/spirit/doc/html/spirit/abstracts/attributes/compound_attributes.html), the attribute of
char_ > int_ is tuple<char, int> or std::pair<char, int>.
So, I tried:

```<code>namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;
};

} // namespace ast
</code>```

in addition to

```<code>BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)
</code>```

But this gives me the compile error:

```<code>error: no matching function for call to 'std::pair<char, int>::pair(const char&)'
</code>```

This rule is simple, creating the AST struct that the result will be stored in should be simple too... but how?

Here is a complete test program with my attempt:

```<code> #include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;

  friend std::ostream& operator<<(std::ostream& os, result const& result);
};

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
  return os << val.first << ' ' << val.second;
}

std::ostream& operator<<(std::ostream& os, result const& result)
{
  os << result.first;
  for (auto& i : result.second)
      os << ' ' << i;
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class test_grammar : public qi::grammar<Iterator, ast::result(), qi::space_type>
{
 private:
  qi::rule<Iterator, ast::result(), qi::space_type> result;

 public:
  test_grammar() : test_grammar::base_type(result, "result_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    result = double_ >> *(char_ > int_);
  }
};

} // namespace client

int main()
{
  std::string const input{"3.4 a 5 b 6 c 7"};
  using iterator_type = std::string::const_iterator;
  using test_grammar = client::test_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  test_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::result out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}
</code>```

答:
I made the following changes:

```<code>#include <boost/fusion/tuple.hpp>

using second_type = std::vector<boost::fusion::tuple<char, int>>;

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
    return os << boost::fusion::get<0>(val) << ' ' << boost::fusion::get<1>(val);
}
</code>```

and the result compiled for me.  There are most certainly other solutions available too.

Body:
I have a more complex rule, but this one will suffice for this question (I hope). Consider the rule:

result = double_ >> *(char_ > int_);

where result is declared in terms of a struct result in namespace ast:

qi::rule<Iterator, ast::result(), qi::space_type> result;

Then how does ast::result have to look like?
According to the boost::spirit docs (http://www.boost.org/doc/libs/develop/libs/spirit/doc/html/spirit/abstracts/attributes/compound_attributes.html), the attribute of
char_ > int_ is tuple<char, int> or std::pair<char, int>.
So, I tried:

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;
};

} // namespace ast

in addition to

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

But this gives me the compile error:

error: no matching function for call to 'std::pair<char, int>::pair(const char&)'

This rule is simple, creating the AST struct that the result will be stored in should be simple too... but how?

Here is a complete test program with my attempt:

 #include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast
{

using second_type = std::vector<std::pair<char, int>>;

struct result
{
  double first;
  second_type second;

  friend std::ostream& operator<<(std::ostream& os, result const& result);
};

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
  return os << val.first << ' ' << val.second;
}

std::ostream& operator<<(std::ostream& os, result const& result)
{
  os << result.first;
  for (auto& i : result.second)
      os << ' ' << i;
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::result,
  (double, first),
  (ast::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class test_grammar : public qi::grammar<Iterator, ast::result(), qi::space_type>
{
 private:
  qi::rule<Iterator, ast::result(), qi::space_type> result;

 public:
  test_grammar() : test_grammar::base_type(result, "result_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    result = double_ >> *(char_ > int_);
  }
};

} // namespace client

int main()
{
  std::string const input{"3.4 a 5 b 6 c 7"};
  using iterator_type = std::string::const_iterator;
  using test_grammar = client::test_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  test_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::result out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}

Body:
I made the following changes:

#include <boost/fusion/tuple.hpp>

using second_type = std::vector<boost::fusion::tuple<char, int>>;

std::ostream& operator<<(std::ostream& os, second_type::value_type val)
{
    return os << boost::fusion::get<0>(val) << ' ' << boost::fusion::get<1>(val);
}

and the result compiled for me.  There are most certainly other solutions available too.


来源: stackexchange

问:
SWFUpload uppload error 500 - asp.net website
I have a asp.net website where I am using the Flash SWFUpload (http://code.google.com/p/swfupload/) upload component.

The same code is hosted on two servers - on server A I can upload images without any problems.
On server B I get Error 500 when I try to upload - no other error message.

I am unable to find what server settings are different between those two servers.
I cant find any solution on SWFUpload forum.

Any idea what could be the issue?

答:
I had a similiar problem using an apache httpd server

fixed it using an answer from SWFUpload forum.

hope it will help.

short version:

append

```<code>SecFilterEngine Off
SecFilterScanPOST Off
</code>```

to .htaccess in root.

Also I want to comment that this is less secure.

ContentLicense: CC BY-SA 2.5

Body:
I had a similiar problem using an apache httpd server

fixed it using an answer from SWFUpload forum.

hope it will help.

short version:

append

SecFilterEngine Off
SecFilterScanPOST Off

to .htaccess in root.

Also I want to comment that this is less secure.


问:
Understanding how a Sed script breaks down into individual commands
I'm new to sed, can you tell me what the following does? I can't find a complete regex in the command from below.

sed -e ':a;N;$!ba;s/>[[:space:]]*\n/>\\\n/g' nlTest1.txt > nlTest2.txt

Are we having 3 commands together?

:a;N;$!ba;s

>[[:space:]]*\n

>\\\n/g

Or I'm not intrepreting the command correctly.

答:
The partitioning of the commands is:

:a;N;$!ba, which is a common idiom for reading the entire input file into the pattern space (buffer to operate on) at once, in a loop; it is composed of 3 ;-separated commands:

label :a (defines a script location that can be jumped to)

function N (reads the next line and appends it to the pattern space)

$! ba, which branches (b) to label a, if the input line is not (!) the last ($) one.

s/>[[:space:]]*\n/>\\\n/g is a regular s function call in the form s/<regex>/<substitution-string>/; here, all occurrences of a > followed by any run of whitespace followed by a newline are replaced with just >\ and a newline.

ContentLicense: CC BY-SA 3.0


问:
Tag Helpers Cache expires-on fails Unexpectedly
Using the latest .net Core Razor Tag Helpers, I have the following usages of expires-after and expires-on in my index.cshtml file.

When I refresh the page every second, the first line (expires-after) only changes every 5 seconds as I expect.

When I refresh the page every second, the second line (expires-on) changes every second. I would expect both lines to behave the same.

```<code>expires after (working): <Cache expires-after="@TimeSpan.FromSeconds(5)">
  @DateTime.Now</Cache>

expires on (not working) <Cache expires-on="@DateTime.Now.AddSeconds(5)">
  @DateTime.Now</Cache>
</code>```

答:
You're setting a new value for "expires-on" each time the page is rendered.
It seems like the MVC framework's caching mechanism refreshes the cache each time a different value "expires-on" is set.
A small tweak of your example, as follows, gives the behaviour you were expecting:

```<code><Cache expires-on="@(new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, (int)(DateTime.Now.Second/10) * 10)).AddSeconds(10)">
  @DateTime.Now</Cache>
</code>```

(This is for a c# Razor template.)
This tweak works because the new expression for "expires-on" provides a value that stays constant except for a new value every 10 seconds. Here's the same expression in a more legible layout:

```<code>(new DateTime(DateTime.Now.Year,
  DateTime.Now.Month,
  DateTime.Now.Day,
  DateTime.Now.Hour,
  DateTime.Now.Minute,
  (int)(DateTime.Now.Second/10) * 10))
.AddSeconds(10)
</code>```

Body:
Using the latest .net Core Razor Tag Helpers, I have the following usages of expires-after and expires-on in my index.cshtml file.

When I refresh the page every second, the first line (expires-after) only changes every 5 seconds as I expect.

When I refresh the page every second, the second line (expires-on) changes every second. I would expect both lines to behave the same.

expires after (working): <Cache expires-after="@TimeSpan.FromSeconds(5)">
  @DateTime.Now</Cache>

expires on (not working) <Cache expires-on="@DateTime.Now.AddSeconds(5)">
  @DateTime.Now</Cache>

Body:
You're setting a new value for "expires-on" each time the page is rendered.
It seems like the MVC framework's caching mechanism refreshes the cache each time a different value "expires-on" is set.
A small tweak of your example, as follows, gives the behaviour you were expecting:

<Cache expires-on="@(new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, (int)(DateTime.Now.Second/10) * 10)).AddSeconds(10)">
  @DateTime.Now</Cache>

(This is for a c# Razor template.)
This tweak works because the new expression for "expires-on" provides a value that stays constant except for a new value every 10 seconds. Here's the same expression in a more legible layout:

(new DateTime(DateTime.Now.Year,
  DateTime.Now.Month,
  DateTime.Now.Day,
  DateTime.Now.Hour,
  DateTime.Now.Minute,
  (int)(DateTime.Now.Second/10) * 10))
.AddSeconds(10)


问:
To check if internet connection is available or not despite of WIFI turned on?
I am trying to build an app ,where in I first need to check if internet connection is available or not,even if it is connected to the WIFI router which does not have a internet connectivity?From sources I came to know ,in order to check this I need to ping the site for e.g.(www.google.com).Please help me with the exact snippet I need to include?
Thanks </p>

答:
this method work fine for me</p>

```<code> public final boolean isInternetOn() {
        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            // if connected with internet
            // Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

            //  Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }
</code>```

Body:
this method work fine for me

 public final boolean isInternetOn() {
        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            // if connected with internet
            // Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

            //  Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }


问:
Why does collect fail with "error: value collect is not a member of Int" on the result of reduce?
I am trying to find the line with the most no of words using apache spark/scala. I am running the program in spark-shell.

I get the correct output when I use following code:

```<code>scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)
</code>```

But I get error when I try to collect the result using following code:

```<code>scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
<console>:30: error: value collect is not a member of Int
              file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
</code>```

Why is that I get error when I use collect() action?

答:
reduce is an action that reduces a series of values of type T into a single value of type T.

reduce(f: (T, T) ⇒ T): T Reduces the elements of this RDD using the specified commutative and associative binary operator.

After reduce you have the final result (that you could have also collected for other transformations).

In your case, assign the value of reduce and check its type. It is Int.

```<code>val result = file1.
  map(line => line.split(" ").size).
  reduce((a, b) => if (a > b) a else b)
// check the type of the value from `reduce`
scala> :type result
Int
</code>```

reduce is very similar to collect as both are actions that give you a value, but collect will give you an Array[T]...

collect(): Array[T] Return an array that contains all of the elements in this RDD.

...while reduce just a single value T.

Body:
I am trying to find the line with the most no of words using apache spark/scala. I am running the program in spark-shell.

I get the correct output when I use following code:

scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)

But I get error when I try to collect the result using following code:

scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
<console>:30: error: value collect is not a member of Int
              file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()

Why is that I get error when I use collect() action?

Body:
reduce is an action that reduces a series of values of type T into a single value of type T.

reduce(f: (T, T) ⇒ T): T Reduces the elements of this RDD using the specified commutative and associative binary operator.

After reduce you have the final result (that you could have also collected for other transformations).

In your case, assign the value of reduce and check its type. It is Int.

val result = file1.
  map(line => line.split(" ").size).
  reduce((a, b) => if (a > b) a else b)
// check the type of the value from `reduce`
scala> :type result
Int

reduce is very similar to collect as both are actions that give you a value, but collect will give you an Array[T]...

collect(): Array[T] Return an array that contains all of the elements in this RDD.

...while reduce just a single value T.


问:
spotify-web-api-node - WebapiError: Unauthorized
```<code>var SpotifyWebApi = require('spotify-web-api-node');

var spotifyApi = new SpotifyWebApi({
    clientId : 'xxx',
    clientSecret : 'xxx',
    redirectUri : 'https://example.com/callback'
});

spotifyApi.getTrack('2q8eudK0r9ImgCB1XhFfxG').then(function(data) {
    console.log(data);
});
</code>```

My code worked but for 1 month I have this error.

(node:12824) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): WebapiError: Unauthorized

(node:12824)
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

答:
According to this issue you need to set an access token.

```<code>spotifyApi.setAccessToken('myAccessToken');
</code>```

Also, take a look here: https://github.com/thelinmichael/spotify-web-api-node#setting-credentials

```<code>// Set necessary parts of the credentials on the constructor
var spotifyApi = new SpotifyWebApi({
  clientId : 'myClientId',
  clientSecret : 'myClientSecret'
});

// Get an access token and 'save' it using a setter
spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    console.log('The access token is ' + data.body['access_token']);
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Something went wrong!', err);
  });

// Get tracks in a playlist
spotifyApi.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn', { 'offset' : 1, 'limit' : 5, 'fields' : 'items' })
  .then(function(data) {
    console.log('The playlist contains these tracks', data.body);
  }, function(err) {
    console.log('Something went wrong!', err);
  });
</code>```

Body:
var SpotifyWebApi = require('spotify-web-api-node');

var spotifyApi = new SpotifyWebApi({
    clientId : 'xxx',
    clientSecret : 'xxx',
    redirectUri : 'https://example.com/callback'
});

spotifyApi.getTrack('2q8eudK0r9ImgCB1XhFfxG').then(function(data) {
    console.log(data);
});

My code worked but for 1 month I have this error.

(node:12824) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): WebapiError: Unauthorized

(node:12824)
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

Body:
According to this issue you need to set an access token.

spotifyApi.setAccessToken('myAccessToken');

Also, take a look here: https://github.com/thelinmichael/spotify-web-api-node#setting-credentials

// Set necessary parts of the credentials on the constructor
var spotifyApi = new SpotifyWebApi({
  clientId : 'myClientId',
  clientSecret : 'myClientSecret'
});

// Get an access token and 'save' it using a setter
spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    console.log('The access token is ' + data.body['access_token']);
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Something went wrong!', err);
  });

// Get tracks in a playlist
spotifyApi.getPlaylistTracks('thelinmichael', '3ktAYNcRHpazJ9qecm3ptn', { 'offset' : 1, 'limit' : 5, 'fields' : 'items' })
  .then(function(data) {
    console.log('The playlist contains these tracks', data.body);
  }, function(err) {
    console.log('Something went wrong!', err);
  });


问:
Animate fontawesome Icon inside anchor tag to fly in onhover
I'm in need for a CSS/SCSS/SASS guru to help me determine what I am doing wrong with this simple animation.

Objective: What I'm trying to accomplish a simple animation in which the fontawesome icon fa-angle-right fly in from the left after the word, onHover. I figured this could be done with a display: none property and adding some transition to the parent property, but it's not animating as intended.

The caveat here is that I CANNOT change the HTML structure.

An example of what I'm trying to do; but granted this is using a different HTML structure & SVG instead of fontawesome icons

JSFiddle: https://jsfiddle.net/bwrmam9o/1/

HTML

```<code><a href="#" class="btn ripple">
     <i class="fa fa-left fa-location-arrow"></i>
     <span class="label">View Location </span>
     <i class="fa fa-right fa-angle-right fa-animate"></i>
</a>
</code>```

SCSS/SASS

```<code>.btn{
  display: inline-block;
  color: #FFF;
  background: #CB5039;
  text-decoration: none;
  font-family: Arial;
  padding: 10px 12px;
  text-transform: uppercase;
  font-size: 13px;
  font-weight: bold;
  transition: all 0.1s cubic-bezier(0.16, 0.08, 0.355, 1);
  .fa-left{
    margin-right: 5px;
  }
  .fa-right{
    margin-left: 5px;
  }
  .fa-animate{
    display: none;
    transition: all 0.1s cubic-bezier(0.16, 0.08, 0.355, 1);
  }
  &:hover{
    background: blue;
    .fa-animate{
      display: inline-block;
    }
  }
}

.ripple {
  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}
.ripple:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  background-image: radial-gradient(circle, #FFF 10%, transparent 10.01%);
  background-repeat: no-repeat;
  background-position: 50%;
  transform: scale(10, 10);
  opacity: 0;
  transition: transform .25s, opacity 1s;
}
.ripple:active:after {
  transform: scale(0, 0);
  opacity: .2;
  transition: 0s;
}
</code>```

Any help on this would be greatly appreciated!

答:
is this what you want? modify style like this .

```<code>.fa-animate{
 left: -15px;
 position:relative;
 opacity: 0;
 transition: 1s;
}
&:hover{
 background: blue;
 .fa-animate{
  left: 0;
  opacity:1;
 }
}
</code>```

full edited code here : https://jsfiddle.net/jayakrishnancn/bwrmam9o/3/

Body:
I'm in need for a CSS/SCSS/SASS guru to help me determine what I am doing wrong with this simple animation.

Objective: What I'm trying to accomplish a simple animation in which the fontawesome icon fa-angle-right fly in from the left after the word, onHover. I figured this could be done with a display: none property and adding some transition to the parent property, but it's not animating as intended.

The caveat here is that I CANNOT change the HTML structure.

An example of what I'm trying to do; but granted this is using a different HTML structure & SVG instead of fontawesome icons

JSFiddle: https://jsfiddle.net/bwrmam9o/1/

HTML

     View Location

SCSS/SASS

.btn{
  display: inline-block;
  color: #FFF;
  background: #CB5039;
  text-decoration: none;
  font-family: Arial;
  padding: 10px 12px;
  text-transform: uppercase;
  font-size: 13px;
  font-weight: bold;
  transition: all 0.1s cubic-bezier(0.16, 0.08, 0.355, 1);
  .fa-left{
    margin-right: 5px;
  }
  .fa-right{
    margin-left: 5px;
  }
  .fa-animate{
    display: none;
    transition: all 0.1s cubic-bezier(0.16, 0.08, 0.355, 1);
  }
  &:hover{
    background: blue;
    .fa-animate{
      display: inline-block;
    }
  }
}

.ripple {
  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}
.ripple:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  background-image: radial-gradient(circle, #FFF 10%, transparent 10.01%);
  background-repeat: no-repeat;
  background-position: 50%;
  transform: scale(10, 10);
  opacity: 0;
  transition: transform .25s, opacity 1s;
}
.ripple:active:after {
  transform: scale(0, 0);
  opacity: .2;
  transition: 0s;
}

Any help on this would be greatly appreciated!

Body:
is this what you want? modify style like this .

.fa-animate{
 left: -15px;
 position:relative;
 opacity: 0;
 transition: 1s;
}
&:hover{
 background: blue;
 .fa-animate{
  left: 0;
  opacity:1;
 }
}

full edited code here : https://jsfiddle.net/jayakrishnancn/bwrmam9o/3/


问:
Talend - Insert/Update versus table-file-table
I have been using insert/update to update or insert a table in mysql from sql server. The job is set up as a cronjob. The job runs every 8 hours. The number of records in the source table is around 400000. Every 8 hours around 100 records might get updated or inserted.

I run the job in such a away that at the source level, I only take the modified runs between the last run and the current run.

I have observed that just to update / insert 100 rows the time taken is 30 minutes.

However, another way was to dump all of the 400000 in a file and then truncate the destination table and insert all of those records all over again. This process is done at every job run

So, now may I know why does insert/update take so much time?

Thanks
Rathi

答:
Without knowing how your database is configured, it's hard to tell the exact reason, but I'd say the updates are slow because you don't have an index on your target table.
Try adding an index on your insert/update key column, it will speed things up.

Also, are you doing a commit after each insert ? If so, disable autocommit, and only commit on success like this : tMysqlOutput -- OnComponentOk -- tMysqlCommit.


问:
How to check if there is an item in an array that exists in another array?
I have the following React code that I want to use to disable a button:

```<code>todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)
</code>```

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

答:
You can boil it down even further to the following, assuming todo.completed returns a boolean.

Of course, replace the checkedIds with this.state.checkedIds.

const todos = [
  { id: 1, completed: true },
  { id: 2, completed: false },
  { id: 3, completed: true },
  { id: 4, completed: false }
];

const checkedIds = [1, 2, 4, 5];

const results = todos
  .filter(todo => todo.completed)
  .map(todo => checkedIds.includes(todo.id));

console.log(results);```

Body:
I have the following React code that I want to use to disable a button:

todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.


问:
How to execute SQL statements saved in a table with T-SQL
Is it possible to execute a SQL statement Stored in a Table, with T-SQL?

```<code>DECLARE @Query text
SET @Query = (Select Query FROM SCM.dbo.CustomQuery)
</code>```

The statements that are stored in the table are ad-hoc statements which could be SELECT TOP 100 * FROM ATable to more complex statements:

```<code>Select
J.JobName As Job,
JD.JobDetailJobStart AS StartDate,
JD.JobDetailJobEnd AS EndDate,
(
    SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END)
) AS NumberOfWorkingDays,
JD.JobDetailDailyTarget AS DailyTarget,
JD.JobDetailWeeklyTarget AS WeeklyTarget,
JD.JobDetailRequiredQTY AS RequiredQuantity,
(
    Select SUM(sJL.JobLabourQuantityEmployees) From JobLabour sJL
) AS NumberOfEmployees,
(
    Select
        SUM((sEM.EmployeeDesignationDefaultRate * sJL.JobLabourQuantityEmployees)*8)*(SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END))
    from EmployeeDesignation sEM
    Inner join JobLabour sJL on sJL.EmployeeDesignationID = sEM.EmployeeDesignationID
) AS FullEmployeeRate

from Job J
Inner Join JobDetail JD on JD.JobID = J.JobID
Inner Join JobLabour JL on JL.JobID = J.JobID

WHERE J.JobActive = 0
</code>```

I want to execute the @Query Variable that I declared from T-SQL. Is this possible? (I am running a MSSQL 2005 enviroment)

答: We use a much simpler approach. Store the scripts (raw sql or stored procedure calls) in a table with a column containing an identifying code for said script. Use placeholders in your script for parameters. Any scripts that are used a lot can be "keyed" in your app or web config file. If scripts need to be executed in a specific order, put an ordinal column in the table. The actual "script" can then be pulled into a c# list or array, passed to a database class library and executed accordingly. This gives you dynamic control over your SQL and allows you to make changes on the database side for said scripts without recompiling your main application. </p>

Body:
Is it possible to execute a SQL statement Stored in a Table, with T-SQL?

DECLARE @Query text
SET @Query = (Select Query FROM SCM.dbo.CustomQuery)

The statements that are stored in the table are ad-hoc statements which could be SELECT TOP 100 * FROM ATable to more complex statements:

Select
J.JobName As Job,
JD.JobDetailJobStart AS StartDate,
JD.JobDetailJobEnd AS EndDate,
(
    SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END)
) AS NumberOfWorkingDays,
JD.JobDetailDailyTarget AS DailyTarget,
JD.JobDetailWeeklyTarget AS WeeklyTarget,
JD.JobDetailRequiredQTY AS RequiredQuantity,
(
    Select SUM(sJL.JobLabourQuantityEmployees) From JobLabour sJL
) AS NumberOfEmployees,
(
    Select
        SUM((sEM.EmployeeDesignationDefaultRate * sJL.JobLabourQuantityEmployees)*8)*(SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END))
    from EmployeeDesignation sEM
    Inner join JobLabour sJL on sJL.EmployeeDesignationID = sEM.EmployeeDesignationID
) AS FullEmployeeRate

from Job J
Inner Join JobDetail JD on JD.JobID = J.JobID
Inner Join JobLabour JL on JL.JobID = J.JobID

WHERE J.JobActive = 0

I want to execute the @Query Variable that I declared from T-SQL. Is this possible? (I am running a MSSQL 2005 enviroment)


问:
Pass parameters through link_to(r) do... end
My code loops through several images. Each image is a link and what I want is to pass the same url parameter in those links.

```<code><% @render.each_slice(2) do |renders| %>
        <div class="row">
            <% renders.each do |r| %>
                <%= link_to(r) do %>
                    <div class="col-md-6" align="center" style="margin-bottom: 5em; border-radius: 5px;">
                        <%= image_tag(r.image) %>
                    </div>
                <% end %>
            <% end %>
        </div>
    <% end %>
</code>```

I have tried link_to(r, :link => 'portafolio') in a lot of ways.

routes.rb is like this

```<code>Rails.application.routes.draw do
# For details on the DSL available within this file, see    http://guides.rubyonrails.org/routing.html
root 'pages#main'
get 'index/' => 'pages#index'
get 'index/see' => 'pages#see'
get 'index/see/:id' => 'pages#show', as: :render
end
</code>```

答:
In order to pass a block on a link_to helper you must specify the path, you're just passing r, but what's that value? what does it print?

You could try specifying the path, and inside as params the r value:

```<code><%= link_to some_path(parameter: value_for_r) do %>
  <!-- The content wrapped in the link_to -->
<% end %>
</code>```

Body:
My code loops through several images. Each image is a link and what I want is to pass the same url parameter in those links.

<% @render.each_slice(2) do |renders| %>

            <% renders.each do |r| %>
                <%= link_to(r) do %>

                        <%= image_tag(r.image) %>

                <% end %>
            <% end %>

    <% end %>

I have tried link_to(r, :link => 'portafolio') in a lot of ways.

routes.rb is like this

Rails.application.routes.draw do
# For details on the DSL available within this file, see    http://guides.rubyonrails.org/routing.html
root 'pages#main'
get 'index/' => 'pages#index'
get 'index/see' => 'pages#see'
get 'index/see/:id' => 'pages#show', as: :render
end

Body:
In order to pass a block on a link_to helper you must specify the path, you're just passing r, but what's that value? what does it print?

You could try specifying the path, and inside as params the r value:

<%= link_to some_path(parameter: value_for_r) do %>
  <!-- The content wrapped in the link_to -->
<% end %>


问:
JAXB anyType fails to cast
The following code is resulting in a cast exception and I'm not sure why. Objects in ParameterValueList should be eagerly unmarshalled to the JAXB object ParameterValueStruct, but it's not. Everything was generated directly from the soap encoding and cwmp schema files.

Does anyone have any suggestions?

```<code>public static void main(String[] args) throws JAXBException, FileNotFoundException
{
    JAXBContext c = JAXBContext.newInstance("org.dslforum.cwmp_1_1");

    Unmarshaller u = c.createUnmarshaller();
    Inform inform = (Inform) u.unmarshal(new FileInputStream("test.xml"));

    List<Object> list = inform.getParameterList().getAny();
    System.out.println(list); // prints [[ParameterValueStruct: null], ...

    for (Object o : list) {
        ParameterValueStruct pv = (ParameterValueStruct)o; // exception here
        System.out.println(pv.getName());
    }
}
</code>```

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to org.dslforum.cwmp_1_1.ParameterValueStruct
      at Test.main(Test.java:26)

I have this class which was generated from http://schemas.xmlsoap.org/soap/encoding/ using Java's xjc tool:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Array", propOrder = {
    "any"
})
@XmlSeeAlso({
    ParameterValueList.class,
})
public class Array {

    @XmlAnyElement(lax = true)
    protected List<Object> any;
    @XmlAttribute(name = "id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected java.lang.String id;
    @XmlAttribute(name = "href")
    @XmlSchemaType(name = "anyURI")
    protected java.lang.String href;
    @XmlAttribute(name = "arrayType", namespace = "http://schemas.xmlsoap.org/soap/encoding/")
    protected java.lang.String arrayType;
    @XmlAttribute(name = "offset", namespace = "http://schemas.xmlsoap.org/soap/encoding/")
    protected java.lang.String offset;
    @XmlAnyAttribute
    private Map<QName, java.lang.String> otherAttributes = new HashMap<QName, java.lang.String>();

    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }
    ....
}
</code>```

I also have these 2 classes which were also generated via the same tool, but from https://www.broadband-forum.org/cwmp/cwmp-1-1.xsd:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueList")
public class ParameterValueList
    extends Array
{
}
</code>```

Second file:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueStruct", propOrder = {
    "name",
    "value"
})
public class ParameterValueStruct {
    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Value", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected Object value;
    ...
}
</code>```

And here is my test.xml file:

```<code><?xml version="1.0"?>
<cwmp:Inform xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:cwmp="urn:dslforum-org:cwmp-1-1" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ParameterList soap-enc:arrayType="cwmp:ParameterValueStruct[3]">
    <ParameterValueStruct>
      <Name>Device.DHCPv4.ClientNumberOfEntries</Name>
      <Value xsi:type="xsd:unsignedInt">0</Value>
    </ParameterValueStruct>
    <ParameterValueStruct>
      <Name>Device.DNS.Client.ServerNumberOfEntries</Name>
      <Value xsi:type="xsd:unsignedInt">1</Value>
    </ParameterValueStruct>
    <ParameterValueStruct>
      <Name>Device.DeviceInfo.AdditionalSoftwareVersion</Name>
      <Value xsi:type="xsd:string">DM: 532,SK: 2.6.33.9-rt31,SF: 251X 137.0,BK: 10</Value>
    </ParameterValueStruct>
  </ParameterList>
</cwmp:Inform>
</code>```

答:
You just have to add @XmlRootElement(name="ParameterValueStruct",namespace="") in front of ParameterValueStruct

Here you need explicit namespace="" becauce of the  package-info.java

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "urn:dslforum-org:cwmp-1-1")
package org.dslforum.cwmp_1_1;
</code>```

The correct class should look like this:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueStruct", propOrder = {
    "name",
    "value"
})
@XmlRootElement(name="ParameterValueStruct",namespace="")
public class ParameterValueStruct {
    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Value", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected Object value;
    ...
}
</code>```

PS: See this http://blog.bdoughan.com/2012/12/jaxbs-xmlanyelementlaxtrue-explained.html for a better JAXB-tutorial about @XmlAnyElement(lax=true)

Title: JAXB anyType fails to cast

Body:
The following code is resulting in a cast exception and I'm not sure why. Objects in ParameterValueList should be eagerly unmarshalled to the JAXB object ParameterValueStruct, but it's not. Everything was generated directly from the soap encoding and cwmp schema files.

Does anyone have any suggestions?

public static void main(String[] args) throws JAXBException, FileNotFoundException
{
    JAXBContext c = JAXBContext.newInstance("org.dslforum.cwmp_1_1");

    Unmarshaller u = c.createUnmarshaller();
    Inform inform = (Inform) u.unmarshal(new FileInputStream("test.xml"));

    List<Object> list = inform.getParameterList().getAny();
    System.out.println(list); // prints [[ParameterValueStruct: null], ...

    for (Object o : list) {
        ParameterValueStruct pv = (ParameterValueStruct)o; // exception here
        System.out.println(pv.getName());
    }
}

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to org.dslforum.cwmp_1_1.ParameterValueStruct
      at Test.main(Test.java:26)

I have this class which was generated from http://schemas.xmlsoap.org/soap/encoding/ using Java's xjc tool:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Array", propOrder = {
    "any"
})
@XmlSeeAlso({
    ParameterValueList.class,
})
public class Array {

    @XmlAnyElement(lax = true)
    protected List<Object> any;
    @XmlAttribute(name = "id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected java.lang.String id;
    @XmlAttribute(name = "href")
    @XmlSchemaType(name = "anyURI")
    protected java.lang.String href;
    @XmlAttribute(name = "arrayType", namespace = "http://schemas.xmlsoap.org/soap/encoding/")
    protected java.lang.String arrayType;
    @XmlAttribute(name = "offset", namespace = "http://schemas.xmlsoap.org/soap/encoding/")
    protected java.lang.String offset;
    @XmlAnyAttribute
    private Map<QName, java.lang.String> otherAttributes = new HashMap<QName, java.lang.String>();

    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }
    ....
}

I also have these 2 classes which were also generated via the same tool, but from https://www.broadband-forum.org/cwmp/cwmp-1-1.xsd:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueList")
public class ParameterValueList
    extends Array
{
}

Second file:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueStruct", propOrder = {
    "name",
    "value"
})
public class ParameterValueStruct {
    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Value", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected Object value;
    ...
}

And here is my test.xml file:

<?xml version="1.0"?>
<cwmp:Inform xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:cwmp="urn:dslforum-org:cwmp-1-1" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ParameterList soap-enc:arrayType="cwmp:ParameterValueStruct[3]">
    <ParameterValueStruct>
      <Name>Device.DHCPv4.ClientNumberOfEntries</Name>
      <Value xsi:type="xsd:unsignedInt">0</Value>
    </ParameterValueStruct>
    <ParameterValueStruct>
      <Name>Device.DNS.Client.ServerNumberOfEntries</Name>
      <Value xsi:type="xsd:unsignedInt">1</Value>
    </ParameterValueStruct>
    <ParameterValueStruct>
      <Name>Device.DeviceInfo.AdditionalSoftwareVersion</Name>
      <Value xsi:type="xsd:string">DM: 532,SK: 2.6.33.9-rt31,SF: 251X 137.0,BK: 10</Value>
    </ParameterValueStruct>
  </ParameterList>
</cwmp:Inform>

Body:
You just have to add @XmlRootElement(name="ParameterValueStruct",namespace="") in front of ParameterValueStruct

Here you need explicit namespace="" becauce of the  package-info.java

@javax.xml.bind.annotation.XmlSchema(namespace = "urn:dslforum-org:cwmp-1-1")
package org.dslforum.cwmp_1_1;

The correct class should look like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParameterValueStruct", propOrder = {
    "name",
    "value"
})
@XmlRootElement(name="ParameterValueStruct",namespace="")
public class ParameterValueStruct {
    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Value", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected Object value;
    ...
}

PS: See this http://blog.bdoughan.com/2012/12/jaxbs-xmlanyelementlaxtrue-explained.html for a better JAXB-tutorial about @XmlAnyElement(lax=true)


问:
Static allocation of opaque data types
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

```<code>// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}
</code>```

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

```<code>void create_handle(handle_t *handle);
</code>```

And then the caller could create the handle this way:

```<code>// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}
</code>```

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

答:
One solution if to create a static pool of struct handle_t objects, and provide then as neceessary.  There are many ways to achieve that, but a simple illustrative example follows:

```<code>// In file module.c
struct handle_t
{
    int foo;
    void* something;
    int another_implementation_detail;

    int in_use ;
} ;

static struct handle_t handle_pool[MAX_HANDLES] ;

handle_t* create_handle()
{
    int h ;
    handle_t* handle = 0 ;
    for( h = 0; handle == 0 && h < MAX_HANDLES; h++ )
    {
        if( handle_pool[h].in_use == 0 )
        {
            handle = &handle_pool[h] ;
        }
    }

    // other initialization
    return handle;
}

void release_handle( handle_t* handle )
{
    handle->in_use = 0 ;
}
</code>```

There are faster faster ways of finding an unused handle, you could for example keep a static index that increments each time a handle is allocated and 'wraps-around' when it reaches MAX_HANDLES; this would be faster for the typical situation where several handles are allocated before releasing any one.  For a small number of handles however, this brute-force search is probably adequate.

Of course the handle itself need no longer be a pointer but could be a simple index into the hidden pool.  This would enhance data hiding and protection of the pool from external access.

So the header would have:

```<code>typedef int handle_t ;
</code>```

and the code would change as follows:

```<code>// In file module.c
struct handle_s
{
    int foo;
    void* something;
    int another_implementation_detail;

    int in_use ;
} ;

static struct handle_s handle_pool[MAX_HANDLES] ;

handle_t create_handle()
{
    int h ;
    handle_t handle = -1 ;
    for( h = 0; handle != -1 && h < MAX_HANDLES; h++ )
    {
        if( handle_pool[h].in_use == 0 )
        {
            handle = h ;
        }
    }

    // other initialization
    return handle;
}

void release_handle( handle_t handle )
{
    handle_pool[handle].in_use = 0 ;
}
</code>```

Because the handle returned is no longer a pointer to the internal data, and inquisitive or malicious user cannnot gain access to it through the handle.

Note that you may need to add some thread-safety mechanisms if you are getting handles in multiple threads.

Title: Static allocation of opaque data types

Body:
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

void create_handle(handle_t *handle);

And then the caller could create the handle this way:

// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

Body:
One solution if to create a static pool of struct handle_t objects, and provide then as neceessary.  There are many ways to achieve that, but a simple illustrative example follows:

// In file module.c
struct handle_t
{
    int foo;
    void* something;
    int another_implementation_detail;

    int in_use ;
} ;

static struct handle_t handle_pool[MAX_HANDLES] ;

handle_t* create_handle()
{
    int h ;
    handle_t* handle = 0 ;
    for( h = 0; handle == 0 && h < MAX_HANDLES; h++ )
    {
        if( handle_pool[h].in_use == 0 )
        {
            handle = &handle_pool[h] ;
        }
    }

    // other initialization
    return handle;
}

void release_handle( handle_t* handle )
{
    handle->in_use = 0 ;
}

There are faster faster ways of finding an unused handle, you could for example keep a static index that increments each time a handle is allocated and 'wraps-around' when it reaches MAX_HANDLES; this would be faster for the typical situation where several handles are allocated before releasing any one.  For a small number of handles however, this brute-force search is probably adequate.

Of course the handle itself need no longer be a pointer but could be a simple index into the hidden pool.  This would enhance data hiding and protection of the pool from external access.

So the header would have:

typedef int handle_t ;

and the code would change as follows:

// In file module.c
struct handle_s
{
    int foo;
    void* something;
    int another_implementation_detail;

    int in_use ;
} ;

static struct handle_s handle_pool[MAX_HANDLES] ;

handle_t create_handle()
{
    int h ;
    handle_t handle = -1 ;
    for( h = 0; handle != -1 && h < MAX_HANDLES; h++ )
    {
        if( handle_pool[h].in_use == 0 )
        {
            handle = h ;
        }
    }

    // other initialization
    return handle;
}

void release_handle( handle_t handle )
{
    handle_pool[handle].in_use = 0 ;
}

Because the handle returned is no longer a pointer to the internal data, and inquisitive or malicious user cannnot gain access to it through the handle.

Note that you may need to add some thread-safety mechanisms if you are getting handles in multiple threads.


问:
filter object becomes empty after iteration?
I'm learning how to use the filter function.

This is the code I've written:

```<code>people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

people2 = filter(lambda x: "height" in x, people)
</code>```

As you can see what I'm trying to do is to remove all the dictionaries that don't contain the 'height' key.

The code works properly, in fact if I do:

```<code>print(list(people2))
</code>```

I get:

```<code>[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}]
</code>```

The problem is that if I do it twice:

```<code>print(list(people2))
print(list(people2))
</code>```

the second time, I get an empty list.

Can you explain me why?

答:
This is a classic python3 doh!.

A filter is a special iterable object you can iterate over. However, much like a generator, you can iterate over it only once. So, by calling list(people2), you are iterating over each element of the filter object to generate the list. At this point, you've reached the end of the iterable and nothing more to return.

So, when you call list(people2) again, you get an empty list.

Demo:

```<code>>>> l = range(10)
>>> k = filter(lambda x: x > 5, l)
>>> list(k)
[6, 7, 8, 9]
>>> list(k)
[]
</code>```

I should mention that with python2, filter returns a list, so you don't run into this issue. The problem arises when you bring py3's lazy evaluation into the picture.

ContentLicense: CC BY-SA 4.0

Body:
I'm learning how to use the filter function.

This is the code I've written:

people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

people2 = filter(lambda x: "height" in x, people)

As you can see what I'm trying to do is to remove all the dictionaries that don't contain the 'height' key.

The code works properly, in fact if I do:

print(list(people2))

I get:

[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}]

The problem is that if I do it twice:

print(list(people2))
print(list(people2))

the second time, I get an empty list.

Can you explain me why?

Body:
This is a classic python3 doh!.

A filter is a special iterable object you can iterate over. However, much like a generator, you can iterate over it only once. So, by calling list(people2), you are iterating over each element of the filter object to generate the list. At this point, you've reached the end of the iterable and nothing more to return.

So, when you call list(people2) again, you get an empty list.

Demo:

>>> l = range(10)
>>> k = filter(lambda x: x > 5, l)
>>> list(k)
[6, 7, 8, 9]
>>> list(k)
[]

I should mention that with python2, filter returns a list, so you don't run into this issue. The problem arises when you bring py3's lazy evaluation into the picture.


问:
Streaming mp3 in Xamarin Android MediaManager not working
I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager

I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).

Code snippet:

```<code>clickButton.Click += (sender, args) =>
{
    ClickButtonEvent();
};

private static async void ClickButtonEvent()
{
    await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}
</code>```

I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:

Am I missing something ?

Or is the library broken ?

答:
I ran into this using Android Emulator on Hyper-v.  It turns out that the network is set to internal. So the http://www.montemagno.com/sample.mp3 could not be found.  My workaround:

Hyper-v -> Virtual Switch Manager, add an external network.

Hyper-v -> Virtual Machines->Settings, add new hardware->Network adapter and set to external network.

"Visual Studio Emulator for Android" desktop app, launch phone vm,

in Visual Studio, deploy and run app.

Sound should work from external source now.

Body:
I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager

I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).

Code snippet:

clickButton.Click += (sender, args) =>
{
    ClickButtonEvent();
};

private static async void ClickButtonEvent()
{
    await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}

I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:

Am I missing something ?

Or is the library broken ?


问:
Autocompletion/Intellisense for React-native styles
What's the best way to  have auto completion (intellisense)  when defining styles?  Using the example below, it will be nice to have intellisense on available styles for titleStyles.</p>

```<code>const styles = {
    titleStyles: {
    fontSize: 18,
    paddingLeft: 15
}};
</code>```

答: Use ATOM with Nuclide that is developed by facebook same origin of react-native FacebookNuclide </p>

Body:
What's the best way to  have auto completion (intellisense)  when defining styles?  Using the example below, it will be nice to have intellisense on available styles for titleStyles.

const styles = {
    titleStyles: {
    fontSize: 18,
    paddingLeft: 15
}};


问:
How to lengthen the allowed text in the scroll effect?

This is a page from my website. http://teleportcorp.com/management.html Notice how the text gets cut off and the scrolling animation resets. Can someone help me identify the css parameter that would allow me to add alrger chunks of text like this one without it getting cut off?

Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content. It's also called placeholder (or filler) text. It's a convenient tool for mock-ups. It helps to outline the visual elements of a document or presentation, eg typography, font, or layout. Lorem ipsum is mostly a part of a Latin text by the classical author and philosopher Cicero. Its words and letters have been changed by addition or removal, so to deliberately render its content nonsensical; it's not genuine, correct, or comprehensible Latin anymore. While lorem ipsum's still resembles classical Latin, it actually has no meaning whatsoever. As Cicero's text doesn't contain the letters K, W, or Z, alien to latin, these, and others are often inserted randomly to mimic the typographic appearence of European languages, as are digraphs not to be found in the original.

I'm not sure what the css Parameter is to do this.

Here is the code. You can copy and paste the above chunk between the

 Tags. Thank you.

https://codepen.io/jonathansampson/pen/rqemL

答:
It is called marquee.

they used css @keyframes to simulate this effect.

```<code>.marquee {
top: 6em;
position: relative;
box-sizing: border-box;
animation: marquee 15s linear infinite;
}

@keyframes marquee
0% {
top: 8em;
}

100% {
top: -11em;
}
</code>```

for better understanding it's better to use below code on your @keyframes:

```<code>@keyframes marquee {
0%   { transform: translatey(100%);}
100% { transform: translatey(-100%);}
}
</code>```

check some examples here:
Css Marquee

Body:
It is called marquee.

they used css @keyframes to simulate this effect.

.marquee {
top: 6em;
position: relative;
box-sizing: border-box;
animation: marquee 15s linear infinite;
}

@keyframes marquee
0% {
top: 8em;
}

100% {
top: -11em;
}

for better understanding it's better to use below code on your @keyframes:

@keyframes marquee {
0%   { transform: translatey(100%);}
100% { transform: translatey(-100%);}
}

check some examples here:
Css Marquee


问:
Angular http post request - No 'Access-Control-Allow-Origin' header is present on the requested resource
I am trying to send data to servlet using angular http post,

```<code>var httpPostData = function (postparameters,postData){

     var headers = {
                'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS',
                'Accept': 'application/json'
            };
  return $http ({

    method  : 'POST',
    url     : 'http://localhost:8080/json/jasoncontroller',
    params  : postparameters,
    headers: headers,
    data    : postData
   }).success (function (responseData){
         return responseData.data;
   })
}
</code>```

But i am keep on getting error that No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I did have set following headers on my servlet

```<code>    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.addHeader("Access-Control-Max-Age", "3600");
    response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
</code>```

if i remove data from http post it works fine, but no luck with data.

答:
Actually what happens is in some frameworks two calls are made,

OPTIONS which checks what methods are available,

And then there is the actual call.

OPTIONS require just empty answer 200 OK

```<code>if(request.methord == 'OPTIONS'){
  res.send(200);
  } else {
   next();
  }
</code>```

You can also install this chrome extension to enable cors, that is the easy way out !

Body:
I am trying to send data to servlet using angular http post,

var httpPostData = function (postparameters,postData){

     var headers = {
                'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS',
                'Accept': 'application/json'
            };
  return $http ({

    method  : 'POST',
    url     : 'http://localhost:8080/json/jasoncontroller',
    params  : postparameters,
    headers: headers,
    data    : postData
   }).success (function (responseData){
         return responseData.data;
   })
}

But i am keep on getting error that No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I did have set following headers on my servlet

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.addHeader("Access-Control-Max-Age", "3600");
    response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

if i remove data from http post it works fine, but no luck with data.

Body:
Actually what happens is in some frameworks two calls are made,

OPTIONS which checks what methods are available,

And then there is the actual call.

OPTIONS require just empty answer 200 OK

if(request.methord == 'OPTIONS'){
  res.send(200);
  } else {
   next();
  }

You can also install this chrome extension to enable cors, that is the easy way out !


问:
Does catching and rethrowing the exact same exception mean anything?
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}
</code>```

Contrast this to:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}
</code>```

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.

答:
This is a violation of a basic rule:

The code should catch only the exceptions that it knows how to handle.

Oracle's guidelines suggests that each time you throw an exception, you should supply something useful for the code that catches your exception (see page 3 of Effective Java Exceptions). Catching an exception simply to re-throw it serves no practical purpose, because there is no additional information added to it for the code above it in the invocation chain, and no information extracted by the method itself.

Body:
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}

Contrast this to:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答: You could also just pipe the output of your prorgam to the tee(1) command.

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Adam Rosenfield


问:
Why can't I copy values from an editable textbox?
I have a GUI where some values are displayed in an editable textbox. For some reason I cannot copy those values with the mouse. I can select the text, but no drop-down menu appears when I right-click on the selected text. I have been looking all over the place. What am I missing? </p>

答:
Did you just want to make the editable textbox 'Enable'?

set(handles.editbox1,'Enable','on');

(assuming that you have the 'handle' to that GUI object.)

This should make the edit box editable.


问:
R - Finding common entries in columns from two separate tables
I am very new to R and apologize in advance if this question is too remedial.  I have downloaded two tables from an online database and would like to identify common (and unique) entries from two columns. I would like to compare the "Genome" column from Table "HPMT" with the "Specie" column from table "TS_COG". My code is below:

Import tables and identify columns:

```<code>HMPT=read.table("HMPtable.csv", header = TRUE, sep = ",", fill=TRUE)
GL=HMPT$Genome
TS=read.table("TS_COG.csv", header = TRUE, sep = ",", fill =TRUE )
SPL=TS$Specie
</code>```

Identify common entries between two columns:

```<code>Same=intersect(GL, SPL)
Same
</code>```

I have gone through the list generated by >Same and it appears to be too short.  I manually went through the two columns and found common entries which are not included in >Same.  There must be something wrong with my formatting or importing of the tables. Thank you in advance.

PS

答:
Assign same names for the specific columns of both the data frame

HMPT$name <- HMPT$Genome
TS$name <- TS$Specie

This will list all the common entries in both the columns

```<code>common <- merge(HMPT, TS, by="name")
</code>```

Body:
I am very new to R and apologize in advance if this question is too remedial.  I have downloaded two tables from an online database and would like to identify common (and unique) entries from two columns. I would like to compare the "Genome" column from Table "HPMT" with the "Specie" column from table "TS_COG". My code is below:

Import tables and identify columns:

HMPT=read.table("HMPtable.csv", header = TRUE, sep = ",", fill=TRUE)
GL=HMPT$Genome
TS=read.table("TS_COG.csv", header = TRUE, sep = ",", fill =TRUE )
SPL=TS$Specie

Identify common entries between two columns:

Same=intersect(GL, SPL)
Same

I have gone through the list generated by >Same and it appears to be too short.  I manually went through the two columns and found common entries which are not included in >Same.  There must be something wrong with my formatting or importing of the tables. Thank you in advance.

PS

Body:
Assign same names for the specific columns of both the data frame

HMPT$name <- HMPT$Genome
TS$name <- TS$Specie

This will list all the common entries in both the columns

common <- merge(HMPT, TS, by="name")


问:
Get the inner HTML of a element in lxml
I am trying to get the HTML content of child node with lxml and xpath in Python. As shown in code below, I want to find the html content of the each of product nodes. Does it have any methods like product.html?</p>

```<code>productGrids = tree.xpath("//div[@class='name']/parent::*")
for product in productGrids:
    print #html content of product
</code>```

答:
After right clicking (copy, copy xpath) on the specific field you want (in chrome's inspector), you might get something like this:

```<code>//*[@id="specialID"]/div[12]/div[2]/h4/text()[1]
</code>```

If you wanted that text element for each "specialID"

```<code>//*[@id="specialID"]/div/div[2]/h4/text()[1]
</code>```

You could select another field and it'll interleave the results

```<code>//*[@id="specialID"]/div/div[2]/h4/text()[1] | //*[@id="specialID"]/div/some/weird/path[95]
</code>```

Example could be improved, but it illustrates the point:

```<code>//*[@id="mw-content-text"]/div/ul[1]/li[11]/text()
</code>```

```<code>from lxml import html
import requests
page = requests.get('https://en.wikipedia.org/wiki/Web_scraping')
tree = html.fromstring(page.content)
data = tree.xpath('//*[@id="mw-content-text"]/div/ul[1]/li/a/text() | //*[@id="mw-content-text"]/div/ul[1]/li/text()[1]')
print(len(data))
for i in range(len(data)):
    print(data[i])
</code>```

Title: Get the inner HTML of a element in lxml

Body:
I am trying to get the HTML content of child node with lxml and xpath in Python. As shown in code below, I want to find the html content of the each of product nodes. Does it have any methods like product.html?

productGrids = tree.xpath("//div[@class='name']/parent::*")
for product in productGrids:
    print #html content of product

Body:
After right clicking (copy, copy xpath) on the specific field you want (in chrome's inspector), you might get something like this:

//*[@id="specialID"]/div[12]/div[2]/h4/text()[1]

If you wanted that text element for each "specialID"

//*[@id="specialID"]/div/div[2]/h4/text()[1]

You could select another field and it'll interleave the results

//*[@id="specialID"]/div/div[2]/h4/text()[1] | //*[@id="specialID"]/div/some/weird/path[95]

Example could be improved, but it illustrates the point:

//*[@id="mw-content-text"]/div/ul[1]/li[11]/text()

from lxml import html
import requests
page = requests.get('https://en.wikipedia.org/wiki/Web_scraping')
tree = html.fromstring(page.content)
data = tree.xpath('//*[@id="mw-content-text"]/div/ul[1]/li/a/text() | //*[@id="mw-content-text"]/div/ul[1]/li/text()[1]')
print(len(data))
for i in range(len(data)):
    print(data[i])


问:
How to get last_activity in Codeigniter 3?
My sessions in Codeigniter are timing out in less time than I specified in the "config/constants.php" file. I set that constant to 3600 seconds (one hour) but sometimes I get kicked out in 5 or 10 minutes. This happens in regular MVC calls, no ajax involved.

I'm trying to access the last_activity value in the CI session, but this is what the CI documentation currently states: "last_activity: Depends on the storage, no straightforward way. Sorry!"

So how can I access that value? Any ideas?

Here's some additional info:

```
    `$config['sess_driver'] = 'files';
    $config['sess_cookie_name'] = 'ci_session';
    $config['sess_expiration'] = EXPIRE_SESSION;
    $config['sess_save_path'] = sys_get_temp_dir();
    $config['sess_match_ip'] = FALSE;
    $config['sess_time_to_update'] = 86400;
    $config['sess_regenerate_destroy'] = FALSE;'
```

答:
If you're using the default session handling scheme, the last activity is the timestamp "column", or whatever it looks like in the session file. Should update every time you refresh a page. It may not update when you do something like access a modal or manipulate the page via AJAX, I haven't checked.

Here's what it looks like from the manual as a database insert:

```<code>CREATE TABLE IF NOT EXISTS `ci_sessions` (
        `id` varchar(128) NOT NULL,
        `ip_address` varchar(45) NOT NULL,
        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
        `data` blob NOT NULL,
        KEY `ci_sessions_timestamp` (`timestamp`)
);
</code>```

Body:
My sessions in Codeigniter are timing out in less time than I specified in the "config/constants.php" file. I set that constant to 3600 seconds (one hour) but sometimes I get kicked out in 5 or 10 minutes. This happens in regular MVC calls, no ajax involved.

I'm trying to access the last_activity value in the CI session, but this is what the CI documentation currently states: "last_activity: Depends on the storage, no straightforward way. Sorry!"

So how can I access that value? Any ideas?

Here's some additional info:

    `$config['sess_driver'] = 'files';
    $config['sess_cookie_name'] = 'ci_session';
    $config['sess_expiration'] = EXPIRE_SESSION;
    $config['sess_save_path'] = sys_get_temp_dir();
    $config['sess_match_ip'] = FALSE;
    $config['sess_time_to_update'] = 86400;
    $config['sess_regenerate_destroy'] = FALSE;'

Body:
If you're using the default session handling scheme, the last activity is the timestamp "column", or whatever it looks like in the session file. Should update every time you refresh a page. It may not update when you do something like access a modal or manipulate the page via AJAX, I haven't checked.

Here's what it looks like from the manual as a database insert:

CREATE TABLE IF NOT EXISTS `ci_sessions` (
        `id` varchar(128) NOT NULL,
        `ip_address` varchar(45) NOT NULL,
        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
        `data` blob NOT NULL,
        KEY `ci_sessions_timestamp` (`timestamp`)
);


答:
It's because what filter really turns is an iterator.  This iterator doesn't really do anything until you start to use it's results, in this case when you cast it to a list.  people2 is this thing that's ready to filter the list of people, then when list is called on it, it iterates through the list of people and delivers the filtered result.  Now that iterator is done, there's nothing left for it to iterate over, so when you call list on it a second time, there's nothing there.

Read this for some more details - Lazy evaluation python

Title: filter object becomes empty after iteration?


问:
PowerShell and Google Calendar - 400 Error when creating event
so this'll be the first time posting on the Google Dev Forum, fingers crossed I can get this resolved as I am pulling my hair out!

I have the following script in PowerShell. I have sorted the OAuth2 and I am able to hit my Calendar API and see the hits in the dashboard. So, authentication is fine. I used the API Explorer to get a rough idea of what I would need to send in order to create a new Calendar event, but in doing so I get a 400 error.

Here's the section I am running:

```<code>$requestUri = "https://www.googleapis.com/calendar/v3/calendars/mysite@blah.com/events?"

$body=@{
end='dateTime:2017-06-07T08:30:00+01:00'
start='dateTime:2017-06-07T08:00:00+01:00'
}

$json = $body | ConvertTo-Json

$header=@{Authorization = "Bearer $($tokens.access_token)"}

Invoke-RestMethod -Headers $header -Uri $requestUri -Method POST -Body
$json -ContentType 'application\json' -TransferEncoding gzip
</code>```

Here is the error I receive:

```<code> Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
</code>```

$json is formed like this:

```<code>{
    "end":  "dateTime:2017-06-07T08:30:00+01:00",
    "start":  "dateTime:2017-06-07T08:00:00+01:00"
}
</code>```

I can remove transferEncoding and I get the same error.

As always, any help would be great :)

thanks

答:
Moving my comment to an answer, the -ContentType looks weird with a backslash in it, and maybe it should be a forward slash, e.g.

```<code>$json -ContentType 'application/json'
</code>```

Body:
so this'll be the first time posting on the Google Dev Forum, fingers crossed I can get this resolved as I am pulling my hair out!

I have the following script in PowerShell. I have sorted the OAuth2 and I am able to hit my Calendar API and see the hits in the dashboard. So, authentication is fine. I used the API Explorer to get a rough idea of what I would need to send in order to create a new Calendar event, but in doing so I get a 400 error.

Here's the section I am running:

$requestUri = "https://www.googleapis.com/calendar/v3/calendars/mysite@blah.com/events?"

$body=@{
end='dateTime:2017-06-07T08:30:00+01:00'
start='dateTime:2017-06-07T08:00:00+01:00'
}

$json = $body | ConvertTo-Json

$header=@{Authorization = "Bearer $($tokens.access_token)"}

Invoke-RestMethod -Headers $header -Uri $requestUri -Method POST -Body
$json -ContentType 'application\json' -TransferEncoding gzip

Here is the error I receive:

 Invoke-RestMethod : The remote server returned an error: (400) Bad Request.

$json is formed like this:

{
    "end":  "dateTime:2017-06-07T08:30:00+01:00",
    "start":  "dateTime:2017-06-07T08:00:00+01:00"
}

I can remove transferEncoding and I get the same error.

As always, any help would be great :)

thanks

Body:
Moving my comment to an answer, the -ContentType looks weird with a backslash in it, and maybe it should be a forward slash, e.g.

$json -ContentType 'application/json'


问:
matplotlib can't find cycler
I'm trying a test code and it can't find cycler
this code:

```<code>import matplotlib.pyplot as plt
plt.plot([1,2,10,4])
plt.ylabel("some numbers")
plt.show()
</code>```

returns the error:

```<code>ImportError: No module named cycler
</code>```

答:
matplotlib relies on cycler. with some versions of matplotlib it was not listed as prerequisite. possible duplicate of ImportError: No module named cycler

try installing cycler, with the same method that you used for matplotlib ideally

```<code>sudo apt-get python-cycler
</code>```

for instance

Title: matplotlib can't find cycler

Body:
I'm trying a test code and it can't find cycler
this code:

import matplotlib.pyplot as plt
plt.plot([1,2,10,4])
plt.ylabel("some numbers")
plt.show()

returns the error:

ImportError: No module named cycler

Body:
matplotlib relies on cycler. with some versions of matplotlib it was not listed as prerequisite. possible duplicate of ImportError: No module named cycler

try installing cycler, with the same method that you used for matplotlib ideally

sudo apt-get python-cycler

for instance


问:
angular2, how to return object who have the max value of an attribute in an array of objects
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];```
</div>
</div>
</p>

<p>this is what i tried in typescript </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}</code>```

答:
I would suggest using Lodash. They have a maxBy function that parses an array of objects and returns the one with a max value by property.

Example from their site.

```<code>var objects = [{ 'n': 1 }, { 'n': 2 }];

_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }

// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }
</code>```

Body:
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];

this is what i tried in typescript

export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}

Body:
I would suggest using Lodash. They have a maxBy function that parses an array of objects and returns the one with a max value by property.

Example from their site.

var objects = [{ 'n': 1 }, { 'n': 2 }];

_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }

// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }


问:
Display single row from dataset across multiple fields in SSRS report
I'm trying to create a SSRS report that displays data as shown below--each block of 3 is a single row in the dataset.  I've tried using the tablix and matrix controls to achieve this display but so far have been unsuccessful. I'd greatly appreciate advice on how to design this.

Referral Id: 1

| Disposition Id: 1 | Created By: John Doe | Created Date: 05-05-2016 |

| Cause Number: 84 | County: King | Prosecutor: Mary Smith |

| Restitution Requested: $1000 | Awarded: $800 | Paid: $800 |

| Disposition Id: 2 | Created By: Joe Blow | Created Date: 07-05-2016 |

| Cause Number: 55 | County: Pierce | Prosecutor: Susan Johnson |

| Restitution Requested: $2000 | Awarded: $1500 | Paid: $1000 |

| Disposition Id: 3 | Created By: Mia Jones | Created Date: 09-08-2016 |

| Cause Number: 62 | County: Thurston | Prosecutor: Ron Sanders |

| Restitution Requested: $1500 | Awarded: $1500 | Paid: $1500 |

答: You need to have a row group in the table that is grouped by the Disposition ID. Then you can put all the text in the cells in those rows. The set of three rows will repeat for each ID. Here's an example of what the basic table structure should look like:


问:
Navigating Between HTML Windows
and thanks for taking a look at this seemingly simple question.

The scenario is as follows: I have a website Homepage named 'welcome.html'. From here users can select from a list of URLs and on clicking on the URL a simple Javascript function is called which opens a new Window.

Once the user has finished in the newly opened Window I want them to click on a button which calls a Javascript function to return them to the Homepage. It seems so simple.

However, if the Homepage Window is still open I want to return to this and not open another new Window displaying the Homepage. If the Homepage Window has been closed then I want a new Window to open displaying the Homepage.

I would be very grateful for some guidance here as I can't seem to get it to work.

Regards

Chris

答:
As others have said, it is not the greatest design.  However, I've run into scenarios like this in the past, where the business logic stipulates that a new window must be opened and there is no ability to change that.

As Pointy said, the biggest thing is just to keep track of the windows opened, and if you need some further help, perhaps this may help:
http://www.quirksmode.org/js/popup.html

But if possible, I would consider a different design (ask here if you need help implementing it!)

Title: Navigating Between HTML Windows


问:
Switching from tensorflow on python 3.6 to python 3.5
This is my first question on stackoverflow, please bear with me as I will do my best to provide as much info as possible.

I have a windows 10, 6-bit processor.  My end goal is to use keras within spyder.  The first thing I did was update python to 3.6 and install tensorflow, which seemed to work.  When I attempted to get keras, however, it wasn't working, and I read that keras worked on python 3.5.  I successfully installed keras on python 3.5, which automatically installed theano as the backend.

But now I have two spyder environments, one running off of python 3.5, one off of 3.6.  The 3.5 reads keras but doesn't go through with any modules because it cannot find tensorflow.  The 3.6 can read tensorflow, but cannot find keras.

Please let me know what you would recommend.  Thank you!

答:
Create a virtualenv with python 3.5 installed.

I dealt with this same issue, using Jupyter Notebook. Didn't understand why you would even need a virtualenv until I learned from this roadblock.

Full details on installing and setting up a virtualenv can be found here:
http://pymote.readthedocs.io/en/latest/install/windows_virtualenv.html


问:
HTTP PATCH Method C#
I don't see the option of including a HTTP "PATCH" request, I don't get the option using Visual Studio Intellisense? How do I include the "PATCH" method in this code instead of "POST"</p>

```<code>using (HttpClient httpClient = new HttpClient())
{
    Uri requesturi = new Uri(string.Format("{0}/api/data/v8.2/", url));
    httpClient.BaseAddress = requesturi;
    httpClient.Timeout = new TimeSpan(0, 0, 4);  // 10 minutes
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    result = GetS2SAccessToken(url, pwd);
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
    request.Content = new StringContent(props.ToString(), Encoding.UTF8, "application/json");
}
</code>```

答:
I found this post here on StackOverflow: click

He has done it with the folowing code example:

```<code>public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
    var method = new HttpMethod("PATCH");

    var request = new HttpRequestMessage(method, requestUri) {
        Content = iContent
    };

    HttpResponseMessage response = new HttpResponseMessage();
    // In case you want to set a timeout
    //CancellationToken cancellationToken = new CancellationTokenSource(60).Token;

    try {
         response = await client.SendRequestAsync(request);
         // If you want to use the timeout you set
         //response = await client.SendRequestAsync(request).AsTask(cancellationToken);
    } catch(TaskCanceledException e) {
        Debug.WriteLine("ERROR: " + e.ToString());
    }

    return response;
}
</code>```

Title: HTTP PATCH Method C#

Body:
I don't see the option of including a HTTP "PATCH" request, I don't get the option using Visual Studio Intellisense? How do I include the "PATCH" method in this code instead of "POST"

using (HttpClient httpClient = new HttpClient())
{
    Uri requesturi = new Uri(string.Format("{0}/api/data/v8.2/", url));
    httpClient.BaseAddress = requesturi;
    httpClient.Timeout = new TimeSpan(0, 0, 4);  // 10 minutes
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    result = GetS2SAccessToken(url, pwd);
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
    request.Content = new StringContent(props.ToString(), Encoding.UTF8, "application/json");
}

Body:
I found this post here on StackOverflow: click

He has done it with the folowing code example:

public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
    var method = new HttpMethod("PATCH");

    var request = new HttpRequestMessage(method, requestUri) {
        Content = iContent
    };

    HttpResponseMessage response = new HttpResponseMessage();
    // In case you want to set a timeout
    //CancellationToken cancellationToken = new CancellationTokenSource(60).Token;

    try {
         response = await client.SendRequestAsync(request);
         // If you want to use the timeout you set
         //response = await client.SendRequestAsync(request).AsTask(cancellationToken);
    } catch(TaskCanceledException e) {
        Debug.WriteLine("ERROR: " + e.ToString());
    }

    return response;
}


问:
get auto_increment value from mysql to jtextfield in java
i have created a two column in mysql

```<code>Category    varchar(30) YES
Serial_No   int(11) NO  PRI     auto_increment
</code>```

how to retrieve Category column using Serial_No in mysql and set this category data in Jtextfield in java.

答:
my answer: i have to update that specific category using serial no which is auto_increment column in mysql. so i find my solution Thank You</p>

```<code>table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                Row=table.getSelectedRow();
                TableModel model=table.getModel();
                Category=model.getValueAt(Row, 0).toString();
                Serial_No=model.getValueAt(Row,1).toString();
                textField_2.setText(Category);
            }
        });

public void Update()
    {
        try
        {
        Category=textField_2.getText();

        query="Update Category_Table Set Category='"+Category+"' where Serial_No='"+Serial_No+"'";
        PStat=con.prepareStatement(query);
        PStat.execute();
        JOptionPane.showMessageDialog(null,"Updated Data");
        Category_List();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
</code>```

Body:
i have created a two column in mysql

Category    varchar(30) YES
Serial_No   int(11) NO  PRI     auto_increment

how to retrieve Category column using Serial_No in mysql and set this category data in Jtextfield in java.

Body:
my answer: i have to update that specific category using serial no which is auto_increment column in mysql. so i find my solution Thank You

table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                Row=table.getSelectedRow();
                TableModel model=table.getModel();
                Category=model.getValueAt(Row, 0).toString();
                Serial_No=model.getValueAt(Row,1).toString();
                textField_2.setText(Category);
            }
        });

public void Update()
    {
        try
        {
        Category=textField_2.getText();

        query="Update Category_Table Set Category='"+Category+"' where Serial_No='"+Serial_No+"'";
        PStat=con.prepareStatement(query);
        PStat.execute();
        JOptionPane.showMessageDialog(null,"Updated Data");
        Category_List();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }