问:
How to access web service using Boost::Asio?
I wonder whether there is a possibility to access a web service using boost asio library.

I have tried following code (in IOS, C++11) which I got from boost asio documentation.
But it throws the following.

```<code>try
{
    boost::asio::io_service io_service;
    std::string address = "http://www.thomas-bayer.com/axis2/services/BLZService/";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address,boost::asio::ip::resolver_query_base::numeric_service);

    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";

    std::cout<<"Print Query --"<<std::endl;

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);

    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "POST: HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by passing
    // a maximum size to the streambuf constructor.

    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);

    if (!response_stream || http_version.substr(0, 5) != "HTTP/")
    {
        std::cout << "Invalid response\n";
        return;
    }
    if (status_code != 200)
    {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
        std::cout << header << "\n";
    std::cout << "\n";

    // Write whatever content we already have to output.
    if (response.size() > 0)
        std::cout << &response;

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response,
                             boost::asio::transfer_at_least(1), error))
        std::cout << &response;
    if (error != boost::asio::error::eof)
        throw boost::system::system_error(error);
}
catch (std::exception& e)
{
    std::cout << "Exception: " << e.what() << "\n";
}
</code>```

Exception: connect: Can't assign requested address

Or

Exception: resolve: Host not found (authoritative)

What is wrong with the code? Or I am doing completely wrong?

Thanks

答:
The name resolution fails, because you are confusing what is a request, a URL, a protocol, hostname and an IP address.

Do the requestion on a FQDN. You need to supply a service unless you know it. The service in this case follows from the the protocol¹, `http:// is usually served on port 80:

```<code>std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);
</code>```

Note that on most systems you can equivalently use:

```<code>std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "http");
</code>```

See where the http:// and www.thomas-bayer.com parts went?

Now /axis2/services/BLZService/ is the query path, as you would write in a GET request:

```<code>request_stream << "GET /axis2/services/BLZService/ HTTP/1.1\r\n";
</code>```

Notes:

POST is not a header (so no colon!) it's a HTTP "verb" (GET, POST, DELETE, PUT...)

The "Host" header is a host name:

```<code> request_stream << "Host: " << address << "\r\n";
</code>```

was correct iff address was really the logical name for the host

setting the hostname like this:

```<code> endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";
</code>```

is something I've never seen before and I'm not sure what it should achieve. Perhaps it's just wrong?

¹ by convention, it could be other

Fixes

```<code>#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;

void test() try {
    boost::asio::io_service io_service;
    std::string const address = "www.thomas-bayer.com";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);

    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    std::cout << "Print Query --" << std::endl;

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);

    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET /axis2/services/BLZService HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by
    // passing a maximum size to the streambuf constructor.
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version, status_message;
    unsigned int status_code;
    std::getline(response_stream >> http_version >> status_code, status_message);

    if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
        std::cout << "Invalid response\n";
        return;
    }
    if (status_code != 200) {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
        std::cout << header << "\n";
    std::cout << "\n";

    // Write whatever content we already have to output.
    if (response.size() > 0)
        std::cout << &response;

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error))
        std::cout << &response;
    if (error != boost::asio::error::eof)
        throw boost::system::system_error(error);
} catch (std::exception &e) {
    std::cout << "Exception: " << e.what() << "\n";
}

int main() { test(); }
</code>```

Body:
I wonder whether there is a possibility to access a web service using boost asio library.

I have tried following code (in IOS, C++11) which I got from boost asio documentation.
But it throws the following.

try
{
    boost::asio::io_service io_service;
    std::string address = "http://www.thomas-bayer.com/axis2/services/BLZService/";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address,boost::asio::ip::resolver_query_base::numeric_service);

    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";

    std::cout<<"Print Query --"<<std::endl;

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);

    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "POST: HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by passing
    // a maximum size to the streambuf constructor.

    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);

    if (!response_stream || http_version.substr(0, 5) != "HTTP/")
    {
        std::cout << "Invalid response\n";
        return;
    }
    if (status_code != 200)
    {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
        std::cout << header << "\n";
    std::cout << "\n";

    // Write whatever content we already have to output.
    if (response.size() > 0)
        std::cout << &response;

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response,
                             boost::asio::transfer_at_least(1), error))
        std::cout << &response;
    if (error != boost::asio::error::eof)
        throw boost::system::system_error(error);
}
catch (std::exception& e)
{
    std::cout << "Exception: " << e.what() << "\n";
}

Exception: connect: Can't assign requested address

Or

Exception: resolve: Host not found (authoritative)

What is wrong with the code? Or I am doing completely wrong?

Thanks

Body:
The name resolution fails, because you are confusing what is a request, a URL, a protocol, hostname and an IP address.

Do the requestion on a FQDN. You need to supply a service unless you know it. The service in this case follows from the the protocol¹, `http:// is usually served on port 80:

std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);

Note that on most systems you can equivalently use:

std::string const address = "www.thomas-bayer.com";
tcp::resolver::query query(address, "http");

See where the http:// and www.thomas-bayer.com parts went?

Now /axis2/services/BLZService/ is the query path, as you would write in a GET request:

request_stream << "GET /axis2/services/BLZService/ HTTP/1.1\r\n";

Notes:

POST is not a header (so no colon!) it's a HTTP "verb" (GET, POST, DELETE, PUT...)

The "Host" header is a host name:

 request_stream << "Host: " << address << "\r\n";

was correct iff address was really the logical name for the host

setting the hostname like this:

 endpoint_iterator->host_name() = "www.thomas-bayer.com/axis2/services/BLZService/";

is something I've never seen before and I'm not sure what it should achieve. Perhaps it's just wrong?

¹ by convention, it could be other

Fixes

#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;

void test() try {
    boost::asio::io_service io_service;
    std::string const address = "www.thomas-bayer.com";

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(address, "80", boost::asio::ip::resolver_query_base::numeric_service);

    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    std::cout << "Print Query --" << std::endl;

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);

    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET /axis2/services/BLZService HTTP/1.0\r\n";
    request_stream << "Host: " << address << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by
    // passing a maximum size to the streambuf constructor.
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version, status_message;
    unsigned int status_code;
    std::getline(response_stream >> http_version >> status_code, status_message);

    if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
        std::cout << "Invalid response\n";
        return;
    }
    if (status_code != 200) {
        std::cout << "Response returned with status code " << status_code << "\n";
        return;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
        std::cout << header << "\n";
    std::cout << "\n";

    // Write whatever content we already have to output.
    if (response.size() > 0)
        std::cout << &response;

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error))
        std::cout << &response;
    if (error != boost::asio::error::eof)
        throw boost::system::system_error(error);
} catch (std::exception &e) {
    std::cout << "Exception: " << e.what() << "\n";
}

int main() { test(); }


来源: stackexchange

问:
Avoiding nesting maps when "pivoting" multidimensional array
I have data in the format

```<code>[
  {
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
         ...
    }
  }
]
</code>```

that in order to use in a google chart I need to change to the format

```<code>[
  ["2017-05-06", 770, 590, 890, ...],
  ["2017-05-07", 760, 210, 2200, ...],
  ["2017-05-08", 1250, 300, 1032, ...]
]
</code>```

I wrote the following to make the transformation

```<code>let mapped = _.map(
  chartData.results[0].timeline_map, (timestampVal, timestampKey) => (
  [timestampKey].concat(
    _.map(
      chartData.results, lineData => (
        lineData.timeline_map[timestampKey]
        )
      )
    )
  )
)
</code>```

This works, but I'm thinking that nesting the maps is not a good idea because how it will increase the amount of looping by the square off the length of the array being mapped. Is there a better way to achieve the desired result here.

JSBIN

答:
Merge the objects using _.mergeWith(), and then _.map() the resulting object to an array of arrays:

const arr = [{
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
    }
  }
];

const result = _.map(_.mergeWith({}, ...arr, (o1, o2) => {
  if(Array.isArray(o1)) {
    o1.push(o2)
    return o1;
  }

  if(_.isNumber(o2)) {
    return [o2];
  }
}).timeline_map, (v, k) => [k, ...v]);

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have data in the format

[
  {
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
         ...
    }
  }
]

that in order to use in a google chart I need to change to the format

[
  ["2017-05-06", 770, 590, 890, ...],
  ["2017-05-07", 760, 210, 2200, ...],
  ["2017-05-08", 1250, 300, 1032, ...]
]

I wrote the following to make the transformation

let mapped = _.map(
  chartData.results[0].timeline_map, (timestampVal, timestampKey) => (
  [timestampKey].concat(
    _.map(
      chartData.results, lineData => (
        lineData.timeline_map[timestampKey]
        )
      )
    )
  )
)

