问:
async_write_some callback not called after delay
My callback for async_write_some is not called after a one second sleep.  If I am starting an io_service worker thread for every write, why is the callback not being called?

header

```<code>boost::system::error_code error_1;
boost::shared_ptr <boost::asio::io_service> io_service_1;
boost::shared_ptr <boost::asio::ip::tcp::socket> socket_1;
</code>```

connect

```<code>void eth_socket::open_eth_socket (void)
{
    // 1. reset io services
    io_service_1.reset();
    io_service_1 = boost::make_shared <boost::asio::io_service> ();

    // 2. create endpoint
    boost::asio::ip::tcp::endpoint remote_endpoint(
        boost::asio::ip::address::from_string("10.0.0.3"),
        socket_1_port
    );

    // 3. reset socket
    socket_1.reset(new boost::asio::ip::tcp::socket(*io_service_1));

    // 4. connect socket
    socket_1->async_connect(remote_endpoint,
        boost::bind(
            &eth_socket::socket_1_connect_callback,
            this, boost::asio::placeholders::error
        )
    );

    // 5. start io_service_1 run thread after giving it work
    boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));
    return;
}
</code>```

write

```<code>void eth_socket::write_data (std::string data)
{
    // 1. check socket status
    if (!socket_1->is_open())
    {
        WARNING << "socket_1 is not open";
        throw -3;
    }

    // 2. start asynchronous write
    socket_1->async_write_some(
        boost::asio::buffer(data.c_str(), data.size()),
        boost::bind(
            &eth_socket::socket_1_write_data_callback,
            this, boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred
        )
    );

    // 3. start io_service_1 run thread after giving it work
    boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));
    return;
}
</code>```

callback

```<code>void eth_socket::socket_1_write_data_callback (const boost::system::error_code& error, size_t bytes_transferred)
{
    // 1. check for errors
    if (error)
    {
        ERROR << "error.message() >> " << error.message().c_str();
        return;
    }
    if (socket_1.get() == NULL || !socket_1->is_open())
    {
        WARNING << "serial_port_1 is not open";
        return;
    }
    INFO << "data written to 10.0.0.3:1337 succeeded; bytes_transferred = " << bytes_transferred;
    return;
}
</code>```

test

```<code>open_eth_socket();
write_data("Hello");    // callback called
write_data("Hello");    // callback called
write_data("Hello");    // callback called
sleep(1);
write_data("Hello");    // callback not called after sleep
</code>```

答:
```<code>boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));
</code>```

That's weird for a number of reasons.

You should not "run" io_services for each operation. Instead, run them steadily while operations may be posted. Optionally use io_service::work to prevent run from returning.

You should not (have to) create threads for each operation. If anything, it's recipe for synchronization issues (Why do I need strand per connection when using boost::asio?)

When running io_service again after it returned (without error) you should call reset() first, as per documentation (Why must io_service::reset() be called?)

You destruct a non-detached thread - likely before it had completed. If you had used std::thread this would even have caused immediate abnormal program termination. It's bad practice to not-join non-detached threads (and I'd add it's iffy to use detached threads without explicit synchronization on thread termination). See Why is destructor of boost::thread detaching joinable thread instead of calling terminate() as standard suggests?

I'd add to these top-level concerns

the smell from using names like socket_1 (just call it socket_ and instantiate another object with a descriptive name to contain the other socket_). I'm not sure, but the question does raise suspicion these might even be global variables. (I hope that's not the case)

throw-ing raw integers, really?

You are risking full on data-races by destructing io_service while never checking that worker threads had completed.

More Undefined Behaviour here:

```<code>_sock.async_write_some(
        ba::buffer(data.c_str(), data.size()),
</code>```

You pass a reference to the parameter data which goes out of scope. When the async operation completes, it will be a dangling reference

There's some obvious copy/paste trouble going on here:

```<code>if (socket_1.get() == NULL || !socket_1->is_open())
{
    WARNING << "serial_port_1 is not open";
    return;
}
</code>```

I'd actually say this stems from precisely the same source that lead to the variable names being serial_port_1 and socket_1

Some Cleanup

Simplify. There wasn't self-contained code, so nothing complete here, but at least see the many points of simplification:

Live On Coliru

```<code>#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>

namespace ba = boost::asio;
using ba::ip::tcp;
using boost::system::error_code;

#define ERROR   std::cerr
#define WARNING std::cerr
#define INFO    std::cerr

struct eth_socket {

    ~eth_socket() {
        _work.reset();
        if (_worker.joinable())
            _worker.join(); // wait
    }

    void open(std::string address);
    void write_data(std::string data);

  private:
    void connected(error_code error) {
        if (error)
            ERROR << "Connect failed: " << error << "\n";
        else
            INFO << "Connected to " << _sock.remote_endpoint() << "\n";
    }
    void written(error_code error, size_t bytes_transferred);

  private:
    ba::io_service _svc;
    boost::optional<ba::io_service::work> _work{ _svc };
    boost::thread _worker{ [this] { _svc.run(); } };

    std::string _data;

    unsigned short _port = 6767;
    tcp::socket _sock{ _svc };
};

void eth_socket::open(std::string address) {
    tcp::endpoint remote_endpoint(ba::ip::address::from_string(address), _port);

    _sock.async_connect(remote_endpoint, boost::bind(&eth_socket::connected, this, _1));
}

void eth_socket::write_data(std::string data) {
    _data = data;

    _sock.async_write_some(ba::buffer(_data), boost::bind(&eth_socket::written, this, _1, _2));
}

void eth_socket::written(error_code error, size_t bytes_transferred) {
    INFO << "data written to " << _sock.remote_endpoint() << " " << error.message() << ";"
         << "bytes_transferred = " << bytes_transferred << "\n";
}

int main() {
    {
        eth_socket s;
        s.open("127.0.0.1");

        s.write_data("Hello"); // callback called
        s.write_data("Hello"); // callback called
        s.write_data("Hello"); // callback called
        boost::this_thread::sleep_for(boost::chrono::seconds(1));
        s.write_data("Hello"); // callback not called after sleep

    } // orderly worker thread join here
}
</code>```

Body:
My callback for async_write_some is not called after a one second sleep.  If I am starting an io_service worker thread for every write, why is the callback not being called?

header

boost::system::error_code error_1;
boost::shared_ptr <boost::asio::io_service> io_service_1;
boost::shared_ptr <boost::asio::ip::tcp::socket> socket_1;

connect

void eth_socket::open_eth_socket (void)
{
    // 1. reset io services
    io_service_1.reset();
    io_service_1 = boost::make_shared <boost::asio::io_service> ();

    // 2. create endpoint
    boost::asio::ip::tcp::endpoint remote_endpoint(
        boost::asio::ip::address::from_string("10.0.0.3"),
        socket_1_port
    );

    // 3. reset socket
    socket_1.reset(new boost::asio::ip::tcp::socket(*io_service_1));

    // 4. connect socket
    socket_1->async_connect(remote_endpoint,
        boost::bind(
            &eth_socket::socket_1_connect_callback,
            this, boost::asio::placeholders::error
        )
    );

    // 5. start io_service_1 run thread after giving it work
    boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));
    return;
}

write

void eth_socket::write_data (std::string data)
{
    // 1. check socket status
    if (!socket_1->is_open())
    {
        WARNING << "socket_1 is not open";
        throw -3;
    }

    // 2. start asynchronous write
    socket_1->async_write_some(
        boost::asio::buffer(data.c_str(), data.size()),
        boost::bind(
            &eth_socket::socket_1_write_data_callback,
            this, boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred
        )
    );

    // 3. start io_service_1 run thread after giving it work
    boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));
    return;
}

callback

void eth_socket::socket_1_write_data_callback (const boost::system::error_code& error, size_t bytes_transferred)
{
    // 1. check for errors
    if (error)
    {
        ERROR << "error.message() >> " << error.message().c_str();
        return;
    }
    if (socket_1.get() == NULL || !socket_1->is_open())
    {
        WARNING << "serial_port_1 is not open";
        return;
    }
    INFO << "data written to 10.0.0.3:1337 succeeded; bytes_transferred = " << bytes_transferred;
    return;
}

test

open_eth_socket();
write_data("Hello");    // callback called
write_data("Hello");    // callback called
write_data("Hello");    // callback called
sleep(1);
write_data("Hello");    // callback not called after sleep

Body:
boost::thread t(boost::bind(&boost::asio::io_service::run, *&io_service_1));

That's weird for a number of reasons.

You should not "run" io_services for each operation. Instead, run them steadily while operations may be posted. Optionally use io_service::work to prevent run from returning.

You should not (have to) create threads for each operation. If anything, it's recipe for synchronization issues (Why do I need strand per connection when using boost::asio?)

When running io_service again after it returned (without error) you should call reset() first, as per documentation (Why must io_service::reset() be called?)

You destruct a non-detached thread - likely before it had completed. If you had used std::thread this would even have caused immediate abnormal program termination. It's bad practice to not-join non-detached threads (and I'd add it's iffy to use detached threads without explicit synchronization on thread termination). See Why is destructor of boost::thread detaching joinable thread instead of calling terminate() as standard suggests?

I'd add to these top-level concerns

the smell from using names like socket_1 (just call it socket_ and instantiate another object with a descriptive name to contain the other socket_). I'm not sure, but the question does raise suspicion these might even be global variables. (I hope that's not the case)