This works, but I'm thinking that nesting the maps is not a good idea because how it will increase the amount of looping by the square off the length of the array being mapped. Is there a better way to achieve the desired result here.

JSBIN

Body:
Merge the objects using _.mergeWith(), and then _.map() the resulting object to an array of arrays:

const arr = [{
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
    }
  }
];

const result = _.map(_.mergeWith({}, ...arr, (o1, o2) => {
  if(Array.isArray(o1)) {
    o1.push(o2)
    return o1;
  }

  if(_.isNumber(o2)) {
    return [o2];
  }
}).timeline_map, (v, k) => [k, ...v]);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
Waiting before returning the source in Selenium (not timeout())
I'm trying to webcrawl this website. As you can see, upon opening, it'll first show a first, wrong page for a few seconds, before loading the actual, right page I'm interested in.

For clarity. First/wrong page and the second, right page

As expected, using BeautifulSoup or Requests I only manage to get the html for the 'first page', and not the 'right' page.

I've tried using Selenium and set_page_load_timeout(), which only returns the 'first/wrong' page instead of the actual page.

```<code>driver = webdriver.Chrome()
driver.set_page_load_timeout(7)
url = 'https://images.nga.gov/en/search/do_quick_search.html?q=%221949.7.1%22'
driver.get(url)
source = BeautifulSoup(driver.page_source, 'html.parser')
print(source)
</code>```

I've tried looking for related questions, but they're all about setting a timeout, which does not seem to be the problem here, since a page is loading, it's just not the page I want.

Is there a way to get the source after 7 seconds? (i.e. waiting 7 seconds before getting the source, instead of having a timeout after 7 seconds)

答:
You can use title_is() expected condition to wait for a particular moment when required page is opened (page title changed from "Just a moment..." to "National Gallery of Art | NGA Images"):

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

driver = webdriver.Chrome()
url = 'https://images.nga.gov/en/search/do_quick_search.html?q=%221949.7.1%22'
title = "National Gallery of Art | NGA Images"
driver.get(url)
wait(driver, 10).until(EC.title_is(title))
source = BeautifulSoup(driver.page_source, 'html.parser')
print(source)
</code>```

Body:
I'm trying to webcrawl this website. As you can see, upon opening, it'll first show a first, wrong page for a few seconds, before loading the actual, right page I'm interested in.

For clarity. First/wrong page and the second, right page

As expected, using BeautifulSoup or Requests I only manage to get the html for the 'first page', and not the 'right' page.

I've tried using Selenium and set_page_load_timeout(), which only returns the 'first/wrong' page instead of the actual page.

driver = webdriver.Chrome()
driver.set_page_load_timeout(7)
url = 'https://images.nga.gov/en/search/do_quick_search.html?q=%221949.7.1%22'
driver.get(url)
source = BeautifulSoup(driver.page_source, 'html.parser')
print(source)

I've tried looking for related questions, but they're all about setting a timeout, which does not seem to be the problem here, since a page is loading, it's just not the page I want.

Is there a way to get the source after 7 seconds? (i.e. waiting 7 seconds before getting the source, instead of having a timeout after 7 seconds)

Body:
You can use title_is() expected condition to wait for a particular moment when required page is opened (page title changed from "Just a moment..." to "National Gallery of Art | NGA Images"):

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

driver = webdriver.Chrome()
url = 'https://images.nga.gov/en/search/do_quick_search.html?q=%221949.7.1%22'
title = "National Gallery of Art | NGA Images"
driver.get(url)
wait(driver, 10).until(EC.title_is(title))
source = BeautifulSoup(driver.page_source, 'html.parser')
print(source)


问:
Find open sockets in docker container
I have attached to a docker container and need to find out the number of sockets being open by java application . Unfortunately there is no lsof or netstat available in the container . There is no data in /proc/PID/net/tcp. Is there any way I can find this data?

答:
Alternatively, you can see this: /proc/PID/net/tcp in the host machine as long as you are in the same box as the docker daemon. This is less elegant than @BMitch's answer.

What you need to do is find out the PID of your process outside the container (in the main pid namespace, technically speaking, your host).

```<code>ps aux | grep java
</code>```

Inside your container, your java has a pid; but outside it has another pid that you can use to access to the information that you have requested: /proc/PID/net/tcp

ContentLicense: CC BY-SA 4.0

Title: Find open sockets in docker container

Body:
Alternatively, you can see this: /proc/PID/net/tcp in the host machine as long as you are in the same box as the docker daemon. This is less elegant than @BMitch's answer.

What you need to do is find out the PID of your process outside the container (in the main pid namespace, technically speaking, your host).

ps aux | grep java

Inside your container, your java has a pid; but outside it has another pid that you can use to access to the information that you have requested: /proc/PID/net/tcp


问:
What's the right way to do counts in Rails?
I have a rails app with many following pieces of code:

```<code>Our active community of <%= Account.find_all_by_admin(false).count %>
</code>```

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

答:
In rails 3 a simple call to count issues a simple count request:

```<code>Contact.count
</code>```

is resolved as:

```<code>SELECT COUNT(*) AS count_id FROM "contacts"
</code>```

a find all by field name will resolve as:

```<code>Contact.find_all_by_country("Canada")

SELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')
</code>```

I would recommend indexing your admin column for faster lookups and this can be translated into a named scope, but that by itself will only predefine the query, not optimize it.

It is important to note that if you issue

```<code>Contact.find_all_by_country("Canada").count
</code>```

count is a method on the array class and doesn't actually issue a count on the database:

```<code>Contact.find_all_by_country("Canada").count

SELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a rails app with many following pieces of code:

Our active community of <%= Account.find_all_by_admin(false).count %>

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

Body:
In rails 3 a simple call to count issues a simple count request:

Contact.count

is resolved as:

SELECT COUNT(*) AS count_id FROM "contacts"

a find all by field name will resolve as:

Contact.find_all_by_country("Canada")

SELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')

I would recommend indexing your admin column for faster lookups and this can be translated into a named scope, but that by itself will only predefine the query, not optimize it.

It is important to note that if you issue

Contact.find_all_by_country("Canada").count

count is a method on the array class and doesn't actually issue a count on the database:

Contact.find_all_by_country("Canada").count

SELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')


问:
C# Regex replace all alphabets except :abc
I have tried few combinations in C# but with no luck

I want to replace any alphabet in the string with empty string,  except where string contains :abc as the last 4 characters?

Test123 will become 123

Testabc123 will become 123

Test:abc123 will become 123

Test123:abc will become 123:abc

Testabc123:abc will become 123:abc

In the above examples,  alphabets were replaced to empty string, except where :abc were the last 4 characters, and then numbers:abc were not replaced by empty string

Can you please suggest appropriate regex?

答:
The regex /^(?:(?!:abc$)\D)+/gm almost works, if you replace with an empty string. As you can see here on Regex101, it will match all parts of a string except numbers and :abc at the end of a line, but, for some reason, stops searching once it finds a number. So 123Test would be unaffected, and Test123abc would become 123abc.

EDIT: Removing the caret (start of line) fixes it, but then it also includes :abc, so it is needed.


问:
bash sed/awk/something for printing lines from match till eof except first line
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

```<code>awk '/regex/,0'
sed '/regex/,$p'
</code>```

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

```<code>$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

Find and print:

```<code>$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

What i want to get:

```<code>14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

答:
another alternative </p>

```<code>awk 'f; /Dinner/{f=1}' file

14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
</code>```

<p>In general, to include either start or end pattern, there are 2x2 combinations. </p>

```<code>$ awk '/Start/{f=1} f; /End/{f=0}' file
Start
1
2
3
End

$ awk '/End/{f=0} f; /Start/{f=1}' file
1
2
3

$ awk '/Start/{f=1} /End/{f=0} f' file
# or
$ awk '/End/{f=0} /Start/{f=1} f' file
Start
1
2
3