throw-ing raw integers, really?

You are risking full on data-races by destructing io_service while never checking that worker threads had completed.

More Undefined Behaviour here:

_sock.async_write_some(
        ba::buffer(data.c_str(), data.size()),

You pass a reference to the parameter data which goes out of scope. When the async operation completes, it will be a dangling reference

There's some obvious copy/paste trouble going on here:

if (socket_1.get() == NULL || !socket_1->is_open())
{
    WARNING << "serial_port_1 is not open";
    return;
}

I'd actually say this stems from precisely the same source that lead to the variable names being serial_port_1 and socket_1

Some Cleanup

Simplify. There wasn't self-contained code, so nothing complete here, but at least see the many points of simplification:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>

namespace ba = boost::asio;
using ba::ip::tcp;
using boost::system::error_code;

#define ERROR   std::cerr
#define WARNING std::cerr
#define INFO    std::cerr

struct eth_socket {

    ~eth_socket() {
        _work.reset();
        if (_worker.joinable())
            _worker.join(); // wait
    }

    void open(std::string address);
    void write_data(std::string data);

  private:
    void connected(error_code error) {
        if (error)
            ERROR << "Connect failed: " << error << "\n";
        else
            INFO << "Connected to " << _sock.remote_endpoint() << "\n";
    }
    void written(error_code error, size_t bytes_transferred);

  private:
    ba::io_service _svc;
    boost::optional<ba::io_service::work> _work{ _svc };
    boost::thread _worker{ [this] { _svc.run(); } };

    std::string _data;

    unsigned short _port = 6767;
    tcp::socket _sock{ _svc };
};

void eth_socket::open(std::string address) {
    tcp::endpoint remote_endpoint(ba::ip::address::from_string(address), _port);

    _sock.async_connect(remote_endpoint, boost::bind(&eth_socket::connected, this, _1));
}

void eth_socket::write_data(std::string data) {
    _data = data;

    _sock.async_write_some(ba::buffer(_data), boost::bind(&eth_socket::written, this, _1, _2));
}

void eth_socket::written(error_code error, size_t bytes_transferred) {
    INFO << "data written to " << _sock.remote_endpoint() << " " << error.message() << ";"
         << "bytes_transferred = " << bytes_transferred << "\n";
}

int main() {
    {
        eth_socket s;
        s.open("127.0.0.1");

        s.write_data("Hello"); // callback called
        s.write_data("Hello"); // callback called
        s.write_data("Hello"); // callback called
        boost::this_thread::sleep_for(boost::chrono::seconds(1));
        s.write_data("Hello"); // callback not called after sleep

    } // orderly worker thread join here
}


来源: stackexchange

问:
how to use cookies in javascript and html?
my question is I took one form like register form and fill al fields like first name, last name,address, check boxes  also used then when submit at final i want it to display those data in new page. Here I want code only in javascript and html. Is their possible please help me........... and send code and guide lines </p>

答: Yes, you could do that with cookies. Along those lines, I suggest using JQuery for your javascript development. JQuery makes cross-browser setting and retrieving cookies very easy.</p>

ContentLicense: CC BY-SA 2.5


问:
SQLite: finding set with specific values
```<code>PEAK (NAME, ELEV, DIFF, MAP, REGION)
CLIMBER (NAME, SEX)
PARTICIPATED (TRIP_ID, NAME)
CLIMBED (TRIP_ID, PEAK, WHEN_CLIMBED)
</code>```

I need to find The peaks that Mark and Mary have climbed

I did this but it doesn't work:

```<code>        select *
        from participated, climbed
        where participated.name="MARY" or "MARK" and participated.trip_id= climbed.trip_id
</code>```

I also tried doing:

```<code>Group By name, peak
Having name="MARY" or "MARK"
</code>```

How would I do this?

答:
If you just want the peak, you can do:

```<code>select c.peak
from climbed c join
     trip t
     on c.trip_id = t.trip_id
where name in ('MARY', 'MARK')
group by c.peak
having count(distinct name) = 2;
</code>```

Note the use of proper JOIN syntax.

ContentLicense: CC BY-SA 3.0

Body:
PEAK (NAME, ELEV, DIFF, MAP, REGION)
CLIMBER (NAME, SEX)
PARTICIPATED (TRIP_ID, NAME)
CLIMBED (TRIP_ID, PEAK, WHEN_CLIMBED)

I need to find The peaks that Mark and Mary have climbed

I did this but it doesn't work:

        select *
        from participated, climbed
        where participated.name="MARY" or "MARK" and participated.trip_id= climbed.trip_id

I also tried doing:

Group By name, peak
Having name="MARY" or "MARK"

How would I do this?

Body:
If you just want the peak, you can do:

select c.peak
from climbed c join
     trip t
     on c.trip_id = t.trip_id
where name in ('MARY', 'MARK')
group by c.peak
having count(distinct name) = 2;

Note the use of proper JOIN syntax.


问:
Hidden Input and AngularJS ng-model binding
I want to use AngularJS to calculate total price for product when I add Quantity. I have a code as below:

```<code><div ng-app="TheApp">
<div ng-controller="TheController">
    <input type="hidden" name="Price" value="100" ng-model="Price" />
    <input type="text" name="Quantity" ng-model="Quantity" />
    Total Price:{{TotalPrice}}
    <button class="btn btn-primary btn-block" ng-click="click()">Add Items</button>
</div>
</code>```

Inside my controller I have:

```<code>    $scope.TotalPrice = $scope.Price * $scope.Quantity;
</code>```

I know Angular does not support hidden but I am looking for the best practice to solve the issue.
Please consider button is not for calculating TotalPrice but sending final result. I want it to be updated real time.

答:
```<code>$scope.price = 10;
</code>```

Use double brackets to capture the scope value.

```<code><input type="hidden" name="Price" value="{{price}}"/>
</code>```

Body:
I want to use AngularJS to calculate total price for product when I add Quantity. I have a code as below:

    <input type="hidden" name="Price" value="100" ng-model="Price" />
    <input type="text" name="Quantity" ng-model="Quantity" />
    Total Price:{{TotalPrice}}
    <button class="btn btn-primary btn-block" ng-click="click()">Add Items</button>

Inside my controller I have:

    $scope.TotalPrice = $scope.Price * $scope.Quantity;

I know Angular does not support hidden but I am looking for the best practice to solve the issue.
Please consider button is not for calculating TotalPrice but sending final result. I want it to be updated real time.

Body:
$scope.price = 10;

Use double brackets to capture the scope value.

<input type="hidden" name="Price" value="{{price}}"/>

ContentLicense: CC BY-SA 4.0


问:
select random data with a nested query?
I have a database table with quite large data. Now i want to get random 4 out of it. What i need is a query that fetches 1000 records from it and then selects random 4 out of these 1000 and gives it as a result. I think it can be done by nested query but have no idea how to do it. Please help me with some example code.</p>

答:
```<code>select * from
(
  select * from your_table
  where some_conditions
  limit 1000
)
as some_aliases
order by rand()
limit 4;
</code>```

Title: select random data with a nested query?


问:
Mysql inner join with multiple tables according to a value
I have to create a database of real state for sale. Problem is the kind of properties: if I have a house, I have a kind of description, but if it is just a land, the descriptions does not need to include number of bathrooms, just the area, front range, etc.

So I did a table with generic data about the element (imoveis) with address, price etc.. Than I created categories of elements (imoveis_categs). I did 5 categories, for each category, there will be a table (e.g.: imoveis_descr2) with the specific features of the kind.

To enter data it's easy, but to list my data, I will need to perform query select to find those elements according with some filters. In PHP will be easy to solve, but I am wondering about the performance for a large amount of data and users requests. Better solve it by SQL commands, thought. But mySQL is not my area, I imagine something like this to start...

```<code> SELECT * FROM imoveis INNER JOIN imoveis_descr(imoveis.categ) ...
</code>```

The "categ" field of imoveis point to the right description table. It is possible to do something like this? Is there another way more appropriate or efficient to do it?

EDIT: I tryed to clarify with an example...
EDIT2: I corrected the example, the column "rooms" will be the same. The fields are not exclusives, both apartment and house categories have number of rooms.

```<code>Table imoveis
id  categ   title            price       address ...
1   2       The House        $ 1000000   Somestreet 77
2   1       An Appartment    $ 500000    Somewhere 11
3   4       A Land           $ 250000    Nowhere 33

Table imoveis_descr1
idImovel    rooms   area    floor   ...
2           2       70      5

Table imoveis_descr2
idImovel    rooms fieldArea   constrArea ...
1           3      120        80

Table imoveis_descr4
idImovel    area    width   height ...
3           2640    22      120

Result
id   categ    title       price     address   rooms fieldArea  constrArea    area    floor        area   width  height
1      2     The House    $ 1000000 Somestreet 77   3   120 80  null    null    null    null    null
2   1   An Appartment   $ 500000    Somewhere 11    2   null    null    70  5   null    null    null
3   4   A Land  $ 250000    Nowhere 33  null    null    null    null    null    2640    22  120
</code>```

答:
Some of your field-names are duplicated in your results (e.g. "rooms"), wouldn't it be better to merge those fields with COALESCE (as they appear mutually exclusive)?

As the tables your refer to are mutually exclusive, you will never get the required results with an INNER JOIN, you'll need an OUTER JOIN:

```<code>SELECT
      i.id,
      i.categ,
      i.title,
      i.price,
      i.address,
      COALESCE(i1.rooms, i2.rooms) AS rooms,
      i2.fieldArea,
      i2.constrArea
      COALESCE(i1.area, i3.area, ...) AS area,
      ...
FROM  imoveis AS i
      LEFT OUTER JOIN imoveis_descr1 AS i1 ON i1.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr2 AS i2 ON i2.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr3 AS i3 ON i3.idImovel = i.id
      ...
</code>```

Body:
I have to create a database of real state for sale. Problem is the kind of properties: if I have a house, I have a kind of description, but if it is just a land, the descriptions does not need to include number of bathrooms, just the area, front range, etc.

So I did a table with generic data about the element (imoveis) with address, price etc.. Than I created categories of elements (imoveis_categs). I did 5 categories, for each category, there will be a table (e.g.: imoveis_descr2) with the specific features of the kind.

To enter data it's easy, but to list my data, I will need to perform query select to find those elements according with some filters. In PHP will be easy to solve, but I am wondering about the performance for a large amount of data and users requests. Better solve it by SQL commands, thought. But mySQL is not my area, I imagine something like this to start...

 SELECT * FROM imoveis INNER JOIN imoveis_descr(imoveis.categ) ...

The "categ" field of imoveis point to the right description table. It is possible to do something like this? Is there another way more appropriate or efficient to do it?

EDIT: I tryed to clarify with an example...
EDIT2: I corrected the example, the column "rooms" will be the same. The fields are not exclusives, both apartment and house categories have number of rooms.

Table imoveis
id  categ   title            price       address ...
1   2       The House        $ 1000000   Somestreet 77
2   1       An Appartment    $ 500000    Somewhere 11
3   4       A Land           $ 250000    Nowhere 33

Table imoveis_descr1
idImovel    rooms   area    floor   ...
2           2       70      5

Table imoveis_descr2
idImovel    rooms fieldArea   constrArea ...
1           3      120        80

Table imoveis_descr4
idImovel    area    width   height ...
3           2640    22      120

Result
id   categ    title       price     address   rooms fieldArea  constrArea    area    floor        area   width  height
1      2     The House    $ 1000000 Somestreet 77   3   120 80  null    null    null    null    null
2   1   An Appartment   $ 500000    Somewhere 11    2   null    null    70  5   null    null    null
3   4   A Land  $ 250000    Nowhere 33  null    null    null    null    null    2640    22  120

Body:
Some of your field-names are duplicated in your results (e.g. "rooms"), wouldn't it be better to merge those fields with COALESCE (as they appear mutually exclusive)?

As the tables your refer to are mutually exclusive, you will never get the required results with an INNER JOIN, you'll need an OUTER JOIN:

SELECT
      i.id,
      i.categ,
      i.title,
      i.price,
      i.address,
      COALESCE(i1.rooms, i2.rooms) AS rooms,
      i2.fieldArea,
      i2.constrArea
      COALESCE(i1.area, i3.area, ...) AS area,
      ...
FROM  imoveis AS i
      LEFT OUTER JOIN imoveis_descr1 AS i1 ON i1.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr2 AS i2 ON i2.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr3 AS i3 ON i3.idImovel = i.id
      ...


问:
How to make that only one radio button can be selected in a repeater?
I am implementing a table in an aspx page using repeater, the table is shown correctly.

In every row of the table I want to add a radio button ( a radio button is selected, means that row is selected), when I execute my program the page showed is the following:

The problem is as you can see in the image is that many radio buttons can be selected at the same time, my purpose is to allow the user to select only one row (one radio button) if a radio button is checked the other shoul be unchekced automatically.

here is my code:

```<code>    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DotNetRepeater.aspx.cs" Inherits="DotNetRepeater.DotNetRepeater" %>

<script type = "text/javascript">
    function RadioCheck(rb) {
        var gv = document.getElementById("<%=rptCustomers.ClientID%>");
        var rbs = gv.getElementsByTagName("input");

        var row = rb.parentNode.parentNode;
        for (var i = 0; i < rbs.length; i++) {
            if (rbs[i].type == "radio") {
                if (rbs[i].checked && rbs[i] != rb) {
                    rbs[i].checked = false;
                    break;
                }
            }
        }
    }
    </script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
            border-collapse: collapse;
           background-color: #00FF00 ;

        }
        table th
        {
            background-color: #FF0000;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border: 2px solid black;
        }
        form {
             width: 100%;
             text-align: center;
            height: 371px;
        }
        #Button1 {
             background-color: yellow;
             font-size: 15pt;

            top: 355px;
            left: 800px;
        }
        /*#SelectRadio1{
            left: 461px;*/
        /*}*/
    </style>
</head>
<body>
    <div class="container">
        <form id="form1" runat="server">

        <asp:Repeater ID="rptCustomers" runat="server" OnItemCommand="rptCustomers_ItemCommand">

        <HeaderTemplate>

            <table cellspacing="0" rules="all" border="1"  align="center"; >

                <tr>
                       <th scope="col" style="background-color:white">

                    </th>

                    <th scope="col" style="width: 80px">
                        Name
                    </th>
                    <th scope="col" style="width: 120px">
                        CountryRegionCode
                    </th>
                    <th scope="col" style="width: 100px">
                        Group
                    </th>
                    <th scope="col" style="width: 100px">
                        SalesYTD
                    </th>
                </tr>

        </HeaderTemplate>

        <ItemTemplate>

            <tr >
                <td style="background-color:white">
                     <asp:RadioButton id="Radio1" Checked="False" GroupName="RadioGroup1" runat="server" />
                </td>
                <td>
                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
                </td>
                <td>
                    <asp:Label ID="lblCountryRegionCode" runat="server" Text='<%# Eval("CountryRegionCode") %>' />
                </td>
                <td>
                    <asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group") %>' />
                </td>
                <td>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("SalesYTD") %>' />
                </td>

            </tr>

        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:Repeater>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="82px" />
    </form>
        </div>
</body>
</html>
</code>```

What should I add to the aspx code or to the code behind to make that only one radio button can be selected ?

Any help please ?

答:
Start by giving your table an unique ID (a Repeater does not generate a html element which has it's ID, so ClientID is of no use)

```<code><table id="rptCustomers" cellspacing="0" rules="all" border="1" align="center">
</code>```

Now you can reference that table in the following jQuery function

```<code><script type="text/javascript">
    $('#rptCustomers input[type="radio"]').click(function () {
        $('#rptCustomers input[type="radio"]').each(function () {
            $(this).prop("checked", "");
        });
        $(this).prop("checked", "checked");
    });
</script>
</code>```

It basically loops all the radio buttons within that table and unchecks them. Then it re-enables the one that was clicked.

For this to work you need jQuery.

Body:
I am implementing a table in an aspx page using repeater, the table is shown correctly.

In every row of the table I want to add a radio button ( a radio button is selected, means that row is selected), when I execute my program the page showed is the following:

The problem is as you can see in the image is that many radio buttons can be selected at the same time, my purpose is to allow the user to select only one row (one radio button) if a radio button is checked the other shoul be unchekced automatically.

here is my code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DotNetRepeater.aspx.cs" Inherits="DotNetRepeater.DotNetRepeater" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

        <form id="form1" runat="server">

        <asp:Repeater ID="rptCustomers" runat="server" OnItemCommand="rptCustomers_ItemCommand">

        <HeaderTemplate>

                        Name

                        CountryRegionCode

                        Group

                        SalesYTD

        </HeaderTemplate>

        <ItemTemplate>

                     <asp:RadioButton id="Radio1" Checked="False" GroupName="RadioGroup1" runat="server" />

                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />

                    <asp:Label ID="lblCountryRegionCode" runat="server" Text='<%# Eval("CountryRegionCode") %>' />

                    <asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group") %>' />

                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("SalesYTD") %>' />

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="82px" />
    </form>

What should I add to the aspx code or to the code behind to make that only one radio button can be selected ?

Any help please ?

Body:
Start by giving your table an unique ID (a Repeater does not generate a html element which has it's ID, so ClientID is of no use)

<table id="rptCustomers" cellspacing="0" rules="all" border="1" align="center">

Now you can reference that table in the following jQuery function

<script type="text/javascript">
    $('#rptCustomers input[type="radio"]').click(function () {
        $('#rptCustomers input[type="radio"]').each(function () {
            $(this).prop("checked", "");
        });
        $(this).prop("checked", "checked");
    });
</script>

It basically loops all the radio buttons within that table and unchecks them. Then it re-enables the one that was clicked.

For this to work you need jQuery.


问:
Object is possibly 'undefined'
So I am in vscode on typescript 2.5.3 and the following code:

```<code>export function isHttpHeaders ( headers: HttpHeaders | undefined ):
headers is HttpHeaders {
    return !!headers && !!headers.get && !!headers.set
}

function headersToHeadersSpec ( options?: RequestOptionsArgs ):
 Headers | undefined {

  const { headers } = options as RequestOptionsArgs

  if ( isHttpHeaders( headers ) ) {
    const reqHeaders = new Headers()
    headers.forEach( reqHeaders.set.bind( reqHeaders ) )
    return reqHeaders
  } else {
    return undefined
  }
}
</code>```

When I attempt to compile, for some reason the line headers.forEach( reqHeaders.set.bind( reqHeaders ) ) is complaining that the headers value is possibly undefined. Shouldn't the type guard guarantee that the value is not undefined?

答: Considering you have option? which means the parameter is optional, it would allow options to be undefined.  Even if you have code in other functions that check the value, typescript isn't smart enough to look at that code and figure out what it does.  Your code is not Compile-Time safe, but may be Run-Time safe.

Title: Object is possibly 'undefined'

Body:
So I am in vscode on typescript 2.5.3 and the following code:

export function isHttpHeaders ( headers: HttpHeaders | undefined ):
headers is HttpHeaders {
    return !!headers && !!headers.get && !!headers.set
}

function headersToHeadersSpec ( options?: RequestOptionsArgs ):
 Headers | undefined {

  const { headers } = options as RequestOptionsArgs

  if ( isHttpHeaders( headers ) ) {
    const reqHeaders = new Headers()
    headers.forEach( reqHeaders.set.bind( reqHeaders ) )
    return reqHeaders
  } else {
    return undefined
  }
}

When I attempt to compile, for some reason the line headers.forEach( reqHeaders.set.bind( reqHeaders ) ) is complaining that the headers value is possibly undefined. Shouldn't the type guard guarantee that the value is not undefined?


问:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
Why does  add a foreign key to the tblDomare table result in this error?

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__tblDomare__PersN__5F7E2DAC". The conflict occurred in database "almu0004", table "dbo.tblBana", column 'BanNR'.

Code

```<code>CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);

CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));

INSERT INTO tblBana (BanNR)
Values (1);

INSERT INTO tblBana (BanNR)
Values (2);

INSERT INTO tblBana (BanNR)
Values (3);

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
</code>```

答:
Smutje is correct and Chad HedgeCock offered a great layman's example.
Id like to build on Chad's example by offering a way to find/delete those records.
We will use Customer as the Parent and Order as the child.  CustomerId is the common field.

```<code>select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
</code>```

if you are reading this thread... you will get results. These are orphaned children. select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null Note the row count in the bottom right.

Go verify w/ whomever you need to that you are going to delete these rows!

```<code>begin tran
delete Order
from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
</code>```

Run the first bit.
Check that row count = what you expected

commit the tran

```<code>commit tran
</code>```

Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.

Body:
Why does  add a foreign key to the tblDomare table result in this error?

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__tblDomare__PersN__5F7E2DAC". The conflict occurred in database "almu0004", table "dbo.tblBana", column 'BanNR'.

Code

CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);

CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));