$ awk 'f; /Start/{f=1} /End/{f=0}' file
# or
$ awk 'f; /End/{f=0} /Start/{f=1}' file
1
2
3
End
</code>```

Body:
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

awk '/regex/,0'
sed '/regex/,$p'

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Find and print:

$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

What i want to get:

14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Body:
another alternative

awk 'f; /Dinner/{f=1}' file

14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake

In general, to include either start or end pattern, there are 2x2 combinations.

$ awk '/Start/{f=1} f; /End/{f=0}' file
Start
1
2
3
End

$ awk '/End/{f=0} f; /Start/{f=1}' file
1
2
3

$ awk '/Start/{f=1} /End/{f=0} f' file
# or
$ awk '/End/{f=0} /Start/{f=1} f' file
Start
1
2
3

$ awk 'f; /Start/{f=1} /End/{f=0}' file
# or
$ awk 'f; /End/{f=0} /Start/{f=1}' file
1
2
3
End


问:
How do I Add a UIBarButtonItem to the navigationBar in a turbolinks-ios app
I have a turbolinks-ios app that I've inherited and need to add a native nav.

At first I used the storyboard to embed the main application controller within a navigation controller, but turbolinks has it's own navigation bar so that creates two stacked navigation bars. I then deleted the nav controller from the storyboard, but now I cannot add my button to the default turbolinks nav bar. There's no errors, and if I step through the code it hits every line within my function, but nothing is displayed in the bar. What am I doing wrong?

My function which is called from viewDidLoad() within the UINavigationController class is as follows...

```<code>    func addSlideMenuButton() {
        let callback = #selector(toggleNav)
        let btnShowMenu = UIButton(type: UIButtonType.system)
        btnShowMenu.setImage(self.defaultMenuImage(), for: UIControlState())
        btnShowMenu.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        btnShowMenu.addTarget(self, action: callback, for: UIControlEvents.touchUpInside)
        let customBarItem = UIBarButtonItem(customView: btnShowMenu)
        navigationController?.navigationItem.rightBarButtonItem = customBarItem
    }
</code>```

Any nudge in the right direction would be greatly appreciated.

答:
You have to call sizeToFit on the customView first.

So add btnShowMenu.sizeToFit just before creating the UIBarButtonItem.

Body:
I have a turbolinks-ios app that I've inherited and need to add a native nav.

At first I used the storyboard to embed the main application controller within a navigation controller, but turbolinks has it's own navigation bar so that creates two stacked navigation bars. I then deleted the nav controller from the storyboard, but now I cannot add my button to the default turbolinks nav bar. There's no errors, and if I step through the code it hits every line within my function, but nothing is displayed in the bar. What am I doing wrong?

My function which is called from viewDidLoad() within the UINavigationController class is as follows...

    func addSlideMenuButton() {
        let callback = #selector(toggleNav)
        let btnShowMenu = UIButton(type: UIButtonType.system)
        btnShowMenu.setImage(self.defaultMenuImage(), for: UIControlState())
        btnShowMenu.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        btnShowMenu.addTarget(self, action: callback, for: UIControlEvents.touchUpInside)
        let customBarItem = UIBarButtonItem(customView: btnShowMenu)
        navigationController?.navigationItem.rightBarButtonItem = customBarItem
    }

Any nudge in the right direction would be greatly appreciated.


问:
How to partition table rows get the min and max for each process
Can someone please let me know how to get the output from first table. please note that I am not allowed to use loops. I tried with window functions and no luck yet. </p>

```<code>CUSTOMER_NUMBER ORDER_NO PROCESS
100             1001        1
100             1002        1
100             1003        2
100             1004        2
100             1005        2
100             1006        3
100             1007        3
100             1008        3
101             1009        1
101             1010        1
101             1011        2
101             1012        2
101             1013        2

CUSTOMER_NUMBER MIN_VALUE, MAX_VALUE, PROCESS
100             1001        1002            1
100             1003        1005            2
100             1006        1008            3
101             1009        1010            1
101             1011        1013            2
</code>```

答:
Here you go</p>

```<code>select
  min(ORDER_NO) as MIN_VALUE,
  max(ORDER_NO) as MAX_VALUE,
  PROCESS
from yourTable
group by PROCESS
</code>```

Body:
Can someone please let me know how to get the output from first table. please note that I am not allowed to use loops. I tried with window functions and no luck yet.

CUSTOMER_NUMBER ORDER_NO PROCESS
100             1001        1
100             1002        1
100             1003        2
100             1004        2
100             1005        2
100             1006        3
100             1007        3
100             1008        3
101             1009        1
101             1010        1
101             1011        2
101             1012        2
101             1013        2

CUSTOMER_NUMBER MIN_VALUE, MAX_VALUE, PROCESS
100             1001        1002            1
100             1003        1005            2
100             1006        1008            3
101             1009        1010            1
101             1011        1013            2

Body:
Here you go

select
  min(ORDER_NO) as MIN_VALUE,
  max(ORDER_NO) as MAX_VALUE,
  PROCESS
from yourTable
group by PROCESS


问:
What is jmap's default heapdump format?
We are taking heapdumps and have a question:

jmap -dump:file=heapdump.hprof,format=b

If you specify format=a it will be usage message in ascii

If you specify format=b it will be binary

OK great, but what if you don't specify a format at all?

jmap -dump:file=heapdump.hprof

Which one will it pick?

答:
The default is binary data file (hprof). You can just try running the command without specifying the format and with format=b and you will find out yourself that they have the same format.

```<code>alessio$ file heapdump.hprof
heapdump.hprof: data
</code>```

Title: What is jmap's default heapdump format?

Body:
The default is binary data file (hprof). You can just try running the command without specifying the format and with format=b and you will find out yourself that they have the same format.

alessio$ file heapdump.hprof
heapdump.hprof: data


问:
Webservice into array , substring suitable?
I am currently developing an Java app in Android Studio.

I am facing a little problem. I have a big file from a web-service, and it's already in a variable. At the end I would like to have an array for each SKU (always under a style). And the array should only contain the first 9 values. So array one should be named: sku1[9] with

```<code>sku1[0]="123456"
sku1[1]="123456"
sku1[2]="123456"
...
</code>```

Then I need another array: sku2[9] with

```<code>sku2[0]="123456"
sku2[1]="123456"
sku2[2]="123456"
...
</code>```

Any ideas how to extract the needed strings from this big ass file and put them into a nice array?

Any help would be appreciated.

答:
As the String is already into a variable, you can use Pattern matching to extract the sku Strings, e.g.:

```<code>String s = "<!DOCTYPE> <div>    styles = {\"sku1_1\":\"12\",..}";
Pattern pattern = Pattern.compile("(\"sku[0-9]_[0-9]\":\"[0-9]+\")");
Matcher m = pattern.matcher(s);
while(m.find()){
    System.out.println(m.group(1));
}
</code>```

This will by default ignore the Strings that have more than one digit after _.

Update

If you want the values to be stored inside an array then you can declare an arraylist, add the elements into it and convert it back to array, e.g.:

```<code>String s = "<!DOCTYPE> <div>    styles = {\"sku1_1\":\"12\",..}";
Pattern pattern = Pattern.compile("(\"sku[0-9]_[0-9]+\":\"[0-9]\")");
Matcher m = pattern.matcher(s);
List<String> values = new ArrayList<>();
while(m.find()){
   String[] tokens = m.group(1).split(":");
   values.add(tokens[1]);
}
String[] array = values.toArray(new String[values.size()]);
</code>```

This way, it will put the values inside an array. If you want multiple arrays then you can check the value of the first token (i.e. tokens[0]) and initialise the new list if it has changed from let's say sku1 to sku2.

Body:
I am currently developing an Java app in Android Studio.

I am facing a little problem. I have a big file from a web-service, and it's already in a variable. At the end I would like to have an array for each SKU (always under a style). And the array should only contain the first 9 values. So array one should be named: sku1[9] with

sku1[0]="123456"
sku1[1]="123456"
sku1[2]="123456"
...

Then I need another array: sku2[9] with

sku2[0]="123456"
sku2[1]="123456"
sku2[2]="123456"
...

Any ideas how to extract the needed strings from this big ass file and put them into a nice array?

Any help would be appreciated.

Body:
As the String is already into a variable, you can use Pattern matching to extract the sku Strings, e.g.:

String s = "<!DOCTYPE> <div>    styles = {\"sku1_1\":\"12\",..}";
Pattern pattern = Pattern.compile("(\"sku[0-9]_[0-9]\":\"[0-9]+\")");
Matcher m = pattern.matcher(s);
while(m.find()){
    System.out.println(m.group(1));
}

This will by default ignore the Strings that have more than one digit after _.

Update

If you want the values to be stored inside an array then you can declare an arraylist, add the elements into it and convert it back to array, e.g.:

String s = "<!DOCTYPE> <div>    styles = {\"sku1_1\":\"12\",..}";
Pattern pattern = Pattern.compile("(\"sku[0-9]_[0-9]+\":\"[0-9]\")");
Matcher m = pattern.matcher(s);
List<String> values = new ArrayList<>();
while(m.find()){
   String[] tokens = m.group(1).split(":");
   values.add(tokens[1]);
}
String[] array = values.toArray(new String[values.size()]);

This way, it will put the values inside an array. If you want multiple arrays then you can check the value of the first token (i.e. tokens[0]) and initialise the new list if it has changed from let's say sku1 to sku2.


问:
how do re-size a HTML <object> tag when the content in it is dynamic
I have some jQuery and HTML that renders an OBJECT tag with a default html page then repopulates the OBJECT on a button click when the new page  ,which is dynamic, is done rendering I'd like to resize the object to be 100% the size of the rendered page is that possible ?

code following

```<code>$(document).ready(function() {
  $('#sq').click(function() {
     var actualYear = $('#ay').val() ;
     var actualTerm = $('#tc').val();
     if (actualTerm == '01')
     {
      actualYear = Number($('#ay').val()) + 1;
     }
     var actualTC = actualYear + actualTerm;                                                               + $('#smcSel').val() +  "&ccc=" + $('#cccSel').val()  + "&ac=" + $('#acSel').val() + "&cs=" + $('#csSel').val() + "&cl=" + $('#clSel').val() + "&smd=" + $('#smdSel').val() + "&sm=" + $('#smSel').val()  + "&sl=" + $('#slSel').val()  + "&ib=" + $('#IBID').val() + "&sb=" + $('#SBID').val() + "&ay=" + $('#ay').val() + "&tc=" + $('#ay').val()  + $('#tc').val() + "&tca="+ actualTC + "&mes=" + $('#mes').val()  + "&pr=" + $('#pr').val()  + "&sr=" + $('#sr').val() + "&tr=" + $('#tr').val() + "&col=" + $('#col').val()  + "&mc=";
     var urlis = window.location.protocol + "//" + window.location.hostname + "/SASStoredProcess/do?_action=execute,nobanner,newwindow&_program=%2FTABBS%2FuQuery%2Ftbir11052&smc=" + $('#smcSel').val() +  "&ccc=" + $('#cccSel').val()  + "&ac=" + $('#acSel').val() + "&cs=" + $('#csSel').val() + "&cl=" + $('#clSel').val() + "&smd=" + $('#smdSel').val() + "&sm=" + $('#smSel').val()  + "&sl=" + $('#slSel').val()  + "&ib=" + $('#IBID').val() + "&sb=" + $('#SBID').val() + "&ay=" + $('#ay').val() + "&tc=" + $('#ay').val()  + $('#tc').val() + "&tca="+ actualTC + "&mes=" + $('#mes').val()  + "&pr=" + $('#pr').val()  + "&sr=" + $('#sr').val() + "&tr=" + $('#tr').val() + "&col=" + $('#col').val()  + "&mc=";

        document.getElementById("contentarea").setAttribute('data', urlis);
    });
});