INSERT INTO tblBana (BanNR)
Values (1);

INSERT INTO tblBana (BanNR)
Values (2);

INSERT INTO tblBana (BanNR)
Values (3);

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

Body:
Smutje is correct and Chad HedgeCock offered a great layman's example.
Id like to build on Chad's example by offering a way to find/delete those records.
We will use Customer as the Parent and Order as the child.  CustomerId is the common field.

select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null

if you are reading this thread... you will get results. These are orphaned children. select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null Note the row count in the bottom right.

Go verify w/ whomever you need to that you are going to delete these rows!

begin tran
delete Order
from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null

Run the first bit.
Check that row count = what you expected

commit the tran

commit tran

Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.


问:
Java Activity not showing any view in layout
I created new Kotlin project with Android Studio 3.0. After that I created a Java activity and change it as main Activity in Manifest. After launching activity I am not getting any views visible. But when I try to load Kotlin activity the views are visible.

Kotlin Activity

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

}
</code>```

Java Activity

```<code>public class HomeActivity extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.activity_main);

    }
}
</code>```

Manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mypackage">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".HomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
You should override the right method</p>

```<code>public class HomeActivity extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

Body:
I created new Kotlin project with Android Studio 3.0. After that I created a Java activity and change it as main Activity in Manifest. After launching activity I am not getting any views visible. But when I try to load Kotlin activity the views are visible.

Kotlin Activity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

}

Java Activity

public class HomeActivity extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.activity_main);

    }
}

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mypackage">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".HomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
You should override the right method

public class HomeActivity extends AppCompatActivity {

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


问:
Using str_replace to alter a field's display in a Drupal 7 view
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

```<code><?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>
</code>```

this doesn't seem to work...

答:
If you are sure it always returns it as My Article Title | My Web Site, you could split the string at |.

```<code>$result = "My Article Title | My Web Site";   //the string that was returned
$splitResult = explode(" | ", $result);       //split the string at " | ", creating an array: ["My Article Title", "My Web Site"]
$articleTitle = $splitResult[0];              //get the first item in the array
</code>```

Body:
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

<?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>

this doesn't seem to work...

Body:
If you are sure it always returns it as My Article Title | My Web Site, you could split the string at |.

$result = "My Article Title | My Web Site";   //the string that was returned
$splitResult = explode(" | ", $result);       //split the string at " | ", creating an array: ["My Article Title", "My Web Site"]
$articleTitle = $splitResult[0];              //get the first item in the array


问:
Android app library efficencies
Does Android do anything to share duplicated libraries across apps?  It seems that the OS could detect duplicate lib hashes and avoid having separate copies for each app.

If a user has 50 apps installed and many of them have versions of Android support, Kotlin, and Guava libs there would be a nice opportunity to save disk space.

答:
Does Android do anything to share duplicated libraries across apps?

No.

It seems that the OS could detect duplicate lib hashes and avoid having separate copies for each app

Each app is digitally signed, so the decision of whether or not to include the libraries has to be done at build time. What you want would appear to require a time machine, to "retcon" Android to have this capability from the beginning. Alternatively, it would require distribution channel support to deliver different APK editions for different scenarios (e.g., newer devices get the APK sans libraries; older devices get the APK with libraries), and not all distribution channels will be in position to support that.

It is also unclear how this would work with respect to multidex and ProGuard. The shared library copies would need to be full libraries, not ones with items removed via ProGuard, since different apps would require different portions of the library. This might force all apps to use multidex, even where that would not ordinarily be required.

Security starts to become more of a problem. Where do the shared library copies come from? If you wish to limit it to a few "well known" libraries (e.g., Kotlin runtime), that's perhaps something that Google can manage. But a "first one in wins" approach raises the spectre of an app distributing a malicious copy of a library that winds up being shared.

Overall, your approach bears strong hallmarks to the "DLL hell" of the 1990s and the "JAR hell" of the 2000s. Shared libraries across apps are tricky to manage properly.

If a user has 50 apps installed and many of them have versions of Android support, Kotlin, and Guava libs there would be a nice opportunity to save disk space.

Guava is not used much in Android development due to its size. With the notable exception of appcompat-v7, most of the Android support libraries are fairly small. I don't think that this will save as much disk space as one might think, and the cost of that savings winds up getting put on the backs of developers.

Title: Android app library efficencies


问:
pyspark rdd isCheckPointed() is false
I was encountering stackoverflowerrors when I was iteratively adding over 500 columns to my pyspark dataframe. So, I included checkpoints. The checkpoints did not help. So, I created the following toy application to test if my checkpoints were working correctly. All I do in this example is iteratively create columns by copying the original column over and over again. I persist, checkpoint and count every 10 iterations. I notice that my dataframe.rdd.isCheckpointed() always returns False. I can verify that the checkpoint folders are indeed being created and populated on disk. I am running on dataproc on glcoud.

Here is my code:

```<code>from pyspark import SparkContext, SparkConf
from pyspark import StorageLevel
from pyspark.sql import SparkSession
import pandas as pd
import numpy as np
import sys

APP_NAME = "isCheckPointWorking"

spark = SparkSession\
    .builder\
    .appName(APP_NAME)\
    .config("spark.sql.crossJoin.enabled","true")\
    .getOrCreate()

sc = SparkContext.getOrCreate()

#set the checkpoint directory
sc.setCheckpointDir('gs://mybucket/checkpointtest/')

#create a spark dataframe with one column containing numbers 1 through 9
df4 = spark.createDataFrame(pd.DataFrame(np.arange(1,10),columns = ["A"]))
df4.show()

#create a list of new columns to be added to the dataframe
numberList = np.arange(0,40)
colNewList = ['col'+str(x) for x in numberList]

print(colNewList)

iterCount = 0

for colName in colNewList:

    #copy column A in to the new column
    df4 = df4.withColumn(colName,df4.A)

    if (np.mod(iterCount,10) == 0):
        df4 = df4.persist(StorageLevel.MEMORY_AND_DISK)

        df4.checkpoint(eager=True)

        df4.count()
        #checking if underlying RDD is being checkpointed
        print("is data frame checkpointed "+str(df4.rdd.isCheckpointed()))

    iterCount +=1
</code>```

It is unclear why df4.rdd.isCheckpointed() is returning False each time, when I can see that the checkpoint folder is being populated. Any thoughts?

答:
The checkpoint method returns a new check-pointed Dataset, it does not modify the current Dataset.

Change

```<code>df4.checkpoint(eager=True)
</code>```

To

```<code>df4 = df4.checkpoint(eager=True)
</code>```

Title: pyspark rdd isCheckPointed() is false

Body:
I was encountering stackoverflowerrors when I was iteratively adding over 500 columns to my pyspark dataframe. So, I included checkpoints. The checkpoints did not help. So, I created the following toy application to test if my checkpoints were working correctly. All I do in this example is iteratively create columns by copying the original column over and over again. I persist, checkpoint and count every 10 iterations. I notice that my dataframe.rdd.isCheckpointed() always returns False. I can verify that the checkpoint folders are indeed being created and populated on disk. I am running on dataproc on glcoud.

Here is my code:

from pyspark import SparkContext, SparkConf
from pyspark import StorageLevel
from pyspark.sql import SparkSession
import pandas as pd
import numpy as np
import sys

APP_NAME = "isCheckPointWorking"

spark = SparkSession\
    .builder\
    .appName(APP_NAME)\
    .config("spark.sql.crossJoin.enabled","true")\
    .getOrCreate()

sc = SparkContext.getOrCreate()

#set the checkpoint directory
sc.setCheckpointDir('gs://mybucket/checkpointtest/')

#create a spark dataframe with one column containing numbers 1 through 9
df4 = spark.createDataFrame(pd.DataFrame(np.arange(1,10),columns = ["A"]))
df4.show()

#create a list of new columns to be added to the dataframe
numberList = np.arange(0,40)
colNewList = ['col'+str(x) for x in numberList]

print(colNewList)

iterCount = 0

for colName in colNewList:

    #copy column A in to the new column
    df4 = df4.withColumn(colName,df4.A)

    if (np.mod(iterCount,10) == 0):
        df4 = df4.persist(StorageLevel.MEMORY_AND_DISK)

        df4.checkpoint(eager=True)

        df4.count()
        #checking if underlying RDD is being checkpointed
        print("is data frame checkpointed "+str(df4.rdd.isCheckpointed()))

    iterCount +=1

It is unclear why df4.rdd.isCheckpointed() is returning False each time, when I can see that the checkpoint folder is being populated. Any thoughts?

Body:
The checkpoint method returns a new check-pointed Dataset, it does not modify the current Dataset.

Change

df4.checkpoint(eager=True)

To

df4 = df4.checkpoint(eager=True)


问:
Select Customer ID who hasnt purchased product X
I have a table of customer IDs and Products Purchased.  A customer ID can purchase multiple products over time.

customerID, productID

In BigQuery I need to find the CustomerID for those who have not purchased product A.

I've been going around in circles trying to do self joins, inner joins, but I'm clueless.

Any help appreciated.

答:
If you have a customer table, you might want:

```<code>select c.*
from customers c
where not exists (select 1 from t where t.customer_id = c.customer_id and t.proectID = 'A');
</code>```

This will return customers who have made no purchases as well as those who have purchased all but product A.  Of course, the definition of a customer in your data might be that the customer has made a purchase, in which case I like Juergen's solution.

Body:
If you have a customer table, you might want:

select c.*
from customers c
where not exists (select 1 from t where t.customer_id = c.customer_id and t.proectID = 'A');

This will return customers who have made no purchases as well as those who have purchased all but product A.  Of course, the definition of a customer in your data might be that the customer has made a purchase, in which case I like Juergen's solution.


问:
Unable to identify formula error
just started to learn how to use python and I'm unsure where to ask if I'm unable to identify what is going wrong with my program, if this is the wrong forum then could someone please direct me to the correct one. It's a calculator designed to give the 3 angles of a triangle when all three lengths are inputted. It seems to work in terms of coding but all 3 angles are identical when they shouldn't be. It's best explained if you run the code below and you'll see what I'm talking about. Also working out the type of triangle is abit dodgy however I'm sure this is an error on my part which when closely looked at will resolve itself.</p>

```<code>import math

#degrees = (180/pi).radians (python maths works in radians) & radians = (pi/180).degrees

print("Welcome to the tri-angle calculator, please ensure that all 3 length inputs form a triangle otherwise program will not function. They must also be converted to the same units of length")

a = int(input("Insert first length of triangle in degrees: "))
b = int(input("Insert second length of triangle in degrees: "))
c = int(input("Insert third length of triangle in degrees: "))
#length inputs

A = math.acos(((b ** 2) + (c ** 2) - (a ** 2)) / (2 * b * c))
B = math.acos(((a ** 2) + (c ** 2) - (b ** 2)) / (2 * a * c))
C = math.acos(((a ** 2) + (b ** 2) - (c ** 2)) / (2 * a * b))
#working out all 3 angles of triangles

if(a == c and b == c):
    type = "Equilateral Triangle"
elif(math.cos(A) == 0 or math.cos(B) == 0 or math.cos(C) == 0):
    type = "Right Angle Triangle"
elif((a == b and c != b) or (b == c and c == a) or (c == a and c != b)):
    type = "Isoceles Triangle"
elif(a != b and b != c and c != a and A < (0.5 * math.pi) and B < (0.5 * math.pi) and C < (0.5 * math.pi)):
    type = "Acute Triangle"
else:
    type = "Obtuse Triangle"
#Working out the triangle type

print("The order of which the angles are shown in are opposite to the length inputted:")
print("Angle A - " + str((180 / math.pi) * A))
print("Angle B - " + str((180 / math.pi) * A))
print("Angle C - " + str((180 / math.pi) * A))

print("And it's a " + type )
#Printing Results

exit()
</code>```

答:
The program, fixed, and in a function (not necessarily the best one, but that can give you ideas :) )

```<code>import math

#degrees = (180/pi).radians (python maths works in radians) & radians = (pi/180).degrees

print("Welcome to the tri-angle calculator, please ensure that all 3 length inputs form a triangle otherwise program will not function. They must also be converted to the same units of length")

def magic_in_progress(a, b, c):
    A = math.acos((b**2 + c**2 - a**2) / (2 * b * c))
    B = math.acos((a**2 + c**2 - b**2) / (2 * a * c))
    C = math.acos((a**2 + b**2 - c**2) / (2 * a * b))
    #working out all 3 angles of triangles

    name = "Undetermined Triangle"

    pi_over_2 = 0.5 * math.pi

    if a == b == c:
        name = "Equilateral Triangle"
    elif 0 in (math.cos(A), math.cos(B), math.cos(C)):
        name = "Right Angle Triangle"
    elif a == b != c or b == c != a or c == a != b:
        name = "Isoceles Triangle"
    elif a != b != c != a and A < pi_over_2 and B < pi_over_2 and C < pi_over_2:
        name = "Acute Triangle"
    else:
        name = "Obtuse Triangle"
    #Working out the triangle type

    print("The order of which the angles are shown in are opposite to the length inputted:")
    print(f"Angle A - {180 / math.pi * A}")
    print(f"Angle B - {180 / math.pi * B}")
    print(f"Angle C - {180 / math.pi * C}")

    return name

#length inputs
a = int(input("Insert first length of triangle: "))
b = int(input("Insert second length of triangle: "))
c = int(input("Insert third length of triangle: "))

triangle_type = magic_in_progress(a, b, c)

print(f"And it's a {triangle_type}")
</code>```

And when used:

```<code>>>> a = int(input("Insert first length of triangle: "))
Insert first length of triangle: 4
>>> b = int(input("Insert second length of triangle: "))
Insert second length of triangle: 5
>>> c = int(input("Insert third length of triangle: "))
Insert third length of triangle: 6
>>> triangle_type = magic_in_progress(a, b, c)
The order of which the angles are shown in are opposite to the length inputted:
Angle A - 41.40962210927086
Angle B - 55.771133672187425
Angle C - 82.81924421854173
>>> print(f"And it's a {triangle_type}")
And it's a Acute Triangle
</code>```

Title: Unable to identify formula error

Body:
just started to learn how to use python and I'm unsure where to ask if I'm unable to identify what is going wrong with my program, if this is the wrong forum then could someone please direct me to the correct one. It's a calculator designed to give the 3 angles of a triangle when all three lengths are inputted. It seems to work in terms of coding but all 3 angles are identical when they shouldn't be. It's best explained if you run the code below and you'll see what I'm talking about. Also working out the type of triangle is abit dodgy however I'm sure this is an error on my part which when closely looked at will resolve itself.

import math

#degrees = (180/pi).radians (python maths works in radians) & radians = (pi/180).degrees

print("Welcome to the tri-angle calculator, please ensure that all 3 length inputs form a triangle otherwise program will not function. They must also be converted to the same units of length")

a = int(input("Insert first length of triangle in degrees: "))
b = int(input("Insert second length of triangle in degrees: "))
c = int(input("Insert third length of triangle in degrees: "))
#length inputs

A = math.acos(((b ** 2) + (c ** 2) - (a ** 2)) / (2 * b * c))
B = math.acos(((a ** 2) + (c ** 2) - (b ** 2)) / (2 * a * c))
C = math.acos(((a ** 2) + (b ** 2) - (c ** 2)) / (2 * a * b))
#working out all 3 angles of triangles

if(a == c and b == c):
    type = "Equilateral Triangle"
elif(math.cos(A) == 0 or math.cos(B) == 0 or math.cos(C) == 0):
    type = "Right Angle Triangle"
elif((a == b and c != b) or (b == c and c == a) or (c == a and c != b)):
    type = "Isoceles Triangle"
elif(a != b and b != c and c != a and A < (0.5 * math.pi) and B < (0.5 * math.pi) and C < (0.5 * math.pi)):
    type = "Acute Triangle"
else:
    type = "Obtuse Triangle"
#Working out the triangle type