<div id="result">
<object type="text/html" data="./contentarea.html" style="float:left;width:100%;height:100%;" id=contentarea></object>

</div>
</code>```

答:
Add this style style="float:left;width:100%;height:100%;" to
.

Body:
I have some jQuery and HTML that renders an OBJECT tag with a default html page then repopulates the OBJECT on a button click when the new page  ,which is dynamic, is done rendering I'd like to resize the object to be 100% the size of the rendered page is that possible ?

code following

$(document).ready(function() {
  $('#sq').click(function() {
     var actualYear = $('#ay').val() ;
     var actualTerm = $('#tc').val();
     if (actualTerm == '01')
     {
      actualYear = Number($('#ay').val()) + 1;
     }
     var actualTC = actualYear + actualTerm;                                                               + $('#smcSel').val() +  "&ccc=" + $('#cccSel').val()  + "&ac=" + $('#acSel').val() + "&cs=" + $('#csSel').val() + "&cl=" + $('#clSel').val() + "&smd=" + $('#smdSel').val() + "&sm=" + $('#smSel').val()  + "&sl=" + $('#slSel').val()  + "&ib=" + $('#IBID').val() + "&sb=" + $('#SBID').val() + "&ay=" + $('#ay').val() + "&tc=" + $('#ay').val()  + $('#tc').val() + "&tca="+ actualTC + "&mes=" + $('#mes').val()  + "&pr=" + $('#pr').val()  + "&sr=" + $('#sr').val() + "&tr=" + $('#tr').val() + "&col=" + $('#col').val()  + "&mc=";
     var urlis = window.location.protocol + "//" + window.location.hostname + "/SASStoredProcess/do?_action=execute,nobanner,newwindow&_program=%2FTABBS%2FuQuery%2Ftbir11052&smc=" + $('#smcSel').val() +  "&ccc=" + $('#cccSel').val()  + "&ac=" + $('#acSel').val() + "&cs=" + $('#csSel').val() + "&cl=" + $('#clSel').val() + "&smd=" + $('#smdSel').val() + "&sm=" + $('#smSel').val()  + "&sl=" + $('#slSel').val()  + "&ib=" + $('#IBID').val() + "&sb=" + $('#SBID').val() + "&ay=" + $('#ay').val() + "&tc=" + $('#ay').val()  + $('#tc').val() + "&tca="+ actualTC + "&mes=" + $('#mes').val()  + "&pr=" + $('#pr').val()  + "&sr=" + $('#sr').val() + "&tr=" + $('#tr').val() + "&col=" + $('#col').val()  + "&mc=";

        document.getElementById("contentarea").setAttribute('data', urlis);
    });
});

<object type="text/html" data="./contentarea.html" style="float:left;width:100%;height:100%;" id=contentarea></object>

Body: Add this style style="float:left;width:100%;height:100%;" to <div id="result">.


问:
Use Xcode 8 with iOS 11
I want to use Xcode 8 with iOS 11.

should I upgrade my Xcode. However, my code can't be built by the new compiler, so I want to stay with Xcode 8.

How can I achieve that?

Apple revealed several new iOS 11 features at WWDC 2017.

答:
I preferred to copy ALL the folder:

```<code>/Volumes/**HighSierra**/Applications/Xcode-**beta.app**/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\)
</code>```

to:

```<code> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/**11**
</code>```

I can confirm I can run on my iPhone 7 with iOS 11

Title: Use Xcode 8 with iOS 11

Body:
I preferred to copy ALL the folder:

/Volumes/**HighSierra**/Applications/Xcode-**beta.app**/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\)