print("The order of which the angles are shown in are opposite to the length inputted:")
print("Angle A - " + str((180 / math.pi) * A))
print("Angle B - " + str((180 / math.pi) * A))
print("Angle C - " + str((180 / math.pi) * A))

print("And it's a " + type )
#Printing Results

exit()

Body:
The program, fixed, and in a function (not necessarily the best one, but that can give you ideas :) )

import math

#degrees = (180/pi).radians (python maths works in radians) & radians = (pi/180).degrees

print("Welcome to the tri-angle calculator, please ensure that all 3 length inputs form a triangle otherwise program will not function. They must also be converted to the same units of length")

def magic_in_progress(a, b, c):
    A = math.acos((b**2 + c**2 - a**2) / (2 * b * c))
    B = math.acos((a**2 + c**2 - b**2) / (2 * a * c))
    C = math.acos((a**2 + b**2 - c**2) / (2 * a * b))
    #working out all 3 angles of triangles

    name = "Undetermined Triangle"

    pi_over_2 = 0.5 * math.pi

    if a == b == c:
        name = "Equilateral Triangle"
    elif 0 in (math.cos(A), math.cos(B), math.cos(C)):
        name = "Right Angle Triangle"
    elif a == b != c or b == c != a or c == a != b:
        name = "Isoceles Triangle"
    elif a != b != c != a and A < pi_over_2 and B < pi_over_2 and C < pi_over_2:
        name = "Acute Triangle"
    else:
        name = "Obtuse Triangle"
    #Working out the triangle type

    print("The order of which the angles are shown in are opposite to the length inputted:")
    print(f"Angle A - {180 / math.pi * A}")
    print(f"Angle B - {180 / math.pi * B}")
    print(f"Angle C - {180 / math.pi * C}")

    return name

#length inputs
a = int(input("Insert first length of triangle: "))
b = int(input("Insert second length of triangle: "))
c = int(input("Insert third length of triangle: "))

triangle_type = magic_in_progress(a, b, c)

print(f"And it's a {triangle_type}")

And when used:

>>> a = int(input("Insert first length of triangle: "))
Insert first length of triangle: 4
>>> b = int(input("Insert second length of triangle: "))
Insert second length of triangle: 5
>>> c = int(input("Insert third length of triangle: "))
Insert third length of triangle: 6
>>> triangle_type = magic_in_progress(a, b, c)
The order of which the angles are shown in are opposite to the length inputted:
Angle A - 41.40962210927086
Angle B - 55.771133672187425
Angle C - 82.81924421854173
>>> print(f"And it's a {triangle_type}")
And it's a Acute Triangle


问:
momentJS convert possibility day into Date() js format
I am trying to convert a date in format momentjs into a date from javascript native new Date().

The problem is that if I have moment(myDay).toDate(); it converts to the current date, and I want the date from myDay.

myDay looks like: "YYYY-MM-DD" => 2017-11-24 and I would like to have it with the format: Fri Nov 24 2017 20:17:11 GMT+0100 (Hora estándar romance) but I get Thu Nov 16 2017 etc...

It is possible to convert it like that way?

答:
Don't need moment:</p>

```<code>let [yr, mn, day] = myDay.split('-').map(Number);
// note that JS months are 0-11 not 1-12
let datestr = new Date(yr, mn - 1, dy).toString();
console.log(datestr); // "Fri Nov 24 2017 00:00:00 GMT-0500 (EST)"
</code>```

Body:
Don't need moment:

let [yr, mn, day] = myDay.split('-').map(Number);
// note that JS months are 0-11 not 1-12
let datestr = new Date(yr, mn - 1, dy).toString();
console.log(datestr); // "Fri Nov 24 2017 00:00:00 GMT-0500 (EST)"


问:
Angular and NGINX permission denied
I'm trying the setup NGINX to access angular /dist folder but can't make it works despite chmod -R 755 /path/to/dist ...

in my NGINX http block:

```<code>server {
  listen 80;
  server_name dashboard.example.local;

  ssl off;

  gzip on;
  root /path/to/dist/;
  index index.html;

  location /api/ {
    proxy_pass http://127.0.0.1:3000/;
  }
}
</code>```

I'm still getting this error "dist/index.html" is forbidden (13: Permission denied)

I already tried all the existing solutions I found on the internet.

EDIT: files that nginx are trying to access are 755

答:
The problem was in fact Mac OS related. To allow NGINX manipulate local files, we need to tell him to act as your user.

In top of the NGINX template, just put user <your-user-name> staff;

Title: Angular and NGINX permission denied

Body:
I'm trying the setup NGINX to access angular /dist folder but can't make it works despite chmod -R 755 /path/to/dist ...

in my NGINX http block:

server {
  listen 80;
  server_name dashboard.example.local;

  ssl off;

  gzip on;
  root /path/to/dist/;
  index index.html;

  location /api/ {
    proxy_pass http://127.0.0.1:3000/;
  }
}

I'm still getting this error "dist/index.html" is forbidden (13: Permission denied)

I already tried all the existing solutions I found on the internet.

EDIT: files that nginx are trying to access are 755


问:
Table relationship in hive, Spark Sql and Azure USQL
Is there any way i can maintain table relationship in Hive, Spark SQL and Azure U SQL. Does any of these support creating relationships like in Oracle or SQL Server. In oracle i can get the relationships using user_constraints table. Looking for something similar to that for processing in ML.</p>

答: I don't believe any of the big data platforms support integrity constraints. They are designed to load data as quickly as possible. Having constraints will only slow down the import. Hope this makes sense</p>


问:
Angular: Toggle class on an element's parent when using ngFor directive
I'm styling a checkbox as a button by placing it inside it's label

```<code><label>
 <input type="checkbox" name="...">
</label>
</code>```

I need to toggle the parent label's class based on whether the checkbox is checked. Now, this would be easy using [ngClass] and a boolean. The problem is, I'm also looping the elements with an *ngFor directive. This apparently used to work in Angular 1.x.x, but in Angular 2/4/... it adds/removes the class for all elements that are repeated.
This could easily be solved by accessing the parent DOM elements classList directly, but this is considered a bad practise in Angular. Is there any Angular way to do this or do I have to change my approach completely?

EDIT: my code
EDIT 2: Wrong code, fixed.

```<code>  <label *ngFor="let item of object.array" [ngClass]="{'label-active': checked}">
    {{item}}
    <input (click)= "checked = !checked"  type="checkbox" name="..." id="..." class="sr-only">
  </label>
</code>```

答:
Maintain a checked state for each item of the array that you iterate over using *ngFor in an array of the same size (this.checked in my example), or as property of the items in the data array this.object.array

```<code>export class MyComponent {
  object;

  someMethod() {
    this.object = {};
    this.object.array = someData; // whereever you get that data
    this.checked = new Arrray(this.object.array.length);
    this.checked.fill(false);
  }
}
</code>```

```<code> <label *ngFor="let item of object.array; let i=index"
    [class.label-active]="checked[i]">
    {{item}}
    <input (click)= "checked[i] = !checked[i]"  type="checkbox" name="..." id="..." class="sr-only">

    <!-- or -->
    <input [(ngModel)]="checked[i]" type="checkbox" name="..." id="..." class="sr-only">
  </label>
</code>```

Body:
I'm styling a checkbox as a button by placing it inside it's label

 <input type="checkbox" name="...">

I need to toggle the parent label's class based on whether the checkbox is checked. Now, this would be easy using [ngClass] and a boolean. The problem is, I'm also looping the elements with an *ngFor directive. This apparently used to work in Angular 1.x.x, but in Angular 2/4/... it adds/removes the class for all elements that are repeated.
This could easily be solved by accessing the parent DOM elements classList directly, but this is considered a bad practise in Angular. Is there any Angular way to do this or do I have to change my approach completely?

EDIT: my code
EDIT 2: Wrong code, fixed.

    {{item}}
    <input (click)= "checked = !checked"  type="checkbox" name="..." id="..." class="sr-only">

Body:
Maintain a checked state for each item of the array that you iterate over using *ngFor in an array of the same size (this.checked in my example), or as property of the items in the data array this.object.array

export class MyComponent {
  object;

  someMethod() {
    this.object = {};
    this.object.array = someData; // whereever you get that data
    this.checked = new Arrray(this.object.array.length);
    this.checked.fill(false);
  }
}

 <label *ngFor="let item of object.array; let i=index"
    [class.label-active]="checked[i]">
    {{item}}
    <input (click)= "checked[i] = !checked[i]"  type="checkbox" name="..." id="..." class="sr-only">

    <!-- or -->
    <input [(ngModel)]="checked[i]" type="checkbox" name="..." id="..." class="sr-only">
  </label>


问:
react-native-fbsdk app invite dialog error
So I am trying to use react-native-fbsdk FBAppInviteDialog to show invitation dialog but I always get this error

I was trying to use this code from Sending App Invites in a React Native app

here is my code

```<code>  constructor (props) {
    super(props)

    this.state = {
      appInviteContent: {
        applinkUrl: 'https://facebook.com'
      }
    }
  }
  _onPress = () => {
    var tmp = this
    AppInviteDialog.canShow(this.state.appInviteContent).then(
      function (canShow) {
        if (canShow) {
          return AppInviteDialog.show(tmp.state.appInviteContent)
        }
      }
    ).then(
      function (result) {
        if (result.isCancelled) {
          Alert.alert('Share cancelled')
        } else {
          Alert.alert('Share success with postId: ' + result.postId)
        }
      },
      function (error) {
        Alert.alert('Share fail with error: ' + error)
      }
    )
  }
</code>```

答:
If you want that the showDialog works you must first as the example show something like this:

appInviteContent= {
    contentType: 'link',
    contentUrl: Platform.select({ ios: 'https://iossomething.com',
    android: 'https://androidsomething.com'}),
    contentDescription: 'Check the website!',
};

Also as I see there in the code you are using the flow language.
Check that.

Body:
So I am trying to use react-native-fbsdk FBAppInviteDialog to show invitation dialog but I always get this error

I was trying to use this code from Sending App Invites in a React Native app

here is my code

  constructor (props) {
    super(props)

    this.state = {
      appInviteContent: {
        applinkUrl: 'https://facebook.com'
      }
    }
  }
  _onPress = () => {
    var tmp = this
    AppInviteDialog.canShow(this.state.appInviteContent).then(
      function (canShow) {
        if (canShow) {
          return AppInviteDialog.show(tmp.state.appInviteContent)
        }
      }
    ).then(
      function (result) {
        if (result.isCancelled) {
          Alert.alert('Share cancelled')
        } else {
          Alert.alert('Share success with postId: ' + result.postId)
        }
      },
      function (error) {
        Alert.alert('Share fail with error: ' + error)
      }
    )
  }


问:
Find a way in the java logging frameworks scene
Java has a lot of frameworks / APIs that help you do logging in your application:

The Java API has java.util.logging package.

Apache's Log4j.

Apache's Commons Logging.

SLF4J (logging Facade).

jLo.
and many many more...

I've always used the log4j library, i found it sufficient most of the time, and extensible when i needed more control.

Anyone who had experience with more than one framework can share his experience? when is it better to use one framework over the other and from application architecture point of view? Why would i prefer one over other?

Thanks

答: If its new code i'd start with slf4j, since it provides the simplest way to switch between the underlying logging api's by just including the required slf-[logging_api].jar in the classparth of your app. For example - if you start with log4j you still have to configure a Conole logger in a log4j.xml to see your logging output, with slf4j you just include the slf4j-simple.jar.  </p>

OwnerDisplayName: Alon


问:
get the latest fragment in backstack
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?</p>

```<code>FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();

/****After add , replace fragments
  (some of the fragments are add to backstack , some are not)***/

//HERE, How can I get the latest added fragment from backstack ??
</code>```

答:
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)

```<code>fun getTopFragment(): Fragment? {
    supportFragmentManager.run {
        return when (backStackEntryCount) {
            0 -> null
            else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
        }
    }
}
</code>```

*This should be called from inside an Activity.

Enjoy :)

Title: get the latest fragment in backstack

Body:
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?

FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();

/****After add , replace fragments
  (some of the fragments are add to backstack , some are not)***/

//HERE, How can I get the latest added fragment from backstack ??

Body:
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)

fun getTopFragment(): Fragment? {
    supportFragmentManager.run {
        return when (backStackEntryCount) {
            0 -> null
            else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
        }
    }
}

*This should be called from inside an Activity.

Enjoy :)


问:
BeautifulSoup doesn't seem to parse anything
I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this :

```<code><html>
 <head>
 </head>
 <body>
  <bound 0x7f977c9121d0="" <http.client.httpresponse="" at="" httpresponse.read="" method="" object="" of="">
>
  </bound>
 </body>
</html>
</code>```

I have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ?

```<code>from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req).read
        soup = BeautifulSoup(str(content), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())
</code>```

答:
You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you.

A better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you.

```<code>from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req)
        html = content.read()
        soup = BeautifulSoup(str(html), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())
        content.close()  # Important to close the connection
</code>```

For more info see: https://docs.python.org/3.0/library/urllib.request.html#examples

Body:
I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this :

  <bound 0x7f977c9121d0="" <http.client.httpresponse="" at="" httpresponse.read="" method="" object="" of="">
>
  </bound>

I have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ?

from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req).read
        soup = BeautifulSoup(str(content), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())

Body:
You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you.

A better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you.

from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req)
        html = content.read()
        soup = BeautifulSoup(str(html), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())
        content.close()  # Important to close the connection

For more info see: https://docs.python.org/3.0/library/urllib.request.html#examples


问:
How do I find the install time and date of Windows?
This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows?

The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution.

答:
Windows 10 OS has yet another registry subkey, this one in the SYSTEM hive file:

```<code>Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\
</code>```

The Install Date information here is the original computer OS install date/time. It also tells you when the update started, ie

```<code> Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)."
</code>```

This may of course not be when the update ends, the user may choose to turn off instead of rebooting when prompted, etc...

The update can actually complete on a different day, and

```<code>Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)"
</code>```

will reflect the date/time it started the update.

OwnerDisplayName: Free Wildebeest

LastEditorDisplayName: VonC

Body:
Windows 10 OS has yet another registry subkey, this one in the SYSTEM hive file:

Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\

The Install Date information here is the original computer OS install date/time. It also tells you when the update started, ie

 Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)."

This may of course not be when the update ends, the user may choose to turn off instead of rebooting when prompted, etc...

The update can actually complete on a different day, and

Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)"

will reflect the date/time it started the update.


问:
Paragraph Bottom Right of Div
I have two divs that each have a paragraph link at the bottom right of the div. When I add the code bottom: 0; position: absolute;, it pulls both the links together into the far right div instead of keeping them in their own divs. How can I set this so that the link stays inside of it's own container at the bottom right corner?

.header-unit {
  height: 300px;
  position: relative;
  margin-top: 5px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("/images/liberty.jpg");
}

#messageContainer {
  margin-left: 200px;
  /*  padding-top: 450px; */
  position: relative;
  display: inline-block;
}

h1 {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
}

#knowledge,
#practice {
  padding: 25px;
  width: 350px;
  height: 300px;
  display: block;
  color: #fff;
}

.linksect {
  bottom: 0;
  right: 25px;
  position: absolute;
}

#knowledge {
  background: #8b8b8b;
}

#practice {
  background: #554a58;
}

.indexheader {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
  color: #554a58;
}

.firmvalues {
  margin-top: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<div class="header-unit">
  <div id="messageContainer" class="w3-row">
    <div id="knowledge" class="w3-col l6">
      <h1>Knowledge. Experience. Commitment. </h1>
      <p>The attorneys of ....</p>
      <p class="linksect">Our Attorneys <span class="fa fa-angle-double-right" aria-hidden="true"></span></p>
    </div>
    <div id="practice" class="w3-col l6">
      <h1>Practice Areas</h1>
      <p>Business and Commercial Law<br> Insurance Coverage and Indemnity Law<br> Medical and Dental Malpractice<br> Probate Law and Practice<br> and more...</p>
      <p class="linksect">Practice Areas <span class="fa fa-angle-double-right" aria-hidden="true"></span></p>
    </div>
  </div>
</div></code>```

答:
You can provide context for position:absolute by adding a non-static position property to the ancestor element you want the absolutely positioned element to be relative to.  position:relative is usually a good choice because it keeps your element in the document flow. (Note that I added it to the #knowledge,#practice rule.)

.header-unit {
  height: 300px;
  position: relative;
  margin-top: 5px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("/images/liberty.jpg");
}

#messageContainer {
  margin-left: 200px;
  /*  padding-top: 450px; */
  position: relative;
  display: inline-block;
}

h1 {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
}

#knowledge,
#practice {
  padding: 25px;
  width: 350px;
  height: 300px;
  display: block;
  color: #fff;
  position: relative;
}

.linksect {
  bottom: 0;
  right: 25px;
  position: absolute;
}

#knowledge {
  background: #8b8b8b;
}

#practice {
  background: #554a58;
}

.indexheader {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
  color: #554a58;
}

.firmvalues {
  margin-top: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<div class="header-unit">
  <div id="messageContainer" class="w3-row">
    <div id="knowledge" class="w3-col l6">
      <h1>Knowledge. Experience. Commitment. </h1>
      <p>The attorneys of ....</p>
      <p class="linksect">Our Attorneys <span class="fa fa-angle-double-right" aria-hidden="true"></span></p>
    </div>
    <div id="practice" class="w3-col l6">
      <h1>Practice Areas</h1>
      <p>Business and Commercial Law<br> Insurance Coverage and Indemnity Law<br> Medical and Dental Malpractice<br> Probate Law and Practice<br> and more...</p>
      <p class="linksect">Practice Areas <span class="fa fa-angle-double-right" aria-hidden="true"></span></p>
    </div>
  </div>
</div></code>```

Title: Paragraph Bottom Right of Div

Body:
I have two divs that each have a paragraph link at the bottom right of the div. When I add the code bottom: 0; position: absolute;, it pulls both the links together into the far right div instead of keeping them in their own divs. How can I set this so that the link stays inside of it's own container at the bottom right corner?

.header-unit {
  height: 300px;
  position: relative;
  margin-top: 5px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("/images/liberty.jpg");
}

#messageContainer {
  margin-left: 200px;
  /*  padding-top: 450px; */
  position: relative;
  display: inline-block;
}

h1 {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
}

#knowledge,
#practice {
  padding: 25px;
  width: 350px;
  height: 300px;
  display: block;
  color: #fff;
}