to:

 /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/**11**

I can confirm I can run on my iPhone 7 with iOS 11


问:
Why Angular Material is responive and AngualJS Material isn't?
I'm trying to choose a framework for an application of mine and I stumbled across
Angular Material and AngularJS Material I understand that both are from Google (correct me if I'm wrong) but basically are both doing more or less the same, rendering components in a HTML page, what I don't get (and google around is not very efficent due to confusion on similar name) why Angular material is not responsive and AngularJS Material is? Wich one I should choose in order to make my app responsive? Or..how would I get an Angular Material app respnsive?</p>

答:
For your Angular 2 and Angular 4 apps you can use

https://github.com/angular/flex-layout

You can see on this demo how it is implemente a responsive layout.

https://tburleson-layouts-demos.firebaseapp.com/#/responsive

hope it helps.


问:
Correctly bundled image could not be loaded
I have a very simple React component, that is supposed to display an image.
I am also using Webpack for bundling.

It's probably worth noting that I am using ReactJS.NET.

Although the webpack bundle builds properly, and the .jpg generated by webpack is viewable (using Windows Photo Viewer, for example), the image does not display in my View.

When I take a peek into inspector, the html structure is built properly, but I am getting:

"Could not load the image" - when I hover over the image path.

I made sure that the image path is correct.

Below is my react component:

```<code>var React = require('react');
var BackgroundImg = require('./Images/img_fjords.jpg');

class Login extends React.Component {
    render() {
        return (
            <img src={BackgroundImg} />
        );
    }

    componentDidMount() {
        console.log("Mounted");
    }
}

module.exports = Login;
</code>```

Webpack config:

```<code>var path = require('path');
var WebpackNotifierPlugin = require('webpack-notifier');

module.exports = {
    context: path.join(__dirname, 'App'),
    entry: {
        server: './server',
        client: './client'
    },

    output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: path.join(__dirname, 'Built/'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new WebpackNotifierPlugin()
    ],
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&mimetype=application/font-woff"
            },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ]
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['.js', '.jsx']
    },

    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};
</code>```

答: Well, I can't see your webpack config, but I'm assuming your using all the correct loaders (file-loader, extract-loader, html-loader, url-loader)? The way I handle it is using the webpack-copy-plugin to copy over my images folder so relative paths still work.</p>

Body:
I have a very simple React component, that is supposed to display an image.
I am also using Webpack for bundling.

It's probably worth noting that I am using ReactJS.NET.

Although the webpack bundle builds properly, and the .jpg generated by webpack is viewable (using Windows Photo Viewer, for example), the image does not display in my View.

When I take a peek into inspector, the html structure is built properly, but I am getting:

"Could not load the image" - when I hover over the image path.

I made sure that the image path is correct.

Below is my react component:

var React = require('react');
var BackgroundImg = require('./Images/img_fjords.jpg');

class Login extends React.Component {
    render() {
        return (

        );
    }

    componentDidMount() {
        console.log("Mounted");
    }
}

module.exports = Login;

Webpack config:

var path = require('path');
var WebpackNotifierPlugin = require('webpack-notifier');

module.exports = {
    context: path.join(__dirname, 'App'),
    entry: {
        server: './server',
        client: './client'
    },

    output: {
        path: path.join(__dirname, 'Built/'),
        publicPath: path.join(__dirname, 'Built/'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new WebpackNotifierPlugin()
    ],
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&mimetype=application/font-woff"
            },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ]
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['.js', '.jsx']
    },

    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};


问:
python function for creating pairs based on ordered items in list
```<code>dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]
</code>```

Using python, I am trying to create a conversation pair dataset where each pair in the set will have speaker 1 and the subsequent response from speaker 2.
With the example dat above, I would need to iterate through the list and 1) merge sentences from the same speaker if they are subsequent and 2) create the pair as below example;

Output:

```<code>((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))
</code>```

How do I write a function that takes in sequential data like this to create conversation pairs?

答:
```<code>def combine_speaker_lines(id_part_iter):
    conversation = []
    last_speaker, part = id_part_iter[0]
    for speaker, fragment in id_part_iter[1:]:
        if speaker != last_speaker:
            conversation.append((last_speaker, part.lstrip()))
            part = ''
        part += ' ' + fragment
        last_speaker = speaker
    conversation.append((speaker, part.lstrip()))
    return conversation
    return conversation
</code>```

Body:
dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]

Using python, I am trying to create a conversation pair dataset where each pair in the set will have speaker 1 and the subsequent response from speaker 2.
With the example dat above, I would need to iterate through the list and 1) merge sentences from the same speaker if they are subsequent and 2) create the pair as below example;

Output:

((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))

How do I write a function that takes in sequential data like this to create conversation pairs?


问:
One to many association on Sails 0.10.x fails to retrieve owner data using populate
I'm trying to create a simple one-to-many assocation using sails 0.10.x with mongoDB.
I have two models, Game and Map, which a game can have multiple maps associated to its account.
Using populate I can correctly get all the maps associated to the game, but the inverse operation doesn't work. I cannot get the game data using populate from Map.

here are my models:

```<code>//Game.js
module.exports = {
   attributes: {
    name:{
       type: 'string',
       required: true
     },

   maps: {
      collection: 'map',
      via: 'game'
   }
}

//Map.js
module.exports = {
    attributes: {
        name: {
           type: 'string',
           required: true
     },

game:{
     model: 'game'
  }
}

//test data:
  Game.create({
    id: 200,
    name: 'game1'});

  Map.create({
    id: 300,
    name: 'map1',
    game: 200
  });
</code>```

If I use

```<code>Game.find().populate("maps").exec(console.log);
</code>```

it correclty returns the maps associated to the game:

```<code> { maps:
 [ { name: 'map1',
     game: '200',
     id: '300' } ],
  name: 'game1'}
</code>```

but the inverse command, trying to retrieve the game data from map, returns a undefined game property:

```<code>Map.find().populate("game").exec(console.log)
</code>```

returns:

```<code>{ name: 'map1',
  game: undefined,
  id: '300' }
</code>```

Even trying using a parameter in find(), I got the same result.

Double checked my code with the Sails and waterline documentation but could't figure out what I'm doing wrong.

Sails doc.: http://sailsjs.org/#/documentation/concepts/ORM/Associations/OnetoMany.html

Waterline doc.:https://github.com/balderdashy/waterline-docs/blob/master/associations.md

UPDATE

I figured out that, if I create the test data without forcing the IDs I want, it works perfectly:

```<code>  Game.create({name: 'game1'}).exec(console.log);

  Game.findOne({name: 'game1'}, function (err, game){
    Map.create({
      name: 'map1',
      game: game.id
    }).exec(console.log);
  });
</code>```

now I can get the owner data. Since it works when I use the mongoDB ids, I believe it is some issue related to the connector.

```<code>Map.find().populate("game").exec(console.log)
//returns (ommited the original IDs
   [ { game:
     { name: 'game1',  id: 'xxx100' },
     name: 'map1',
     id: 'xxx300' } ]
</code>```

Thanks!

答:
I figured out that, if I create the test data without forcing the IDs I want, it works perfectly:

```<code>Game.create({name: 'game1'}).exec(console.log);

Game.findOne({name: 'game1'}, function (err, game){
 Map.create({
   name: 'map1',
   game: game.id
 }).exec(console.log);
});
</code>```

now I can get the owner data.

Since it works when I use the mongoDB ids, I believe it is some issue related to the connector.

```<code>Map.find().populate("game").exec(console.log)
//returns (ommited the original IDs)
 [ { game:
    { name: 'game1',  id: 'xxx100' },
      name: 'map1',
      id: 'xxx300'
     }
 ]
</code>```

Body:
I'm trying to create a simple one-to-many assocation using sails 0.10.x with mongoDB.
I have two models, Game and Map, which a game can have multiple maps associated to its account.
Using populate I can correctly get all the maps associated to the game, but the inverse operation doesn't work. I cannot get the game data using populate from Map.

here are my models:

//Game.js
module.exports = {
   attributes: {
    name:{
       type: 'string',
       required: true
     },

   maps: {
      collection: 'map',
      via: 'game'
   }
}

//Map.js
module.exports = {
    attributes: {
        name: {
           type: 'string',
           required: true
     },

game:{
     model: 'game'
  }
}

//test data:
  Game.create({
    id: 200,
    name: 'game1'});

  Map.create({
    id: 300,
    name: 'map1',
    game: 200
  });

If I use

Game.find().populate("maps").exec(console.log);

it correclty returns the maps associated to the game:

 { maps:
 [ { name: 'map1',
     game: '200',
     id: '300' } ],
  name: 'game1'}

but the inverse command, trying to retrieve the game data from map, returns a undefined game property:

Map.find().populate("game").exec(console.log)

returns:

{ name: 'map1',
  game: undefined,
  id: '300' }

Even trying using a parameter in find(), I got the same result.

Double checked my code with the Sails and waterline documentation but could't figure out what I'm doing wrong.

Sails doc.: http://sailsjs.org/#/documentation/concepts/ORM/Associations/OnetoMany.html

Waterline doc.:https://github.com/balderdashy/waterline-docs/blob/master/associations.md

UPDATE

I figured out that, if I create the test data without forcing the IDs I want, it works perfectly:

  Game.create({name: 'game1'}).exec(console.log);

  Game.findOne({name: 'game1'}, function (err, game){
    Map.create({
      name: 'map1',
      game: game.id
    }).exec(console.log);
  });

now I can get the owner data. Since it works when I use the mongoDB ids, I believe it is some issue related to the connector.

Map.find().populate("game").exec(console.log)
//returns (ommited the original IDs
   [ { game:
     { name: 'game1',  id: 'xxx100' },
     name: 'map1',
     id: 'xxx300' } ]

Thanks!

Body:
I figured out that, if I create the test data without forcing the IDs I want, it works perfectly:

Game.create({name: 'game1'}).exec(console.log);

Game.findOne({name: 'game1'}, function (err, game){
 Map.create({
   name: 'map1',
   game: game.id
 }).exec(console.log);
});

now I can get the owner data.

Since it works when I use the mongoDB ids, I believe it is some issue related to the connector.

Map.find().populate("game").exec(console.log)
//returns (ommited the original IDs)
 [ { game:
    { name: 'game1',  id: 'xxx100' },
      name: 'map1',
      id: 'xxx300'
     }
 ]


问:
Registration page with PHP & MySQL
I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?</p>

```<code><?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
    registerUser();
}
function registerUser() {
    $query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
    VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
    $run = mysqli_query($query);
    if ($run) {
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['user'] = $_POST['email'];
        header('Location: http://localhost/homepage.php');
    } else {
        echo 'Error';
    }
}
?>
</code>```

答:
The problem is you are using single quotes-inside single-quotes. For instance '{$_POST['first_name']}' is read as {$_POST[ being one thing first_name as a SQL variable and ]} another string.

Try the following

```<code>...

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];

$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())";
</code>```

...

Title: Registration page with PHP & MySQL

Body:
I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?

<?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
    registerUser();
}
function registerUser() {
    $query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
    VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
    $run = mysqli_query($query);
    if ($run) {
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['user'] = $_POST['email'];
        header('Location: http://localhost/homepage.php');
    } else {
        echo 'Error';
    }
}
?>

Body:
The problem is you are using single quotes-inside single-quotes. For instance '{$_POST['first_name']}' is read as {$_POST[ being one thing first_name as a SQL variable and ]} another string.

Try the following

...

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];

$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())";

...


问:
I have text file with a 2D matrix in it. How do turn this into a grey scale image in python?
I'm fairly new with python so I'm not really sure where to start. All I have done is I imported the text file to python. I was suggested to use matshow.py but I don't know how I would use the text file to create the actual image.</p>

答:
What exactly are you trying to achieve, your point isn't clear.

if you are trying to draw an image using a matrix.

you will need to look into PIL.

Here is the link to download the library and here is the link for the documentations.


问:
How to Preserve aspect ratio of a button image .net
I'm trying to re-size an image of the Button control while preserving the aspect ratio from the original image so the new image doesn't look squashed/stretched.

And when i again get it back to the original position (Normal Window Maximized state) it should retain its original resolution.

Basically i want the images in all of monitor resolutions to look the same.

For ex: In my application,
An image of a Globe looks fine with the monitor resolution 1280 * 1024 (5:4)
but looks stretched like an ellipse with the monitor resolution 1920×1080 (16:9)

I know i have to do some form of transformation programatically, but am not getting how to do it. I tried calling the below method on OnResize event, though it works for the first iteration, the images gets smaller on subsequent resizing and finally i lose my image finally.

public Rectangle MaintainAspectRatio(Image imgPhoto, Rectangle thumbRect)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

```<code>    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
    nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

    //if we have to pad the height pad both the top and the bottom
    //with the difference between the scaled height and the desired height
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = (int)((thumbRect.Width - (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = (int)((thumbRect.Height - (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
    return retRect;
}
</code>```

I use this code in my overriden OnPaint eventhandler method as :

protected override void  OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Graphics g = e.Graphics;

```<code>     int iHeight;
     int iWidth;

     if (Image != null)
     {
         Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
         iHeight = ResizedRectangle.Height;
         iWidth = ResizedRectangle.Width;

     }
     else
     {
         iWidth = ClientRectangle.Width;
         iHeight = ClientRectangle.Height;
     }

     // Draw border
     Color oLeftTopColor = SystemColors.ControlLightLight;
     Color oRightBottomColor = SystemColors.ActiveCaption;
     Pen oLeftTopPen = new Pen(oLeftTopColor);
     Pen oRightBottomPen = new Pen(oRightBottomColor);
     // top line
     g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
     //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
     // bottom line
     g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
     //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
     // right line
     g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
     // left line
     g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

     // Draw image
     if (Image != null)
     {

         Rectangle oDrawRectagle = new Rectangle(
            0, 0, iWidth, iHeight);
         if (Enabled == false)
         {
             e.Graphics.DrawImage(Image, oDrawRectagle,
                0, 0, Image.Width, Image.Height,
                GraphicsUnit.Pixel);
         }
         else
         {
             e.Graphics.DrawImage(Image, oDrawRectagle);

         }
     }

     // Draw text
     if (Text != null)
     {
         int iTextTop = 5;
         int iTextLeft = 5;
         int iMaxTextWidth = iWidth - 10;
         int iMaxTextHeight = iHeight - 10;
     }
}
</code>```

Can anyone guide me how should i proceed with this ?

答:
I tried calling the below method on
  OnResize event, though it works for
  the first iteration, the images gets
  smaller on subsequent resizing and
  finally i lose my image finally.

I think you should use the DisplaySettingsChanged instead of OnResize event, it will trigger only when resolution is changed.

Body:
I'm trying to re-size an image of the Button control while preserving the aspect ratio from the original image so the new image doesn't look squashed/stretched.

And when i again get it back to the original position (Normal Window Maximized state) it should retain its original resolution.

Basically i want the images in all of monitor resolutions to look the same.

For ex: In my application,
An image of a Globe looks fine with the monitor resolution 1280 * 1024 (5:4)
but looks stretched like an ellipse with the monitor resolution 1920×1080 (16:9)

I know i have to do some form of transformation programatically, but am not getting how to do it. I tried calling the below method on OnResize event, though it works for the first iteration, the images gets smaller on subsequent resizing and finally i lose my image finally.

public Rectangle MaintainAspectRatio(Image imgPhoto, Rectangle thumbRect)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
    nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

    //if we have to pad the height pad both the top and the bottom
    //with the difference between the scaled height and the desired height
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = (int)((thumbRect.Width - (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = (int)((thumbRect.Height - (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
    return retRect;
}

I use this code in my overriden OnPaint eventhandler method as :

protected override void  OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Graphics g = e.Graphics;

     int iHeight;
     int iWidth;

     if (Image != null)
     {
         Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
         iHeight = ResizedRectangle.Height;
         iWidth = ResizedRectangle.Width;

     }
     else
     {
         iWidth = ClientRectangle.Width;
         iHeight = ClientRectangle.Height;
     }

     // Draw border
     Color oLeftTopColor = SystemColors.ControlLightLight;
     Color oRightBottomColor = SystemColors.ActiveCaption;
     Pen oLeftTopPen = new Pen(oLeftTopColor);
     Pen oRightBottomPen = new Pen(oRightBottomColor);
     // top line
     g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
     //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
     // bottom line
     g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
     //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
     // right line
     g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
     // left line
     g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

     // Draw image
     if (Image != null)
     {

         Rectangle oDrawRectagle = new Rectangle(
            0, 0, iWidth, iHeight);
         if (Enabled == false)
         {
             e.Graphics.DrawImage(Image, oDrawRectagle,
                0, 0, Image.Width, Image.Height,
                GraphicsUnit.Pixel);
         }
         else
         {
             e.Graphics.DrawImage(Image, oDrawRectagle);

         }
     }

     // Draw text
     if (Text != null)
     {
         int iTextTop = 5;
         int iTextLeft = 5;
         int iMaxTextWidth = iWidth - 10;
         int iMaxTextHeight = iHeight - 10;
     }
}

Can anyone guide me how should i proceed with this ?


问:
From an Ansible inventory file, is it possible to include variables from another file?
My Ansible hosts file:

```<code>mybox.mydomain.com ansible_ssh_pass={{mypassword}}
</code>```

The variable 'mypassword' is defined in a file "variables.yml":

```<code>mypassword = somepassword
</code>```

Is there a way I can include the variables from "variables.yml" in my hosts file?  Otherwise when I try to run some Ansible command, I get the error

```<code>the field 'password' has an invalid value, which appears to include a variable that is undefined. The error was: 'mypassword' is undefined
</code>```

I'm asking this because ultimately I want to use a Vault encrypted variable from a .yml file (since that is the only way Vault encrypts individual variables)

答:
Put variables.yml into group_vars/all/variables.yml near your inventory.

This will load everything in variables.yml as group variables for every host in your inventory.

Body:
My Ansible hosts file:

mybox.mydomain.com ansible_ssh_pass={{mypassword}}

The variable 'mypassword' is defined in a file "variables.yml":

mypassword = somepassword

Is there a way I can include the variables from "variables.yml" in my hosts file?  Otherwise when I try to run some Ansible command, I get the error

the field 'password' has an invalid value, which appears to include a variable that is undefined. The error was: 'mypassword' is undefined

I'm asking this because ultimately I want to use a Vault encrypted variable from a .yml file (since that is the only way Vault encrypts individual variables)


问:
Wildfly 9 - Want to expose 1 app to internet and another to intranet
Im working on Wildfly 9 and want to expose 1 app to intranet 10.x.x.x and another to Internet on 200.x.x.x

The question is how you do this in standalone.xml?

Thanks.

答:
While this may not be the answer you want I've done what you're trying to do by fronting Wildfly with Apache.  If you take a look at the IP based virtual host docs, you can have Apache handle the virtual host switch.  Basically your Apache .conf file will have something like:

```<code><VirtualHost 10.x.x.x:80>
    ServerName internal.host.name

    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/internal-app
    ProxyTimeout 360
</VirtualHost>

<VirtualHost 200.x.x.x:80>
    ServerName external.host.name

    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/external-app
    ProxyTimeout 360
</VirtualHost>
</code>```

This is using HTTP proxying - AJP may be a bit faster but I've always found the HTTP version easier to implement and maintain.

Again, the downside is that this requires another package to setup and maintain.  Apache is extreamly well supported in the community but that may not help if you're the one doing the work.

Note that this requires the proxy and proxy_http Apache modules to be enabled.  If you go this route, let me know you O/S and I can tell you how to enable them.

Body:
While this may not be the answer you want I've done what you're trying to do by fronting Wildfly with Apache.  If you take a look at the IP based virtual host docs, you can have Apache handle the virtual host switch.  Basically your Apache .conf file will have something like:

<VirtualHost 10.x.x.x:80>
    ServerName internal.host.name

    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/internal-app
    ProxyTimeout 360
</VirtualHost>

<VirtualHost 200.x.x.x:80>
    ServerName external.host.name

    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/external-app
    ProxyTimeout 360
</VirtualHost>

This is using HTTP proxying - AJP may be a bit faster but I've always found the HTTP version easier to implement and maintain.

Again, the downside is that this requires another package to setup and maintain.  Apache is extreamly well supported in the community but that may not help if you're the one doing the work.

Note that this requires the proxy and proxy_http Apache modules to be enabled.  If you go this route, let me know you O/S and I can tell you how to enable them.


问:
View controller after transition is fitting its contraints to size class instead of device
First of all, I followed this tutorial: https://www.youtube.com/watch?v=B9sH_VxPPo4 and then I used this transition in a real project where I work, but since then I am facing a problem with it. A problem that I can't quite understand why it is happening. Perhaps you could help me out.

What's happening is the following: I'm making a tutorial for my app using this transition. In the view controller where I set the text for the tutorial, I set constraints for top, bottom, leading and trailing to 0. Thus, it should fit the view controller to the edges, right? But it only happens when I have chosen in size class the same device that I am using in the simulator. For instance, I must run an iPhone 7 plus simulator AND set the size classe to iPhone 7 plus in order to work properly. When I run the simulator of iPhone 7 without having changed anything in interface builder, It crashes. I realized that the view controller is not fitting to the edges of the device (simulated or physical), it's fitting to the edges of the size class. I realized that when I comment the lines with ".transitioningDelegate = self and .modalPresentationStyle = .custom" it works as it should (but without the transitioning, of course). I thought it could be a problem with this transition. Can you help me out?

Here goes a snippet of the code I'm using to present the view controller using this transition:

```<code>let levelTutorial = CPQuizLevelTutorialViewController()
levelTutorial.transitioningDelegate = self
levelTutorial.modalPresentationStyle = .custom
self.present(levelTutorial, animated: true, completion: nil)
</code>```

Here goes another part of my code where I implement the UIViewControllerTransitioningDelegate:

```<code>extension CPMainQuizViewController: UIViewControllerTransitioningDelegate {

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.transitionMode = .dismiss
        transition.startingPoint = self.view.center
        transition.circleColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha:0.6)

        return transition
    }

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.transitionMode = .present
        transition.startingPoint = self.view.center
        transition.circleColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha:0.6)

        return transition
    }
}
</code>```

I don't know if it has something related to the error, but I'm using xib instead of Storyboard. One thing I do know it's related to the bug is that I'm pretty new to iOS development. So, first of all, sorry if I said something stupid. LOL

Thanks in advance, guys!

答:
Well, I found a workaround for this.

I added this line of code in every view controller I was having this problem:

```<code>self.view.frame.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
</code>```

After have done it, screens behave perfectly adjusting its edges to the smartphone edges. :D

I still don't know what caused this error. So, if anyone has any ideas about it, share with us. :D

Body:
First of all, I followed this tutorial: https://www.youtube.com/watch?v=B9sH_VxPPo4 and then I used this transition in a real project where I work, but since then I am facing a problem with it. A problem that I can't quite understand why it is happening. Perhaps you could help me out.

What's happening is the following: I'm making a tutorial for my app using this transition. In the view controller where I set the text for the tutorial, I set constraints for top, bottom, leading and trailing to 0. Thus, it should fit the view controller to the edges, right? But it only happens when I have chosen in size class the same device that I am using in the simulator. For instance, I must run an iPhone 7 plus simulator AND set the size classe to iPhone 7 plus in order to work properly. When I run the simulator of iPhone 7 without having changed anything in interface builder, It crashes. I realized that the view controller is not fitting to the edges of the device (simulated or physical), it's fitting to the edges of the size class. I realized that when I comment the lines with ".transitioningDelegate = self and .modalPresentationStyle = .custom" it works as it should (but without the transitioning, of course). I thought it could be a problem with this transition. Can you help me out?

Here goes a snippet of the code I'm using to present the view controller using this transition:

let levelTutorial = CPQuizLevelTutorialViewController()
levelTutorial.transitioningDelegate = self
levelTutorial.modalPresentationStyle = .custom
self.present(levelTutorial, animated: true, completion: nil)

Here goes another part of my code where I implement the UIViewControllerTransitioningDelegate:

extension CPMainQuizViewController: UIViewControllerTransitioningDelegate {

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.transitionMode = .dismiss
        transition.startingPoint = self.view.center
        transition.circleColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha:0.6)

        return transition
    }

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.transitionMode = .present
        transition.startingPoint = self.view.center
        transition.circleColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha:0.6)

        return transition
    }
}

I don't know if it has something related to the error, but I'm using xib instead of Storyboard. One thing I do know it's related to the bug is that I'm pretty new to iOS development. So, first of all, sorry if I said something stupid. LOL

Thanks in advance, guys!

Body:
Well, I found a workaround for this.

I added this line of code in every view controller I was having this problem:

self.view.frame.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

After have done it, screens behave perfectly adjusting its edges to the smartphone edges. :D

I still don't know what caused this error. So, if anyone has any ideas about it, share with us. :D


问:
PHP MYSQL. How to retrieve the same data from a table based on 2 different ID's in another table
I'm building a website for Airplane Tickets, i have 2 tables, AIRPORTS and AIRPLANES, the AIRPLANES table has 2 columns containing its airport destination id(ID_DESTINATION) and its airport origin id(ID_ORIGIN), what i want to do is to loop all of the AIRPLANES using while with the AIRPORT_NAME as its origin and destination from the AIRPORTS table, how can i do that?

this is the query i'm using :

```<code>SELECT a.ID_PLANE, a.PLANE_NAME,
       a.ID_ORIGIN, a.ID_DESTINATION,
       a.TAKEOFF, a.LANDING, a.PRICE,
       b.ID_AIRPORT, b.AIRPORT_NAME
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS b
ON a.ID_ORIGIN = b.ID_AIRPORT
</code>```

Thanks in advance.

答:
Notice I aliased O for origin D for destination
Assuming you just want the names of airports for each airplane (flight)</p>

```<code>SELECT a.ID_PLANE
     , a.PLANE_NAME
     , a.ID_ORIGIN
     , a.ID_DESTINATION
     , a.TAKEOFF
     , a.LANDING
     , a.PRICE
     , o.ID_AIRPORT as Orig_ID
     , o.AIRPORT_NAME Orig_Name
     , d.ID_AIRPORT as Dest_ID
     , d.AIRPORT_NAME Dest_Name
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS o
  ON a.ID_ORIGIN = b.ID_AIRPORT
LEFT JOIN AIRPORTS d
  ON a.ID_DESTINATION = b.ID_AIRPORT
</code>```

Body:
I'm building a website for Airplane Tickets, i have 2 tables, AIRPORTS and AIRPLANES, the AIRPLANES table has 2 columns containing its airport destination id(ID_DESTINATION) and its airport origin id(ID_ORIGIN), what i want to do is to loop all of the AIRPLANES using while with the AIRPORT_NAME as its origin and destination from the AIRPORTS table, how can i do that?

this is the query i'm using :

SELECT a.ID_PLANE, a.PLANE_NAME,
       a.ID_ORIGIN, a.ID_DESTINATION,
       a.TAKEOFF, a.LANDING, a.PRICE,
       b.ID_AIRPORT, b.AIRPORT_NAME
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS b
ON a.ID_ORIGIN = b.ID_AIRPORT

Thanks in advance.

Body:
Notice I aliased O for origin D for destination
Assuming you just want the names of airports for each airplane (flight)

SELECT a.ID_PLANE
     , a.PLANE_NAME
     , a.ID_ORIGIN
     , a.ID_DESTINATION
     , a.TAKEOFF
     , a.LANDING
     , a.PRICE
     , o.ID_AIRPORT as Orig_ID
     , o.AIRPORT_NAME Orig_Name
     , d.ID_AIRPORT as Dest_ID
     , d.AIRPORT_NAME Dest_Name
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS o
  ON a.ID_ORIGIN = b.ID_AIRPORT
LEFT JOIN AIRPORTS d
  ON a.ID_DESTINATION = b.ID_AIRPORT


问:
Graph theory - learn cost function to find optimal path
This is a supervised learning problem.

I have a directed acyclic graph (DAG). Each edge has a vector of features X, and each node (vertex) has a label 0 or 1. The task is to find a cost function w(X), so that the shortest path between any pair of nodes has the highest ratio of 1s to 0s (minimum classification error).

The solution must generalize well. I tried logistic regression, and the learned logistic function predicts fairly well the label of a node giving the features of a incoming edge. However, the graph's topology is not taken into account by that approach, so the solution in the whole graph is non-optimal. In other words, the logistic function is not a good weight function given the problem setup above.

Although my problem setup is not the typical binary classification problem setup, here is a good intro to it:
http://en.wikipedia.org/wiki/Supervised_learning#How_supervised_learning_algorithms_work

Here are some more details:

Each feature vector X is a d-dimensional list of real numbers.

Each edge has a vector of features. That is, given the set of edges E = {e1, e2, .. en} and set of feature vectors F = {X1, X2 ... Xn}, then edge ei is associated to vector Xi.

It is possible to come up with a function f(X), so that f(Xi)
gives the likelihood that edge ei points to a node labeled with a 1.
An example of such function is the one I mentioned above, found through logistic
regression. However, as I mentioned above, such function is non-optimal.

SO THE QUESTION IS:
Given the graph, a starting node and an finish node, how do I learn the optimal cost function w(X), so that the ratio of nodes 1s to 0s is maximized (minimum classification error)?

答: I believe your question is very close to the field of Inverse Reinforcement Learning, where you take certain "expert demonstrations" of optimal paths and try to learn a cost function such that your planner (A* or some reinforcement learning agent) outputs the same path as the expert demonstration. This training is done in an iterative way. I think that in your case, the expert demonstrations could be created by you to be paths that go through maximum number of 1 labelled edges. Here is a link to a good paper on the same: Learning to Search: Functional Gradient Techniques for Imitation Learning. It is from the robotics community where motion planning is usually setup as a graph-search problem and learning cost functions is essential for demonstrating desired behavior.</p>


问:
How do I assign embedded interface to object in golang
I am attempting to assign an array of structs of type Baz to an array of interfaces of type Bar embedded in a second struct of type Foo. I have not been able to find the exact information here or elsewhere googling. I have provided a minimum working example.

I get the following error:

$ go run main.go

./main.go:38: cannot use baz (type []*Baz) as type []Bar in argument to NewFoo

My apologies if my code is not idiomatic go and also if I have not confirmed exactly to standards for posting questions, this is my first post.

```<code>package main

import (
    "fmt"
)
type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int{
    return baz.a * baz.b
}

func NewFoo(bar []Bar) *Foo{
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {

    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}
</code>```

UPDATE: I approved the duplicate vote after further reading and understanding the suggested related posts. Thank you to those who pointed me in that direction. For future interested readers, my final implementation consistent with my use case is as follows:

```<code>package main

import (
    "fmt"
)

type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface { //
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo{
    f := &Foo{}
    f.b = make([]Bar, 2)
    fmt.Println("len(bar) ", len(bar), "len(f.b)", len(f.b) )
    for i, _ := range f.b {
        f.b[i] = bar[i]

    }
    return f
}

func MakeBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = NewBaz(1, 2)
    bazes[1] = NewBaz(3, 4)
    return bazes
}

func NewBaz(aa, bb int) *Baz {
    return &Baz{a: aa, b: bb}
}

func main() {
    baz := MakeBaz()
    foo := NewFoo(baz)
    fmt.Printf("%v\n", foo)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}
</code>```

答:
The error you are getting:

cannot use baz (type []*Baz) as type []Bar

Is because Go won't let you assign an array of Baz to an array of Bar, even when it'd let you assign a Baz to a Bar variable.

To see this in a more simple form, this works fine:

```<code>var oneBaz *Baz = &Baz{a: 1, b: 2}
var oneBar Bar = oneBaz
</code>```

Because the type Baz satisfies the Bar interface and you can assign a Baz object to a Bar variable.

But this does not work (even if it'd looks like it could work):

```<code>var bazArray []*Baz = make([]*Baz, 2)
var barArray []Bar = bazArray
</code>```

It will throw the same error you are seeing.

In order to make this work, you'd probably need to implement one of the solutions listed in this related question:

Type converting slices of interfaces in go

Body:
I am attempting to assign an array of structs of type Baz to an array of interfaces of type Bar embedded in a second struct of type Foo. I have not been able to find the exact information here or elsewhere googling. I have provided a minimum working example.

I get the following error:

$ go run main.go

./main.go:38: cannot use baz (type []*Baz) as type []Bar in argument to NewFoo

My apologies if my code is not idiomatic go and also if I have not confirmed exactly to standards for posting questions, this is my first post.

package main

import (
    "fmt"
)
type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int{
    return baz.a * baz.b
}

func NewFoo(bar []Bar) *Foo{
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {

    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}

UPDATE: I approved the duplicate vote after further reading and understanding the suggested related posts. Thank you to those who pointed me in that direction. For future interested readers, my final implementation consistent with my use case is as follows:

package main

import (
    "fmt"
)

type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface { //
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo{
    f := &Foo{}
    f.b = make([]Bar, 2)
    fmt.Println("len(bar) ", len(bar), "len(f.b)", len(f.b) )
    for i, _ := range f.b {
        f.b[i] = bar[i]

    }
    return f
}

func MakeBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = NewBaz(1, 2)
    bazes[1] = NewBaz(3, 4)
    return bazes
}

func NewBaz(aa, bb int) *Baz {
    return &Baz{a: aa, b: bb}
}

func main() {
    baz := MakeBaz()
    foo := NewFoo(baz)
    fmt.Printf("%v\n", foo)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}

Body:
The error you are getting:

cannot use baz (type []*Baz) as type []Bar

Is because Go won't let you assign an array of Baz to an array of Bar, even when it'd let you assign a Baz to a Bar variable.

To see this in a more simple form, this works fine:

var oneBaz *Baz = &Baz{a: 1, b: 2}
var oneBar Bar = oneBaz

Because the type Baz satisfies the Bar interface and you can assign a Baz object to a Bar variable.

But this does not work (even if it'd looks like it could work):

var bazArray []*Baz = make([]*Baz, 2)
var barArray []Bar = bazArray

It will throw the same error you are seeing.

In order to make this work, you'd probably need to implement one of the solutions listed in this related question:

Type converting slices of interfaces in go


问:
Session is null in PreRequestHandlerExecute
In my ASP.NET 4.0 application, I've got an event handler for PreRequestHandlerExecute in global.asax.cs.

I want to access data in the Session. Most times, the session is defined, but sometimes it is null. Can somebody explain me when it is initialized and when it is not?

答: The session is not loaded for every type of request by default.  If the request is for a content file (like an image or stylesheet), then the session is not loaded.  This done in order to reduce the overhead of processing a request.  If working in the Generic Handler (.ashx) and you want access to the session, then have the handler implement IRequiresSessionState.</p>


问:
Android Studio: I am trying to wire a button to a toast but there is an error with the callback method
```<code>package com.example.chris.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        public void buttonWasClicked(View button) {
        Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

<p>//The buttonWasClicked is not red but greyed out in the editor, and the editor shows an error that buttonWasClicked has not been used before. I'm not sure why, I thought this was how I define a callback method. </p>

答:
Your method is inside the onCreate() method, that's why. Move it outside onCreate() to be able to call it.

Try this:

```<code>package com.example.chris.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.my_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonWasClicked(view);
            }
        });
    }
    public void buttonWasClicked(View button) {
        Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
package com.example.chris.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        public void buttonWasClicked(View button) {
        Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
        }
    }
}

//The buttonWasClicked is not red but greyed out in the editor, and the editor shows an error that buttonWasClicked has not been used before. I'm not sure why, I thought this was how I define a callback method.

Body:
Your method is inside the onCreate() method, that's why. Move it outside onCreate() to be able to call it.

Try this:

package com.example.chris.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.my_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonWasClicked(view);
            }
        });
    }
    public void buttonWasClicked(View button) {
        Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
    }
}


问:
Having a single default argument in a controller action expecting multiple
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

```<code>[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}
</code>```

Here is the route I attempted but was not successful (RouteConfig.cs):

```<code>routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });
</code>```

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.

答:
Sounds like you try to pass null as an int32, that will not work. In c# int32 is  a value type, not a reference. You could use nullable int32, but reading your question it sounds like you were expecting something different then an int32.

Add some code, and you will get help!

Body:
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}

Here is the route I attempted but was not successful (RouteConfig.cs):

routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.