.linksect {
  bottom: 0;
  right: 25px;
  position: absolute;
}

#knowledge {
  background: #8b8b8b;
}

#practice {
  background: #554a58;
}

.indexheader {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
  color: #554a58;
}

.firmvalues {
  margin-top: 50px;
}

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

Knowledge. Experience. Commitment.

The attorneys of ....

Our Attorneys

Practice Areas

Business and Commercial Law
 Insurance Coverage and Indemnity Law
 Medical and Dental Malpractice
 Probate Law and Practice
 and more...

Practice Areas

Body:
You can provide context for position:absolute by adding a non-static position property to the ancestor element you want the absolutely positioned element to be relative to.  position:relative is usually a good choice because it keeps your element in the document flow. (Note that I added it to the #knowledge,#practice rule.)

.header-unit {
  height: 300px;
  position: relative;
  margin-top: 5px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("/images/liberty.jpg");
}

#messageContainer {
  margin-left: 200px;
  /*  padding-top: 450px; */
  position: relative;
  display: inline-block;
}

h1 {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
}

#knowledge,
#practice {
  padding: 25px;
  width: 350px;
  height: 300px;
  display: block;
  color: #fff;
  position: relative;
}

.linksect {
  bottom: 0;
  right: 25px;
  position: absolute;
}

#knowledge {
  background: #8b8b8b;
}

#practice {
  background: #554a58;
}

.indexheader {
  font-family: 'Montserrat', sans-serif;
  font-size: 2em;
  line-height: 1.15;
  text-transform: uppercase;
  color: #554a58;
}

.firmvalues {
  margin-top: 50px;
}

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<div class="header-unit">
  <div id="messageContainer" class="w3-row">
    <div id="knowledge" class="w3-col l6">
      <h1>Knowledge. Experience. Commitment. </h1>
      <p>The attorneys of ....</p>
      <p class="linksect"><a href="/page/3/attorneys">Our Attorneys <span class="fa fa-angle-double-right" aria-hidden="true"></span></a></p>
    </div>
    <div id="practice" class="w3-col l6">
      <h1>Practice Areas</h1>
      <p>Business and Commercial Law<br> Insurance Coverage and Indemnity Law<br> Medical and Dental Malpractice<br> Probate Law and Practice<br> and more...</p>
      <p class="linksect"><a href="/page/2/practices">Practice Areas <span class="fa fa-angle-double-right" aria-hidden="true"></span></a></p>
    </div>
  </div>
</div>


问:
how to unwind javascript object into Json object without duplicate entries
existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}

I want to convert this javascript into something that doesnt have array items in it, like below

desiredJsObj = [{"a":1, "b":11},{"a":2,"b":22},{"a":3, "b":33},{"a":4, "b":44}]

答:
I would do following:

```<code>const income = {"a": [1,2,3,4], "b":[11,22,33,44]};

const res = income.a.map((a, i) => ({ a: a, b: income.b[i] }));
</code>```

This works in assumption that "a" length is equal to "b" length.

Body:
I would do following:

const income = {"a": [1,2,3,4], "b":[11,22,33,44]};

const res = income.a.map((a, i) => ({ a: a, b: income.b[i] }));

This works in assumption that "a" length is equal to "b" length.


问:
How can I make a function treat a whole sentence like one parameter?
How should I pass a sentence to function and make it behave like one parameter.

Example:

```<code>function Test ()
{
  echo $1
}
body="This the test"
Test $body
</code>```

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

答:
Always quote all parameter substitutions.

```<code>function Test() {
  echo "$1"   # needs quoting
}
body='This the test'  # double quotes would also work in this case
Test "$body"  # needs quoting as well
</code>```

Corrected and readable version of the code below:

```<code>logger() {
    local message="$1"
    local mode="$2"
    case "$mode" in
        0)
            echo "$message"
            ;;
        1)
            echo "$message" > "$LOG_FILE_DIRECTORY_PATH$LOG_FILE_NAME"
            echo
            ;;
    esac
}

logmsg=' This is log message '
logger "$logmsg" 0
</code>```

Body:
How should I pass a sentence to function and make it behave like one parameter.

Example:

function Test ()
{
  echo $1
}
body="This the test"
Test $body

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

Body:
Always quote all parameter substitutions.

function Test() {
  echo "$1"   # needs quoting
}
body='This the test'  # double quotes would also work in this case
Test "$body"  # needs quoting as well

Corrected and readable version of the code below:

logger() {
    local message="$1"
    local mode="$2"
    case "$mode" in
        0)
            echo "$message"
            ;;
        1)
            echo "$message" > "$LOG_FILE_DIRECTORY_PATH$LOG_FILE_NAME"
            echo
            ;;
    esac
}

logmsg=' This is log message '
logger "$logmsg" 0


问:
Error while installing from script ZeroBraneStudio
When executing ZeroBraneStudioEduPack-1.70-linux.sh i get this error: xdg-desktop-menu: No writable system menu directory found.
It could be related to my desktop environment ? currently i'm using sway with xwayland.

答: According to this answer, seems to be an xdg bug. You can check if running sudo mkdir /usr/share/desktop-directories/ before running the install command fixes the issue. I'll consider adding it to the install script if it helps.


问:
Loading Fonts.com Web-Font Doesn't work in Chrome (but only when deployed?)
I'm currently hosting a React/Gatsby project via GitHub Pages, and I've been messing with fonts.com and their web-fonts system to get the Rockwell font. I followed the instructions of inputting the script tag into the  section of my code:

```<code><script type="text/javascript" src="//fast.fonts.net/jsapi/0a390850-37c6-420c-8ead-c15e81202559.js"></script>
</code>```

I followed all of their advice when referencing my domains, and I've run into this interesting bug.

<s>The font loads perfectly normally in Firefox.  </s>

a. UPDATE: This was not true, it was cached there too.

The font also loads when I run 'gatsby develop' and have my project running in localhost:8000

a. (I know that it works in localhost because I use the nifty "empty cache and hard reload" function of Chrome.)

And yet, when I pull the page up in Chrome, I get the following error

```<code>GET https://fast.fonts.net/dv2/14/8dd355f9-1a9a-4d91-8aa1-7dcc9deeb439.woff2?d44f19a684109620e4841578a490e8187cac2bf7466ecccd35f843ec9e8410dc73fea4cea7acbbbaf9d830e48fc615a792f4b24a1c10853efb77f66879fc39a15a09593f079cf7a38cb48dd4836fa2ebba1b54d33b577d893508a6f4d0526453533728dec4671fee2d130ac32d5b8a97d5&projectId=0a390850-37c6-420c-8ead-c15e81202559 net::ERR_ABORTED
</code>```

So either that will show up, or I get a 403 error. (I've followed their posted advice on solving 403 errors.)

I've Googled and messed around to no avail. I found a similar problem suggesting to use an @import in the css, but that doesn't work because it's a javascript file

As far as I can tell, it has something to do with loading the woff2 part of the font in particular, but I can't take that part out because it's a web font. Somehow that's resulting in a net::ERR_ABORTED. Could it have something to do with how Gatsby publishes? Or maybe how React handles having script tags in the ?

Thanks for any advice you can give!

UPDATE: Firefox had it cached. This leads me to believe that Webpack is messing with the script tag/downloaded stuff.

答:
Alright so I solved this.
While the project was being hosted on a project domain (www.mywebsite.com/project), I saw deep in the network calls that the request itself was coming from the regular domain (www.mywebsite.com). So I had to adjust that in the listed domains.</p>

Body:
I'm currently hosting a React/Gatsby project via GitHub Pages, and I've been messing with fonts.com and their web-fonts system to get the Rockwell font. I followed the instructions of inputting the script tag into the  section of my code:

I followed all of their advice when referencing my domains, and I've run into this interesting bug.

<s>The font loads perfectly normally in Firefox.  </s>

a. UPDATE: This was not true, it was cached there too.

The font also loads when I run 'gatsby develop' and have my project running in localhost:8000

a. (I know that it works in localhost because I use the nifty "empty cache and hard reload" function of Chrome.)

And yet, when I pull the page up in Chrome, I get the following error

GET https://fast.fonts.net/dv2/14/8dd355f9-1a9a-4d91-8aa1-7dcc9deeb439.woff2?d44f19a684109620e4841578a490e8187cac2bf7466ecccd35f843ec9e8410dc73fea4cea7acbbbaf9d830e48fc615a792f4b24a1c10853efb77f66879fc39a15a09593f079cf7a38cb48dd4836fa2ebba1b54d33b577d893508a6f4d0526453533728dec4671fee2d130ac32d5b8a97d5&projectId=0a390850-37c6-420c-8ead-c15e81202559 net::ERR_ABORTED

So either that will show up, or I get a 403 error. (I've followed their posted advice on solving 403 errors.)

I've Googled and messed around to no avail. I found a similar problem suggesting to use an @import in the css, but that doesn't work because it's a javascript file

As far as I can tell, it has something to do with loading the woff2 part of the font in particular, but I can't take that part out because it's a web font. Somehow that's resulting in a net::ERR_ABORTED. Could it have something to do with how Gatsby publishes? Or maybe how React handles having script tags in the ?

Thanks for any advice you can give!

UPDATE: Firefox had it cached. This leads me to believe that Webpack is messing with the script tag/downloaded stuff.