问:
Kendo Grid UI: Collapse single Tree node instead of complete tree
I have a Tree view data (3 Levels) in Kendo Grid and I am using Kendo Grid feature to Expand/collapse tree view. My requirement is to expand /collapse Tree Data level by level and not all at once.

Expand is working fine using the following code

```<code>$(".treeview").data("kendoTreeView").expand(".k-item");
</code>```

Problem is with the collapse. By clicking the collapse button tree collapses completely but I want it to collapse only once.

I tried following

```<code>$(".treeview").data("kendoTreeView").collapse(".k-item"); Collapses to first level
$(".treeview").data("kendoTreeView").collapse(".k-group"); same: Collapses to first level
</code>```

I could use treeview.collapse(treeview.findByText("foo")); something like that but as the data is dynamic so I don't know the exact text.

Is there any way I can collapse only one node instead of the whole tree.

答:
If the node is dynamic first find its value by some function

```<code>function collapse() {

    var text= calculateNode(test);

    var treeview = $(".treeview").data("kendoTreeView");
    for (var i = 0; i < nTextValue.length; i++) {
        treeview.collapse(treeview.findByText(text[i]));
    }
}
</code>```

and then collapse all nodes on that level

Body:
I have a Tree view data (3 Levels) in Kendo Grid and I am using Kendo Grid feature to Expand/collapse tree view. My requirement is to expand /collapse Tree Data level by level and not all at once.

Expand is working fine using the following code

$(".treeview").data("kendoTreeView").expand(".k-item");

Problem is with the collapse. By clicking the collapse button tree collapses completely but I want it to collapse only once.

I tried following

$(".treeview").data("kendoTreeView").collapse(".k-item"); Collapses to first level
$(".treeview").data("kendoTreeView").collapse(".k-group"); same: Collapses to first level

I could use treeview.collapse(treeview.findByText("foo")); something like that but as the data is dynamic so I don't know the exact text.

Is there any way I can collapse only one node instead of the whole tree.

Body:
If the node is dynamic first find its value by some function

function collapse() {

    var text= calculateNode(test);

    var treeview = $(".treeview").data("kendoTreeView");
    for (var i = 0; i < nTextValue.length; i++) {
        treeview.collapse(treeview.findByText(text[i]));
    }
}

and then collapse all nodes on that level


来源: stackexchange

问:
 with fixed
 and scrollable

I've looked through questions here and articles all over the internet, but haven't found yet solution that would satisfy my requirements. So now in 2017, is there an elegant way to have a
 that would:

be written in html+css (no js)

have fixed header (not scrollable; not sticky)

have scrollable
 (scrollbar may be always visible)

header and body would handle resizing properly and not mess alignment of the
 columns and the
 columns

would not use nested tables or separate table for header

答:
How about this?

```<code><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
table {
    max-width:980px;
    table-layout:fixed;
    margin:auto;
}
th, td {
    padding:5px 10px;
    border:1px solid #000;
}
thead, tfoot {
    background:#f9f9f9;
    display:table;
    width:100%;
    width:calc(100% - 18px);
}
tbody {
    height:300px;
    overflow:auto;
    overflow-x:hidden;
    display:block;
    width:100%;
}
tbody tr {
    display:table;
    width:100%;
    table-layout:fixed;
}
</style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th scope="col">Header 1                    </th>
                <th scope="col">Header 2                    </th>
                <th scope="col">Header 3                    </th>
                <th scope="col">Header 4                    </th>
            </tr>
        </thead>
    <tbody>
    <tr>
        <td>Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    </tbody>
    <tfoot>
        <tr>
        <td>Footer 1        </td>
        <td>Footer 2        </td>
        <td>Footer 3        </td>
        <td>Footer 4        </td>
        </tr>
    </tfoot>
    </table>
</body>
</html>
</code>```

I've created a fiddle below

https://jsfiddle.net/jchaplin2/dt829611/1/

ContentLicense: CC BY-SA 4.0

Title: <table> with fixed <thead> and scrollable <tbody>

Body:
How about this?

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
table {
    max-width:980px;
    table-layout:fixed;
    margin:auto;
}
th, td {
    padding:5px 10px;
    border:1px solid #000;
}
thead, tfoot {
    background:#f9f9f9;
    display:table;
    width:100%;
    width:calc(100% - 18px);
}
tbody {
    height:300px;
    overflow:auto;
    overflow-x:hidden;
    display:block;
    width:100%;
}
tbody tr {
    display:table;
    width:100%;
    table-layout:fixed;
}
</style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th scope="col">Header 1                    </th>
                <th scope="col">Header 2                    </th>
                <th scope="col">Header 3                    </th>
                <th scope="col">Header 4                    </th>
            </tr>
        </thead>
    <tbody>
    <tr>
        <td>Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required Cell content with content to wrap as required            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
        <td>Cell content            </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    <tr>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
        <td>Cell content        </td>
    </tr>
    </tbody>
    <tfoot>
        <tr>
        <td>Footer 1        </td>
        <td>Footer 2        </td>
        <td>Footer 3        </td>
        <td>Footer 4        </td>
        </tr>
    </tfoot>
    </table>
</body>
</html>

I've created a fiddle below

https://jsfiddle.net/jchaplin2/dt829611/1/

ContentLicense: CC BY-SA 3.0


问:
Add element to sublist of a list
I have the following code:

```<code>let numbers = [[1],[2],[3],[4]]
</code>```

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

```<code>(numbers !! 2) ++ [3]
</code>```

to get this:

```<code>numbers = [[1],[2],[3,3],[4]]
</code>```

But Im very confused :P Any idea?

答:
As chi already commented, the best way to do such an update on part of a structure in modern Haskell is with lense combinators, specifically, ix:

```<code>Prelude Control.Lens> let numbers = [[1],[2],[3],[4]]
Prelude Control.Lens> numbers & ix 2 %~ (++[3])
[[1],[2],[3,3],[4]]
</code>```

(Don't be scared of lenses. The main lens package is huge and dependency-heavy, but most of its killer features, including ix, are also covered by the compatible and much smaller microlens package.)

Title: Add element to sublist of a list

Body:
I have the following code:

let numbers = [[1],[2],[3],[4]]

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

(numbers !! 2) ++ [3]

to get this:

numbers = [[1],[2],[3,3],[4]]

But Im very confused :P Any idea?

Body:
As chi already commented, the best way to do such an update on part of a structure in modern Haskell is with lense combinators, specifically, ix:

Prelude Control.Lens> let numbers = [[1],[2],[3],[4]]
Prelude Control.Lens> numbers & ix 2 %~ (++[3])
[[1],[2],[3,3],[4]]

(Don't be scared of lenses. The main lens package is huge and dependency-heavy, but most of its killer features, including ix, are also covered by the compatible and much smaller microlens package.)


问:
How to get all data from a table which you also query for AVG
Hello I need help on solving the query problem below.. Thanks in advance.

I have three tables

attachments
  sun_individual
  sun_reviews

I want to select user names, profession and reviewed by his/her ID from sun_individual and join with his profile photo from table attachments then get his/her reviews (each review and rate) and the average RATE

TABLE : sun_individual

```<code>id|sun_id|first_name|last_name |sun_profession|sun_verified_date|sun_verified|flg
---------------------------------------------------------------------------------
20|SV-001|Alex      | James    | Doctor       |2017-12-08       | 1         |1
21|SV-002|Jane      | Rose     | Programmer   |2017-12-08       | 1         |1
</code>```

TABLE: sun_reviews

```<code>id|user_id|rev_txt   |rev_rate|rev_date  |flg
----------------------------------------------------
1 |20     | the best | 4      |2017-12-09|1
2 |21     | know CLI | 2      |2017-12-09|1
3 |20     | recommend| 3      |2017-12-09|0
4 |20     | so far   | 3      |2017-12-09|1
</code>```

TABLE: attachments

```<code>id|user|type    |path              |flg
----------------------------------------
88|20  |passport|/upload/img128.jpg|1
89|21  |passport|/upload/img008.jpg|1
</code>```

flg:1 means the value is active, flg:0the value is to be ignored

My Code is :

```<code>SELECT
      sun_reviews.rev_txt As txtReview, sun_reviews.rev_date As dateReview,
      sun_reviews.rev_rate As rateReview,

      AVG(sun_reviews.rev_rate) As avgREV,
      concat(sun_individual.first_name, sun_individual.last_name) As name,

      sun_individual.sun_profession As profession,
      sun_individual.sun_verified_date As dateVerified,

      CASE when sun_verified = 1 then 'VERIFIED' else 'EXPIRED' END As status,

      attachments.path As photo
FROM `sun_individual`

     LEFT JOIN sun_reviews ON sun_reviews.user_id = sun_individual.id
     INNER JOIN attachments ON attachments.user = sun_individual.id

WHERE attachments.type = 'passport' AND attachments.flg = 1
      AND sun_reviews.flg = 1 AND sun_individual.flg = 1
      AND sun_individual.sun_id LIKE '%SV-001'
</code>```

What I want to archive is when someone is looking for user (let say SV-001) when the code is inputted to get result like

result for: SV-001

```<code>txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg
so far   |2017-12-09|3         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg
</code>```

I want to get result like the one above, however when I ran the query I get only one review

```<code>txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg
</code>```

I think there is something am doing wrong... If you know the solution to my problem kindly help me.

Thanks.

答:
```<code>select
  a.rev_txt                    as txtReview,
  a.rev_date                   as dateReview,
  a.rev_rate                   as rateReview,
  d.avgRev                     as avgRev,
  b.first_name || b.last_name  as name,
  b.sun_profession             as profession,
  b.sun_verified_date          as dateVerified,
  case
    when sun_verified = 1 then 'VERIFIED'
    else 'EXPIRED'
  end                          as status,
  c.path                       as photo
from
  sun_reviews a
  join
  sun_individual b
  on a.user_id = b.id
  join
  attachments c
  on c.user_id = b.id
  join
  (
    select
      user_id,
      avg(rev_rate) as avgRev
    from
      sun_reviews
    where
      flg = 1
    group by
      user_id
  ) d
  on d.user_id = b.id
where
  c.type = 'passport' and
  c.flg = 1 and
  a.flg = 1 and
  b.flg = 1 and
  b.sun_id LIKE '%SV-001';

 txtreview | datereview | ratereview |       avgrev       |   name    | profession | dateverified |  status  |       photo
-----------+------------+------------+--------------------+-----------+------------+--------------+----------+--------------------
 the best  | 2017-12-09 |          4 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
 so far    | 2017-12-09 |          3 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
(2 rows)
</code>```

When you have a group by, all columns in the result set must be either group by columns or aggregates.  I guess you are using MySQL which does not enforce this.  You should enforce it yourself though, otherwise it gets very confusing.

Body:
Hello I need help on solving the query problem below.. Thanks in advance.

I have three tables

attachments
  sun_individual
  sun_reviews

I want to select user names, profession and reviewed by his/her ID from sun_individual and join with his profile photo from table attachments then get his/her reviews (each review and rate) and the average RATE

TABLE : sun_individual

id|sun_id|first_name|last_name |sun_profession|sun_verified_date|sun_verified|flg
---------------------------------------------------------------------------------
20|SV-001|Alex      | James    | Doctor       |2017-12-08       | 1         |1
21|SV-002|Jane      | Rose     | Programmer   |2017-12-08       | 1         |1

TABLE: sun_reviews

id|user_id|rev_txt   |rev_rate|rev_date  |flg
----------------------------------------------------
1 |20     | the best | 4      |2017-12-09|1
2 |21     | know CLI | 2      |2017-12-09|1
3 |20     | recommend| 3      |2017-12-09|0
4 |20     | so far   | 3      |2017-12-09|1

TABLE: attachments

id|user|type    |path              |flg
----------------------------------------
88|20  |passport|/upload/img128.jpg|1
89|21  |passport|/upload/img008.jpg|1

flg:1 means the value is active, flg:0the value is to be ignored

My Code is :

SELECT
      sun_reviews.rev_txt As txtReview, sun_reviews.rev_date As dateReview,
      sun_reviews.rev_rate As rateReview,

      AVG(sun_reviews.rev_rate) As avgREV,
      concat(sun_individual.first_name, sun_individual.last_name) As name,

      sun_individual.sun_profession As profession,
      sun_individual.sun_verified_date As dateVerified,

      CASE when sun_verified = 1 then 'VERIFIED' else 'EXPIRED' END As status,

      attachments.path As photo
FROM `sun_individual`

     LEFT JOIN sun_reviews ON sun_reviews.user_id = sun_individual.id
     INNER JOIN attachments ON attachments.user = sun_individual.id

WHERE attachments.type = 'passport' AND attachments.flg = 1
      AND sun_reviews.flg = 1 AND sun_individual.flg = 1
      AND sun_individual.sun_id LIKE '%SV-001'

What I want to archive is when someone is looking for user (let say SV-001) when the code is inputted to get result like

result for: SV-001

txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg
so far   |2017-12-09|3         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg

I want to get result like the one above, however when I ran the query I get only one review

txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg

I think there is something am doing wrong... If you know the solution to my problem kindly help me.

Thanks.

Body:
select
  a.rev_txt                    as txtReview,
  a.rev_date                   as dateReview,
  a.rev_rate                   as rateReview,
  d.avgRev                     as avgRev,
  b.first_name || b.last_name  as name,
  b.sun_profession             as profession,
  b.sun_verified_date          as dateVerified,
  case
    when sun_verified = 1 then 'VERIFIED'
    else 'EXPIRED'
  end                          as status,
  c.path                       as photo
from
  sun_reviews a
  join
  sun_individual b
  on a.user_id = b.id
  join
  attachments c
  on c.user_id = b.id
  join
  (
    select
      user_id,
      avg(rev_rate) as avgRev
    from
      sun_reviews
    where
      flg = 1
    group by
      user_id
  ) d
  on d.user_id = b.id
where
  c.type = 'passport' and
  c.flg = 1 and
  a.flg = 1 and
  b.flg = 1 and
  b.sun_id LIKE '%SV-001';

 txtreview | datereview | ratereview |       avgrev       |   name    | profession | dateverified |  status  |       photo
-----------+------------+------------+--------------------+-----------+------------+--------------+----------+--------------------
 the best  | 2017-12-09 |          4 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
 so far    | 2017-12-09 |          3 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
(2 rows)

When you have a group by, all columns in the result set must be either group by columns or aggregates.  I guess you are using MySQL which does not enforce this.  You should enforce it yourself though, otherwise it gets very confusing.


问:
define height of element against width of parent div
How can I set the height of an element based on the width of it's parent div ?

if I do

```<code>height: <some_ratio>vw
</code>```

I'm getting a height that equals some_ratio of the viewport's width.
I want some_ratio of parent div's width.
Is that possible ?

(I need this to generate square elements in bootstrap cols. Thus the height of those elements must equal the width of the col)

答:
If you want a pure CSS way, you can set the children height to 0 and then use padding-bottom to set a percentage :) (paddings are based on width, even the top/bottom padding)

.parent{
    height: 100px;
    width: 300px;
    background: red;
}
.child{
    background: blue;
    width: 50px;
    height: 0;
    padding-bottom: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
<div class="child">
</div>
</div></code>```

Body:
How can I set the height of an element based on the width of it's parent div ?

if I do

height: <some_ratio>vw

I'm getting a height that equals some_ratio of the viewport's width.
I want some_ratio of parent div's width.
Is that possible ?

(I need this to generate square elements in bootstrap cols. Thus the height of those elements must equal the width of the col)

Body:
If you want a pure CSS way, you can set the children height to 0 and then use padding-bottom to set a percentage :) (paddings are based on width, even the top/bottom padding)

.parent{
    height: 100px;
    width: 300px;
    background: red;
}
.child{
    background: blue;
    width: 50px;
    height: 0;
    padding-bottom: 25%;
}

<div class="parent">
<div class="child">
</div>
</div>


问:
Selecting columns to insert into table with where condition
I am working on a project where I need to grab the img path from a backup table and insert it in to the image path column of a new table based on if the item names match up perfectly (as the id's vary).

This is what I tried, but getting an error that the items.prod_name column is not found:

MySQL

```<code>INSERT INTO items (img_path)
SELECT img_path
FROM items_backup
WHERE items.prod_name = items_backup.prod_name
</code>```

答:
To follow up on my comment:</p>

```<code>UPDATE items
INNER JOIN items_backup ON items.prod_name = items_backup.prod_name
SET items.img_path = items_backup.img_path
</code>```

Body:
I am working on a project where I need to grab the img path from a backup table and insert it in to the image path column of a new table based on if the item names match up perfectly (as the id's vary).

This is what I tried, but getting an error that the items.prod_name column is not found:

MySQL

INSERT INTO items (img_path)
SELECT img_path
FROM items_backup
WHERE items.prod_name = items_backup.prod_name

Body:
To follow up on my comment:

UPDATE items
INNER JOIN items_backup ON items.prod_name = items_backup.prod_name
SET items.img_path = items_backup.img_path


问:
how display record from table to gridview on page load and also search record for particular fields using textbox vb.net?
My database : table1

```<code>ID             FIRSTNAME              AGE
1              Sumit                  22
2              Sanjeev                23
</code>```

i  have gridview 1 and textbox1 and button1

i want when pages load the gridview displays the all records from table1 and also ...i i wanna search record for firstname by typing sumit in textbox1 and click on button1 then in gridview the record of sumit will be shown ..by default gridview display alll records from table1

How to do this ?

My Selct Query is below : but it doesnot display all record ...but it can display record if you search for a particular record ...

```<code>SELECT a1_admins.EmployeeId, a1_admins.Firstname, a1_admins.Lastname, a1_admins.Email
, a1_admins.City, a1_admins.State, a1_admins.Country, aspnet_Membership.LastLoginDate
, aspnet_Membership.CreateDate, a1_admins.Password, a1_admins.pan_no, a1_admins.Contactno
, a1_admins.Address
FROM a1_admins
INNER JOIN aspnet_Membership
ON a1_admins.UserId = aspnet_Membership.UserId
WHERE (a1_admins.EmployeeId LIKE N'%' + @EmployeeId + N'%')
    OR (a1_admins.City LIKE N'%' + @City + N'%')
    OR (a1_admins.State LIKE N'%' + @State + N'%')
    OR (a1_admins.Country LIKE N'%' + @Country + N'%')
</code>```

答:
I assume the variables are set to NULL when not filtered?
That would cause the LIKEs to fail, since X LIKE NULL cannot be true.

```<code>SELECT
  a1_admins.EmployeeId, a1_admins.Firstname, a1_admins.Lastname, a1_admins.Email,
  a1_admins.City, a1_admins.State, a1_admins.Country, aspnet_Membership.LastLoginDate,
  aspnet_Membership.CreateDate, a1_admins.Password, a1_admins.pan_no, a1_admins.Contactno, a1_admins.Address
FROM a1_admins
INNER JOIN aspnet_Membership ON a1_admins.UserId = aspnet_Membership.UserId
WHERE (a1_admins.EmployeeId LIKE N'%' + @EmployeeId + N'%')
   OR (a1_admins.City LIKE N'%' + @City + N'%')
   OR (a1_admins.State LIKE N'%' + @State + N'%')
   OR (a1_admins.Country LIKE N'%' + @Country + N'%')
   OR (Coalesce(@employeeid,@city,@state,@country) is null)
</code>```

You can add the last clause, which shows everything if all of the filters are not set.

ContentLicense: CC BY-SA 2.5

Body:
My database : table1

ID             FIRSTNAME              AGE
1              Sumit                  22
2              Sanjeev                23

i  have gridview 1 and textbox1 and button1

i want when pages load the gridview displays the all records from table1 and also ...i i wanna search record for firstname by typing sumit in textbox1 and click on button1 then in gridview the record of sumit will be shown ..by default gridview display alll records from table1

How to do this ?

My Selct Query is below : but it doesnot display all record ...but it can display record if you search for a particular record ...

SELECT a1_admins.EmployeeId, a1_admins.Firstname, a1_admins.Lastname, a1_admins.Email
, a1_admins.City, a1_admins.State, a1_admins.Country, aspnet_Membership.LastLoginDate
, aspnet_Membership.CreateDate, a1_admins.Password, a1_admins.pan_no, a1_admins.Contactno
, a1_admins.Address
FROM a1_admins
INNER JOIN aspnet_Membership
ON a1_admins.UserId = aspnet_Membership.UserId
WHERE (a1_admins.EmployeeId LIKE N'%' + @EmployeeId + N'%')
    OR (a1_admins.City LIKE N'%' + @City + N'%')
    OR (a1_admins.State LIKE N'%' + @State + N'%')
    OR (a1_admins.Country LIKE N'%' + @Country + N'%')

Body:
I assume the variables are set to NULL when not filtered?
That would cause the LIKEs to fail, since X LIKE NULL cannot be true.

SELECT
  a1_admins.EmployeeId, a1_admins.Firstname, a1_admins.Lastname, a1_admins.Email,
  a1_admins.City, a1_admins.State, a1_admins.Country, aspnet_Membership.LastLoginDate,
  aspnet_Membership.CreateDate, a1_admins.Password, a1_admins.pan_no, a1_admins.Contactno, a1_admins.Address
FROM a1_admins
INNER JOIN aspnet_Membership ON a1_admins.UserId = aspnet_Membership.UserId
WHERE (a1_admins.EmployeeId LIKE N'%' + @EmployeeId + N'%')
   OR (a1_admins.City LIKE N'%' + @City + N'%')
   OR (a1_admins.State LIKE N'%' + @State + N'%')
   OR (a1_admins.Country LIKE N'%' + @Country + N'%')
   OR (Coalesce(@employeeid,@city,@state,@country) is null)

You can add the last clause, which shows everything if all of the filters are not set.


问:
Saving a json request as an Image in Flask
I have a flask get request like this

```<code>content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,...]}
</code>```

My image file is with the key data.

```<code>data = content['myphoto']['buffer']['data']
</code>```

I am unable to save it as a jpeg file.

I am not sure how to decode this object as an image as its currently a list.

答:
If I correctly understood your question, it could be done like this:

```<code>#!/usr/bin/env python3

content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,20]}}}
data = content['myPhoto']['buffer']['data']
str_data = ''.join(chr(d) for d in data) # build string using list comprehension
bytes_data = str_data.encode() # build bytes array from string
with open('output.jpg', 'wb') as f: # open file for writing bytes
    f.write(bytes_data) # write bytes array to file
</code>```

Code of course is not perfect and could be used as starting point.

Body:
I have a flask get request like this

content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,...]}

My image file is with the key data.

data = content['myphoto']['buffer']['data']

I am unable to save it as a jpeg file.

I am not sure how to decode this object as an image as its currently a list.

Body:
If I correctly understood your question, it could be done like this:

#!/usr/bin/env python3

content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,20]}}}
data = content['myPhoto']['buffer']['data']
str_data = ''.join(chr(d) for d in data) # build string using list comprehension
bytes_data = str_data.encode() # build bytes array from string
with open('output.jpg', 'wb') as f: # open file for writing bytes
    f.write(bytes_data) # write bytes array to file

Code of course is not perfect and could be used as starting point.


问:
urllib2.urlopen with pandas data

Hi,
I query the google places api with data from a outlook.csv export.
For example: Fronäckerstr. 24","Sindelfingen","71063","Deutschland

I read the data with pandas.

```<code> pd.read_csv('/contacts.CSV')...
</code>```

```<code>    place = urllib2.quote(street + '+' + city + '+' + postcode + '+' + country)
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' \
        + place \
        + google_key

    data = json.loads(urllib2.urlopen(url).read())
</code>```

The url: https://maps.googleapis.com/maps/api/geocode/json?address=Fron%E4ckerstr.%2024%2BSindelfingen%2B71063%2BDeutschland&key=ABCD

I always get :HTTPError: HTTP Error 400: Bad Request
I can't figure out why

答: One of parameter you are passing in the url is non-UTF-8 string, That is why you are getting 'HTTPError: HTTP Error 400: Bad Request'.</p>

Title: urllib2.urlopen with pandas data

Body:
Hi,
I query the google places api with data from a outlook.csv export.
For example: Fronäckerstr. 24","Sindelfingen","71063","Deutschland

I read the data with pandas.

 pd.read_csv('/contacts.CSV')...

    place = urllib2.quote(street + '+' + city + '+' + postcode + '+' + country)
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' \
        + place \
        + google_key

    data = json.loads(urllib2.urlopen(url).read())

The url: https://maps.googleapis.com/maps/api/geocode/json?address=Fron%E4ckerstr.%2024%2BSindelfingen%2B71063%2BDeutschland&key=ABCD

I always get :HTTPError: HTTP Error 400: Bad Request
I can't figure out why


问:
Listen preference change and transfer boolean in checkbox to MainActivity
I have 2 file:

control_preferences.xml:`

```<code><PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>
</code>```

`

SettingsActivity.java:

```<code>package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}
</code>```

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

答:
@Jawegiel

I insert this to:

```<code>public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);

            final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

            checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
            {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {

                    Toast.makeText(getActivity().getApplicationContext(), "CLICK",
                            Toast.LENGTH_SHORT).show();

                    return false;
                }
            });
        }
    }
</code>```

and it works :)

Thank you both :)

Body:
I have 2 file:

control_preferences.xml:`

<PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>

`

SettingsActivity.java:

package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

Body:
@Jawegiel

I insert this to:

public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);

            final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

            checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
            {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {

                    Toast.makeText(getActivity().getApplicationContext(), "CLICK",
                            Toast.LENGTH_SHORT).show();

                    return false;
                }
            });
        }
    }

and it works :)

Thank you both :)


问:
connect my android app with other websites for runtime search and update
I want to create an app like cleartrip or any other flight booking app. But i want to know how can i access the details of flights from respective airlines in such a way that if a ticket is booked from my app then it should also be affect the particular airlines website. Or if a ticket is booked in the respective airlines website the it should also affect in my app. I want to know the logic of how to make my app work in sync with airlines. can i achieve this with the help of api of respective airlines?  </p>

答:
The easiest solution would be to use a service that provides you the API for all airlines. One of the examples is Travelport API.

The API can help you get all the details for airlines and also enable you to book tickets. You'll need to pay them for the API usage and also need to get well acquainted with their docs in order to use the API.


问:
how to get the second (third...) occurence of a substring in xslt?
I have a long String separated with the equal sign(=)as delimiter,something like this:

```<code>AAA=BBBBB=CCCCCCCCCCCCCCCC=D=FFFFF=GG=H
</code>```

The substrings can have arbitrary length.If I want to get the first substring I can use the substring-before function like this:

```<code><xsl:value-of select="substring-before($vari, '=')"/>
</code>```

But is there a way to get only the second, (third, etc) substring?
I need BBBBB instead of AAA=BBBBB and CCCCCCCCCCCCCCCC instead of  AAA=BBBBB=CCCCCCCCCCCCCCCC so substring-before-last won't work.

答:
Here is an xslt-1.0 solution that doesn't require the use of extensions and works with arbitrary separator lengths an separator occurrences:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:call-template name="substring-nth-occurrence-position">
      <xsl:with-param name="string">aaa_#bbb_#ccc_#dddd_#ee</xsl:with-param>
      <xsl:with-param name="substr">_#</xsl:with-param>
      <xsl:with-param name="occurrence">3</xsl:with-param>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="substring-nth-occurrence-position">
    <xsl:param name="string"/>
    <xsl:param name="substr"/>
    <xsl:param name="occurrence"/>
    <xsl:param name="current_iteration" select="1"/>
    <xsl:param name="accumulated_length" select="0"/>

    <xsl:choose>
      <!-- in case occurrence is greater than the number of instances of substr return 0 -->
      <xsl:when test="not(contains($string, $substr))">0</xsl:when>

      <xsl:otherwise>
        <!-- determine the position of the next instance of substr in the (remaining part of ) string and add it to accumulated_length-->
        <xsl:variable name="v.accumulated_length_new">
          <xsl:variable name="v.idx.of.substr">
            <xsl:call-template name="instr">
              <xsl:with-param name="string" select="$string"/>
              <xsl:with-param name="substr" select="$substr"/>
            </xsl:call-template>
          </xsl:variable>

          <xsl:value-of select="$accumulated_length + $v.idx.of.substr"></xsl:value-of>
        </xsl:variable>

        <!-- if current_iteration equals occurrence then return accumulated length... -->
        <xsl:choose>
          <xsl:when test="$current_iteration= $occurrence ">
            <xsl:value-of select="$v.accumulated_length_new" />
          </xsl:when>

          <!-- ... else run another iteration-->
          <xsl:otherwise>
            <xsl:call-template name="substring-nth-occurrence-position">
              <xsl:with-param name="string" select="substring-after($string, $substr)"/>
              <xsl:with-param name="substr" select="$substr"/>
              <xsl:with-param name="occurrence" select="$occurrence"/>
              <xsl:with-param name="current_iteration" select="$current_iteration + 1"/>
              <xsl:with-param name="accumulated_length" select="$v.accumulated_length_new + string-length($substr) - 1"/>
            </xsl:call-template>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- returns the position of the first occurrence of a substring in a string -->
  <xsl:template name="instr">
    <xsl:param name="string"/>
    <xsl:param name="substr"/>
    <xsl:value-of select="contains($string,$substr)*(1 + string-length(substring-before($string,$substr)))"  />
  </xsl:template>

</xsl:stylesheet>
</code>```

(Execution result of the above example is 14).

Body:
I have a long String separated with the equal sign(=)as delimiter,something like this:

AAA=BBBBB=CCCCCCCCCCCCCCCC=D=FFFFF=GG=H

The substrings can have arbitrary length.If I want to get the first substring I can use the substring-before function like this:

<xsl:value-of select="substring-before($vari, '=')"/>

But is there a way to get only the second, (third, etc) substring?
I need BBBBB instead of AAA=BBBBB and CCCCCCCCCCCCCCCC instead of  AAA=BBBBB=CCCCCCCCCCCCCCCC so substring-before-last won't work.

Body:
Here is an xslt-1.0 solution that doesn't require the use of extensions and works with arbitrary separator lengths an separator occurrences:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:call-template name="substring-nth-occurrence-position">
      <xsl:with-param name="string">aaa_#bbb_#ccc_#dddd_#ee</xsl:with-param>
      <xsl:with-param name="substr">_#</xsl:with-param>
      <xsl:with-param name="occurrence">3</xsl:with-param>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="substring-nth-occurrence-position">
    <xsl:param name="string"/>
    <xsl:param name="substr"/>
    <xsl:param name="occurrence"/>
    <xsl:param name="current_iteration" select="1"/>
    <xsl:param name="accumulated_length" select="0"/>

    <xsl:choose>
      <!-- in case occurrence is greater than the number of instances of substr return 0 -->
      <xsl:when test="not(contains($string, $substr))">0</xsl:when>

      <xsl:otherwise>
        <!-- determine the position of the next instance of substr in the (remaining part of ) string and add it to accumulated_length-->
        <xsl:variable name="v.accumulated_length_new">
          <xsl:variable name="v.idx.of.substr">
            <xsl:call-template name="instr">
              <xsl:with-param name="string" select="$string"/>
              <xsl:with-param name="substr" select="$substr"/>
            </xsl:call-template>
          </xsl:variable>

          <xsl:value-of select="$accumulated_length + $v.idx.of.substr"></xsl:value-of>
        </xsl:variable>

        <!-- if current_iteration equals occurrence then return accumulated length... -->
        <xsl:choose>
          <xsl:when test="$current_iteration= $occurrence ">
            <xsl:value-of select="$v.accumulated_length_new" />
          </xsl:when>

          <!-- ... else run another iteration-->
          <xsl:otherwise>
            <xsl:call-template name="substring-nth-occurrence-position">
              <xsl:with-param name="string" select="substring-after($string, $substr)"/>
              <xsl:with-param name="substr" select="$substr"/>
              <xsl:with-param name="occurrence" select="$occurrence"/>
              <xsl:with-param name="current_iteration" select="$current_iteration + 1"/>
              <xsl:with-param name="accumulated_length" select="$v.accumulated_length_new + string-length($substr) - 1"/>
            </xsl:call-template>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- returns the position of the first occurrence of a substring in a string -->
  <xsl:template name="instr">
    <xsl:param name="string"/>
    <xsl:param name="substr"/>
    <xsl:value-of select="contains($string,$substr)*(1 + string-length(substring-before($string,$substr)))"  />
  </xsl:template>

</xsl:stylesheet>

(Execution result of the above example is 14).


问:
How do I go about extracting only relevant JSON data from this web service
So I need to implement an external web service to include remote data, combined with my own local data, of various events in the United Kingdom. These events will be produced upon a search of keywords, such as name or date. I'm going to use the eventful api, and this is what I have found:

```<code>  Javascript Sample page <br>
  <script type="text/javascript" src="http://api.eventful.com/js/api">
  </script>
  <script type="text/javascript">
  function show_alert()
  {
    var oArgs = {
              app_key:"MY APP KEY",
              id: "20218701",
              page_size: 25 ,
    };
    EVDB.API.call("/events/get", oArgs, function(oData) {
        // Note: this relies on the custom toString() methods below    });
        alert("your myObject is " + JSON.stringify(oData) );
    });

  }
  function show_alert2()
  {
     var oArgs = {
        app_key: "MY APP KEY",
        q: "music",
        where: "United Kingdom",
        "date": "2013061000-2015062000",
        page_size: 5,
        sort_order: "popularity",
     };
     EVDB.API.call("/events/search", oArgs, function(oData) {
        // Note: this relies on the custom toString() methods below
        alert("your myObject is " + JSON.stringify(oData));
      });
  }
  </script>
</code>```

So for example, when the alert is called I get a long string of JSON data relating to that hardcoded search.

My question is how do I extract only the relevant data from that long string? Here's an example string:

https://pastebin.com/gdHZdQT9

I only want core data, such as the events name, description, date, and the venue name, town, and postcode.

UPDATED:

```<code>  <script type="text/javascript" src="http://api.eventful.com/js/api">
  </script>
  <script type="text/javascript">

  function show_alert2()
  {
     var oArgs = {
        app_key: "MY KEY",
        q: "music",
        where: "United Kingdom",
        "date": "2013061000-2015062000",
        page_size: 5,
        sort_order: "popularity",
     };
     EVDB.API.call("/events/search", oArgs, function(oData) {
        // Note: this relies on the custom toString() methods below
        //alert("your myObject is " + JSON.stringify(oData));
        let obj = JSON.stringify(oData);
        return obj;
        //var data = oData;
      });
  }

  function simplifyObject(obj){
  return obj.events.event.map((x) => { return { title: x.title, description: x.description, date: x.start_time, venue_name: x.venue_name, venue_address: x.venue_address, postal_code: x.postal_code } });
  }
  var result = simplifyObject(obj);//result is an array of objects
  console.log(result[0].title);//for 1st object's title
  </script>
</code>```

Current search code:

My initial thought was to do a onkeydown="show_alert2()"> which triggers the function above to produce the var result.

```<code><div class="panel panel-default" onkeydown="show_alert2()">
  <div class="panel-heading" ng-init="getEvents()">
    <h3 class="panel-title">Latest events</h3>
  </div>
  <div>
  <input type="text" ng-model="search" placeholder="Search for events, venues, or dates" size="40">
  <div class="panel-body">
    <div class="row">
        <div ng-repeat="event in events | filter:search">
            <div class="col-md-3">
                <div class="col-md-6">
                    <h4>{{event.title}}</h4>
                    <p>{{event.desc}}</p>
            <p>{{event.venue.name}}</p>
                    <a class="btn btn-primary" href="#!/events/details/{{event._id}}">View event</a>
                </div>
                <div class="col-md-6">
                    <img class="thumbnail" src="{{event.venue.icon}}">
                </div>
            </div>
    </div>
  </div>
  </div>
  </div>
</code>```

答:
Do it like this,</p>

```<code>var obj = JSON.parse(oData);
function simplifyObject(obj){
  return obj.events.event.map((x) => { return { title: x.title, description: x.description, date: x.start_time, venue_name: x.venue_name, venue_address: x.venue_address, postal_code: x.postal_code } });
}
var result = simplifyObject(obj);//result is an array of objects
console.log(result[0].title);//for 1st object's title
</code>```

Body:
So I need to implement an external web service to include remote data, combined with my own local data, of various events in the United Kingdom. These events will be produced upon a search of keywords, such as name or date. I'm going to use the eventful api, and this is what I have found:

  Javascript Sample page

So for example, when the alert is called I get a long string of JSON data relating to that hardcoded search.

My question is how do I extract only the relevant data from that long string? Here's an example string:

https://pastebin.com/gdHZdQT9

I only want core data, such as the events name, description, date, and the venue name, town, and postcode.

UPDATED:

Current search code:

My initial thought was to do a onkeydown="show_alert2()"> which triggers the function above to produce the var result.

Latest events

  <input type="text" ng-model="search" placeholder="Search for events, venues, or dates" size="40">

{{event.title}}

{{event.desc}}

{{event.venue.name}}

                    View event

Body:
Do it like this,

var obj = JSON.parse(oData);
function simplifyObject(obj){
  return obj.events.event.map((x) => { return { title: x.title, description: x.description, date: x.start_time, venue_name: x.venue_name, venue_address: x.venue_address, postal_code: x.postal_code } });
}
var result = simplifyObject(obj);//result is an array of objects
console.log(result[0].title);//for 1st object's title


问:
preparing data for vegan NMDS in R
I'd like to run an NMDS and PERMANOVA on subsets of my data using vegan in R. My data contains a lot of zeroes and looks like this:

```<code>> str(invert)
'data.frame':   96 obs. of  67 variables:
 $ SampleID                       : Factor w/ 96 levels "11-1-E-1","11-1-E-2",..: 61 62 63 49 50 51 85 86 87 73 ...
 $ SampleDate                     : Factor w/ 8 levels "17-Aug-12","17-Oct-12",..: 1 1 1 6 6 6 2 2 2 4 ...
 $ Year                           : int  2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
 $ Month                          : Factor w/ 4 levels "August","July",..: 1 1 1 2 2 2 3 3 3 4 ...
 $ Habitat                        : Factor w/ 4 levels "epiphyte","pool",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ N                              : num  1429 143 1705 1147 212 ...
 $ S                              : int  6 2 8 9 4 5 6 8 5 5 ...
 $ Aeshnidae                      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Anax                : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Gynacantha          : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Oplonaeschna        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Anisoptera                     : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ant                            : num  0 0 0 0 0 0 0 0 0 0 ...
</code>```

As you can see, there are four levels of "Habitat". I would like to analyse each habitat separately. I have tried subsetting, but this means I have to do it four times (one for each habitat). Is there a more efficient way of doing it?

This is how I subsetted for the pool habitat:

```<code>invert[6:67] <- lapply(invert[6:67], as.numeric)
pool <- subset(invert, Habitat=="pool")

ord <- metaMDS(pool[,7:67],
               k=2,
               trymax = 1000,
               autotransform = TRUE,
               expand = FALSE,
               plot = FALSE)

plot(ord$points[,2],ord$points[,1], type="n",
     main="Communities by month",
     xlab="NMDS 1",
     ylab="NMDS 2",
     xlim=c(-1.5,1.5),
     ylim=c(-1.5,1.5))
ordisymbol(ord, pool, factor="Month", cex=1.25, rainbow=T, legend=T)

#run PERMANOVA;
adonis(pool[,8:67] ~ pool$Month)
</code>```

答:
You should run all the species x sites in a matrix form for your nmds, and then create a group object specifying which rows are from which habitat.
For example, if the first 6 rows of my matrix came from urbanized areas and then the next 6 came from the rain forest I would create a grouping object like this:</p>

```<code>habitattypes<-c(rep("Urbanized",16), rep("RainForest",16))
Permanova<-adonis(yourdata^0.25~habitattypes, permutations = 999, method = "bray")
</code>```

Title: preparing data for vegan NMDS in R

Body:
I'd like to run an NMDS and PERMANOVA on subsets of my data using vegan in R. My data contains a lot of zeroes and looks like this:

> str(invert)
'data.frame':   96 obs. of  67 variables:
 $ SampleID                       : Factor w/ 96 levels "11-1-E-1","11-1-E-2",..: 61 62 63 49 50 51 85 86 87 73 ...
 $ SampleDate                     : Factor w/ 8 levels "17-Aug-12","17-Oct-12",..: 1 1 1 6 6 6 2 2 2 4 ...
 $ Year                           : int  2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
 $ Month                          : Factor w/ 4 levels "August","July",..: 1 1 1 2 2 2 3 3 3 4 ...
 $ Habitat                        : Factor w/ 4 levels "epiphyte","pool",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ N                              : num  1429 143 1705 1147 212 ...
 $ S                              : int  6 2 8 9 4 5 6 8 5 5 ...
 $ Aeshnidae                      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Anax                : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Gynacantha          : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Aeshnidae..Oplonaeschna        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Anisoptera                     : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ant                            : num  0 0 0 0 0 0 0 0 0 0 ...

As you can see, there are four levels of "Habitat". I would like to analyse each habitat separately. I have tried subsetting, but this means I have to do it four times (one for each habitat). Is there a more efficient way of doing it?

This is how I subsetted for the pool habitat:

invert[6:67] <- lapply(invert[6:67], as.numeric)
pool <- subset(invert, Habitat=="pool")

ord <- metaMDS(pool[,7:67],
               k=2,
               trymax = 1000,
               autotransform = TRUE,
               expand = FALSE,
               plot = FALSE)

plot(ord$points[,2],ord$points[,1], type="n",
     main="Communities by month",
     xlab="NMDS 1",
     ylab="NMDS 2",
     xlim=c(-1.5,1.5),
     ylim=c(-1.5,1.5))
ordisymbol(ord, pool, factor="Month", cex=1.25, rainbow=T, legend=T)

#run PERMANOVA;
adonis(pool[,8:67] ~ pool$Month)

Body:
You should run all the species x sites in a matrix form for your nmds, and then create a group object specifying which rows are from which habitat.
For example, if the first 6 rows of my matrix came from urbanized areas and then the next 6 came from the rain forest I would create a grouping object like this:

habitattypes<-c(rep("Urbanized",16), rep("RainForest",16))
Permanova<-adonis(yourdata^0.25~habitattypes, permutations = 999, method = "bray")


问:
Ordering local storage score in an ascending order
I want the data in the table to be in an ascending order, so the person with the highest score should be at the top of the table, and the person with the lowest score to be at the bottom of the table. I've created an array and used a for loop to order the data, but nothing displays on the table. I've created a JSFiddle Here</p>

```<code>/* Rank Table */
function displayTable() {
    var data = [];
    data = {firstName: data.FirstName, lastName: data.LastName, topScore: data.Score};
    var getData = function(key){return JSON.parse(localStorage[key]);}
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th><th>Score</th></tr>\n";
    for (var key in localStorage) {
        if (key !== 'loggedInUser') {
            data = getData(key);
            for (var i = 0; i < data.length; i++) {
                highScoreTable += "<tr><td>" + data[i].firstName + "</td><td>" + data[i].lastName + "</td><td>" + data[i].topScore + "</td></tr>";
            }
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}
</code>```

答:
Few things are wrong with your implementation, kindly see below for change I made to your code:

```<code>/* Register */
function storeUserDetail() {
  const fNameInput = document.getElementById("firstNameInput").value;
  const lNameInput = document.getElementById("lastNameInput").value;
  const uNameInput = document.getElementById("userNameInput").value;
  const pWordInput = document.getElementById("passWordInput").value;
  const yourScoreInput = document.getElementById("scoreInput").value;

  const storeDetails = {
    firstName: fNameInput,
    lastName: lNameInput,
    username: uNameInput,
    password: pWordInput,
    score: yourScoreInput
  };

  const username = storeDetails.username;

  // save details to localStorage using username as key
  localStorage[username] = JSON.stringify(storeDetails);
}

/* Log In */
function loginUser() {
  const username = document.getElementById("uNameInput").value;
  const password = document.getElementById("pWordInput").value;
  const storeDetails = JSON.parse(localStorage[username]);

  storeDetails.username = document.getElementById("uNameInput").value;
  storeDetails.password = document.getElementById("pWordInput").value;

  localStorage.loggedInUser = username;
}

const data = [];

const getData = key => {
  return JSON.parse(localStorage[key]);
};

/* Rank Table */
function displayTable() {
  let tableBody = '';
  const tableHeader =
    "<tr><th>First Name</th><th>Last Name</th><th>Score</th></tr>\n";

  for (let key in localStorage) {
    if (key !== "loggedInUser") {
      data.push(getData(key));
    }
  }

  for (let user of data) {
    if (tableBody) {
      tableBody +=
        `<tr><td>
        ${user.firstName}
        </td><td>
        ${user.lastName}
        </td><td>
        ${user.score}
        </td></tr>`;
    } else {
      tableBody =
        `<tr><td>
        ${user.firstName}
        </td><td>
        ${user.lastName}
        </td><td>
        ${user.score}
        </td></tr>`;
    }
  }

  document.getElementById("rankTable").innerHTML = "";
  document.getElementById("rankTable").innerHTML = tableHeader + tableBody;
}
</code>```

You can view full source here.

Body:
I want the data in the table to be in an ascending order, so the person with the highest score should be at the top of the table, and the person with the lowest score to be at the bottom of the table. I've created an array and used a for loop to order the data, but nothing displays on the table. I've created a JSFiddle Here

/* Rank Table */
function displayTable() {
    var data = [];
    data = {firstName: data.FirstName, lastName: data.LastName, topScore: data.Score};
    var getData = function(key){return JSON.parse(localStorage[key]);}
    var highScoreTable = "
First Name	Last Name	Score
\n";
    for (var key in localStorage) {
        if (key !== 'loggedInUser') {
            data = getData(key);
            for (var i = 0; i < data.length; i++) {
                highScoreTable += "
" + data[i].firstName + "	" + data[i].lastName + "	" + data[i].topScore + "
";
            }
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}

Body:
Few things are wrong with your implementation, kindly see below for change I made to your code:

/* Register */
function storeUserDetail() {
  const fNameInput = document.getElementById("firstNameInput").value;
  const lNameInput = document.getElementById("lastNameInput").value;
  const uNameInput = document.getElementById("userNameInput").value;
  const pWordInput = document.getElementById("passWordInput").value;
  const yourScoreInput = document.getElementById("scoreInput").value;

  const storeDetails = {
    firstName: fNameInput,
    lastName: lNameInput,
    username: uNameInput,
    password: pWordInput,
    score: yourScoreInput
  };

  const username = storeDetails.username;

  // save details to localStorage using username as key
  localStorage[username] = JSON.stringify(storeDetails);
}

/* Log In */
function loginUser() {
  const username = document.getElementById("uNameInput").value;
  const password = document.getElementById("pWordInput").value;
  const storeDetails = JSON.parse(localStorage[username]);

  storeDetails.username = document.getElementById("uNameInput").value;
  storeDetails.password = document.getElementById("pWordInput").value;

  localStorage.loggedInUser = username;
}

const data = [];

const getData = key => {
  return JSON.parse(localStorage[key]);
};

/* Rank Table */
function displayTable() {
  let tableBody = '';
  const tableHeader =
    "<tr><th>First Name</th><th>Last Name</th><th>Score</th></tr>\n";

  for (let key in localStorage) {
    if (key !== "loggedInUser") {
      data.push(getData(key));
    }
  }

  for (let user of data) {
    if (tableBody) {
      tableBody +=
        `<tr><td>
        ${user.firstName}
        </td><td>
        ${user.lastName}
        </td><td>
        ${user.score}
        </td></tr>`;
    } else {
      tableBody =
        `<tr><td>
        ${user.firstName}
        </td><td>
        ${user.lastName}
        </td><td>
        ${user.score}
        </td></tr>`;
    }
  }

  document.getElementById("rankTable").innerHTML = "";
  document.getElementById("rankTable").innerHTML = tableHeader + tableBody;
}

You can view full source here.


问:
C - Use sigsuspend in a thread doesn't work
for a homework assignment I have to use only linux system calls to manage signals in a game, programmed in C.
One thing I have to do, it's to call indefinitly sigsuspend in a thread and wait for a SIGALRM,then if there is a sigalarm (signal alarm) I have to printf() something (doesn't matter what).

However, I tried several things but it doesn't work, I don't know how to "deblock" sigsuspend and print what  i want. And there is a timer in the game which send sigalrm. My code works but not the part with the sigsuspend
Of course I have also a sigarlm handler which does some stuff with SDL when it receives a sigarlm.
I don't really how I have to use masks with sigsuspend

Code :

```<code>//initialising sigaction struct
int init (void)

{
  // Signal handler
  sigact.sa_handler = sigalrm_handler;
  sigact.sa_flags = 0;
  sigemptyset(&sigact.sa_mask);

  // Linked list
  head = NULL;

  sigaction(SIGALRM, &sigact, NULL);
  pthread_create(&tid_sigrecv, NULL, (void *)deamon, NULL);
  return 1; // Implementation ready ?
}
</code>```

The sigsuspend part

```<code>void deamon(void * arg)
{
  int sig;
  while(1) {
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigsuspend(&mask);
    printf("in thread\n");
  }
}
</code>```

Currently it only does not print "in thread" when a sigarlm is received, what should I do to use sigsuspend properly ? I am obliged to use sigsuspend

答:
You create a thread that should wait for the signal SIGALRM thanks to sigsuspend(), but instead you open the thread to all signals but SIGALRM.

Replace

```<code>sigemptyset(&mask);         // clear mask
sigaddset(&mask, SIGALRM);  // set mask to SIGALRM
sigsuspend(&mask);          // wait for any signal but blocks SIGALRM
</code>```

with

```<code>sigfillset(&mask);          // mask set to all signals
sigdelset(&mask, SIGALRM);  // remove SIGALRM from the mask
sigsuspend(&mask);          // block all signals but SIGALRM
</code>```

this way sigsuspend() waits for a non blocked signal (SIGALRM).

For testing, you could send the thread the SIGALRM signal using

```<code>pthread_kill(tid_sigrecv, SIGALRM);
</code>```

from the main thread, for instance.

Body:
for a homework assignment I have to use only linux system calls to manage signals in a game, programmed in C.
One thing I have to do, it's to call indefinitly sigsuspend in a thread and wait for a SIGALRM,then if there is a sigalarm (signal alarm) I have to printf() something (doesn't matter what).

However, I tried several things but it doesn't work, I don't know how to "deblock" sigsuspend and print what  i want. And there is a timer in the game which send sigalrm. My code works but not the part with the sigsuspend
Of course I have also a sigarlm handler which does some stuff with SDL when it receives a sigarlm.
I don't really how I have to use masks with sigsuspend

Code :

//initialising sigaction struct
int init (void)

{
  // Signal handler
  sigact.sa_handler = sigalrm_handler;
  sigact.sa_flags = 0;
  sigemptyset(&sigact.sa_mask);

  // Linked list
  head = NULL;

  sigaction(SIGALRM, &sigact, NULL);
  pthread_create(&tid_sigrecv, NULL, (void *)deamon, NULL);
  return 1; // Implementation ready ?
}

The sigsuspend part

void deamon(void * arg)
{
  int sig;
  while(1) {
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigsuspend(&mask);
    printf("in thread\n");
  }
}

Currently it only does not print "in thread" when a sigarlm is received, what should I do to use sigsuspend properly ? I am obliged to use sigsuspend

Body:
You create a thread that should wait for the signal SIGALRM thanks to sigsuspend(), but instead you open the thread to all signals but SIGALRM.

Replace

sigemptyset(&mask);         // clear mask
sigaddset(&mask, SIGALRM);  // set mask to SIGALRM
sigsuspend(&mask);          // wait for any signal but blocks SIGALRM

with

sigfillset(&mask);          // mask set to all signals
sigdelset(&mask, SIGALRM);  // remove SIGALRM from the mask
sigsuspend(&mask);          // block all signals but SIGALRM

this way sigsuspend() waits for a non blocked signal (SIGALRM).

For testing, you could send the thread the SIGALRM signal using

pthread_kill(tid_sigrecv, SIGALRM);

from the main thread, for instance.


问:
Gradle transitive dependency doesn't respect version
I have a Gradle 3.5 project, and in that project I depend on an artifact:

```<code>compile "a.b.c:depProject:1.1.0"
</code>```

"depProject" is a Maven project, where in that project's pom file, it depends on another artifact:

```<code>   <dependency>
        <groupId>org.apache.solr</groupId>
        <artifactId>solr-solrj</artifactId>
        <version>4.4.0</version>
   </dependency>
</code>```

Now, when I perform "gradle dependencies" on my project, it correctly shows that I should get the solrj dependency via transitive dependency resolution, but it doesn't respect the 4.4.0 version declaration, instead my project gains a dependency on version 5.5.4.

```<code>+--- a.b.c:depProject:1.1.0
|    \--- org.apache.solr:solr-solrj:4.4.0 -> 5.5.4
</code>```

These lines appear several times in the dependency report, always the same.

Why is Gradle "upgrading" my dependency automatically?  Is there a way to get this to stop, other than to directly depend on the transitive dependency, specifying the version I want?

Note, if I exclude the solrj dependency in my project via:

```<code>compile ("a.b.c:depProject:1.1.0") {
    exclude group:"org.apache.solr" module:"solr-solrj"
}
</code>```

Then there is NO solrj dependency in the resulting "gradle dependencies" call, so there is no other place that solrj is being depended on at that higher version.

I can't post the entire build.gradle, but I can show what plugins are applied:

```<code>apply plugin:"idea"
apply plugin:"org.grails.grails-web"
apply plugin:"com.moowork.node"
apply plugin:"org.grails.plugins.views-json"
apply plugin: "org.grails.grails-gsp"
apply plugin: "maven"
apply plugin: "codenarc"
apply plugin: "jacoco"
apply plugin: "org.sonarqube"
apply plugin: "asset-pipeline"
</code>```

答:
Gradle only picks a newer version of a dependency if there is a conflict between two transitive dependencies. So either you found a bug in gradle, or something else in your project depends on

```<code>org.apache.solr:solr-solrj:5.5.4
</code>```

Just run

```<code>gradle dependencies | grep -B5 solrj:5
</code>```

And see if there really is no dependency to that version.

You can also force a certain resolution, searching for gradle force version will give you answers quickly, but since this would downgrade solrj, you should first find out what's wrong before deciding.

Body:
I have a Gradle 3.5 project, and in that project I depend on an artifact:

compile "a.b.c:depProject:1.1.0"

"depProject" is a Maven project, where in that project's pom file, it depends on another artifact:

   <dependency>
        <groupId>org.apache.solr</groupId>
        <artifactId>solr-solrj</artifactId>
        <version>4.4.0</version>
   </dependency>

Now, when I perform "gradle dependencies" on my project, it correctly shows that I should get the solrj dependency via transitive dependency resolution, but it doesn't respect the 4.4.0 version declaration, instead my project gains a dependency on version 5.5.4.

+--- a.b.c:depProject:1.1.0
|    \--- org.apache.solr:solr-solrj:4.4.0 -> 5.5.4

These lines appear several times in the dependency report, always the same.

Why is Gradle "upgrading" my dependency automatically?  Is there a way to get this to stop, other than to directly depend on the transitive dependency, specifying the version I want?

Note, if I exclude the solrj dependency in my project via:

compile ("a.b.c:depProject:1.1.0") {
    exclude group:"org.apache.solr" module:"solr-solrj"
}

Then there is NO solrj dependency in the resulting "gradle dependencies" call, so there is no other place that solrj is being depended on at that higher version.

I can't post the entire build.gradle, but I can show what plugins are applied:

apply plugin:"idea"
apply plugin:"org.grails.grails-web"
apply plugin:"com.moowork.node"
apply plugin:"org.grails.plugins.views-json"
apply plugin: "org.grails.grails-gsp"
apply plugin: "maven"
apply plugin: "codenarc"
apply plugin: "jacoco"
apply plugin: "org.sonarqube"
apply plugin: "asset-pipeline"

Body:
Gradle only picks a newer version of a dependency if there is a conflict between two transitive dependencies. So either you found a bug in gradle, or something else in your project depends on

org.apache.solr:solr-solrj:5.5.4

Just run

gradle dependencies | grep -B5 solrj:5

And see if there really is no dependency to that version.

You can also force a certain resolution, searching for gradle force version will give you answers quickly, but since this would downgrade solrj, you should first find out what's wrong before deciding.


问:
How do you solve the error KeyError: 'A secret key is required to use CSRF.' when using a wtform in flask application?
I have been trying to build a web app using flask and wtforms and a firebase database, but I keep getting the error message "KeyError: 'A secret key is required to use CSRF.'" and I don't know how to solve it.
here is my code:</p>

```<code>from flask import Flask, render_template, request
from firebase import firebase
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect, CSRFError
from wtforms import DateField, StringField, TextAreaField
from wtforms.validators import DataRequired
from wtforms_components import TimeField

app = Flask(__name__)

csrf = CSRFProtect(app)

firebase = firebase.FirebaseApplication("https://uhungry-f9563.firebaseio.com", None)

class myForm(FlaskForm):
        event = StringField("event", validators=[DataRequired()])
        location = StringField("location", validators=[DataRequired()])
        startDay = DateField("startDay", validators=[DataRequired()])
        startTime = TimeField("startTime", validators=[DataRequired()])
        endDay = DateField("endDay", validators=[DataRequired()])
        endTime = TimeField("endTime", validators=[DataRequired()])
        details = TextAreaField("details", validators=[DataRequired()])

count = 0

@app.route('/', methods=['GET' , 'POST'])
def home():
    form = myForm()
    if form.validate_on_submit():
        global count
        count += 1
        putData = {'Event': form.event.data, 'Location': form.location.data, 'startDay': form.startDay.data, 'startTime': form.startTime.data,'endDay': form.endDay.data, 'endTime': form.endTime.data, 'Details': form.details.data}
        firebase.put('/events', 'event' + str(count), putData)
        return render_template("trial.html")
    return render_template("home.html")

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
you need to add a SECRET_KEY in the application configuration to take advantage of csrf protection and provide a WRF CSRF SECRET_KEY otherwise your secret key will be used instead</p>

```<code>app.config.update(dict(
    SECRET_KEY="powerful secretkey",
    WTF_CSRF_SECRET_KEY="a csrf secret key"
))
</code>```

Body:
I have been trying to build a web app using flask and wtforms and a firebase database, but I keep getting the error message "KeyError: 'A secret key is required to use CSRF.'" and I don't know how to solve it.
here is my code:

from flask import Flask, render_template, request
from firebase import firebase
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect, CSRFError
from wtforms import DateField, StringField, TextAreaField
from wtforms.validators import DataRequired
from wtforms_components import TimeField

app = Flask(__name__)

csrf = CSRFProtect(app)

firebase = firebase.FirebaseApplication("https://uhungry-f9563.firebaseio.com", None)

class myForm(FlaskForm):
        event = StringField("event", validators=[DataRequired()])
        location = StringField("location", validators=[DataRequired()])
        startDay = DateField("startDay", validators=[DataRequired()])
        startTime = TimeField("startTime", validators=[DataRequired()])
        endDay = DateField("endDay", validators=[DataRequired()])
        endTime = TimeField("endTime", validators=[DataRequired()])
        details = TextAreaField("details", validators=[DataRequired()])

count = 0

@app.route('/', methods=['GET' , 'POST'])
def home():
    form = myForm()
    if form.validate_on_submit():
        global count
        count += 1
        putData = {'Event': form.event.data, 'Location': form.location.data, 'startDay': form.startDay.data, 'startTime': form.startTime.data,'endDay': form.endDay.data, 'endTime': form.endTime.data, 'Details': form.details.data}
        firebase.put('/events', 'event' + str(count), putData)
        return render_template("trial.html")
    return render_template("home.html")

if __name__ == '__main__':
    app.run(debug=True)

Body:
you need to add a SECRET_KEY in the application configuration to take advantage of csrf protection and provide a WRF CSRF SECRET_KEY otherwise your secret key will be used instead

app.config.update(dict(
    SECRET_KEY="powerful secretkey",
    WTF_CSRF_SECRET_KEY="a csrf secret key"
))


问:
rails controller test, getting ActionView::MissingTemplate: Missing template
I figured I should finally write some tests for my rails app.

My controller is "UsersController".  It doesn't have any HTML as I just have an iphone app sending a post in to a rails controller.

Here is my test:

```<code>require 'test_helper'

class UsersControllerTest < ActionController::TestCase

  def test_create
    # to http post
    # /users
    #user[email]=%@&user[password]=%@&user[password_confirmation]=%@
    #post
    post(:create, :user => {:password => "testpassword", :password_confirmation => "testpassword"})
  end
</code>```

Problem is that I get this error:

1) Error:
test_create(UsersControllerTest):
ActionView::MissingTemplate: Missing template users/new with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths

So I guess it's trying to populate an HTML page?  If so, I find this odd.  I would think it would directly do the post to the controller.  Can someone confirm that this "post" method tries and populates an HTML form?

If this is the case, how should I proceed in writing a test to directly send an HTTP post to the controller?

Thanks for any help

答:
Unless you tell it otherwise the post method assumes the requested content type is HTML. Typically the create action looks something like this:

```<code>@user = User.new(params[:user])
if @user.save
  redirect_to posts_path
else
  render :new
end
</code>```

If the action fails it tries to render 'users/new', which doesn't exist, thus the error.

So there are a couple of issues here. It's not clear what content type is expected (XML?). The action is failing, but we can't see why. It might help to edit the question to show us what the controller action does.

Body:
I figured I should finally write some tests for my rails app.

My controller is "UsersController".  It doesn't have any HTML as I just have an iphone app sending a post in to a rails controller.

Here is my test:

require 'test_helper'

class UsersControllerTest < ActionController::TestCase

  def test_create
    # to http post
    # /users
    #user[email]=%@&user[password]=%@&user[password_confirmation]=%@
    #post
    post(:create, :user => {:password => "testpassword", :password_confirmation => "testpassword"})
  end

Problem is that I get this error:

1) Error:
test_create(UsersControllerTest):
ActionView::MissingTemplate: Missing template users/new with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths

So I guess it's trying to populate an HTML page?  If so, I find this odd.  I would think it would directly do the post to the controller.  Can someone confirm that this "post" method tries and populates an HTML form?

If this is the case, how should I proceed in writing a test to directly send an HTTP post to the controller?

Thanks for any help

Body:
Unless you tell it otherwise the post method assumes the requested content type is HTML. Typically the create action looks something like this:

@user = User.new(params[:user])
if @user.save
  redirect_to posts_path
else
  render :new
end

If the action fails it tries to render 'users/new', which doesn't exist, thus the error.

So there are a couple of issues here. It's not clear what content type is expected (XML?). The action is failing, but we can't see why. It might help to edit the question to show us what the controller action does.


问:
Parsing a JSON Response into a Java object
I am new to Android development. I have a node test server running that returns the following json post response

```<code>res.json({ userName: 'test@gmail.com', ratedOn: new Date(), rating: Math.ceil(Math.random() * 5) });
</code>```

I am using gson to parse the response into an object
 Class Definition of the target class

```<code>public class RateWork {
    public int rating;
    public Date ratedOn;
    public String userName;

    public RateWork(int rating, Date ratedOn, String userName){
        this.rating = rating;
        this.ratedOn = ratedOn;
        this.userName = userName;
    }
}
</code>```

In the client(Android side) i am using volley to capture the response.

```<code>StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.API_POST_RATING,

new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("TEST", response);
        RateWork rw = gson.fromJson(response, RateWork.class);
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d("TEST", "Error: " + error.getMessage());
    }
}
</code>```

Log of the response

D/TEST: {"userName":"test@gmail.com","ratedOn":"Sat Dec 09 14:10:49 GMT+05:30 2017","rating":3}

I get an exception at this line -> com.google.gson.JsonSyntaxException

```<code>RateWork rw = gson.fromJson(response, RateWork.class);
</code>```

Please help fix the error.

答:
Use this to create your Gson Object

```<code>Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
</code>```

refer this for more detail

Body:
I am new to Android development. I have a node test server running that returns the following json post response

res.json({ userName: 'test@gmail.com', ratedOn: new Date(), rating: Math.ceil(Math.random() * 5) });

I am using gson to parse the response into an object
 Class Definition of the target class

public class RateWork {
    public int rating;
    public Date ratedOn;
    public String userName;

    public RateWork(int rating, Date ratedOn, String userName){
        this.rating = rating;
        this.ratedOn = ratedOn;
        this.userName = userName;
    }
}

In the client(Android side) i am using volley to capture the response.

StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.API_POST_RATING,

new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("TEST", response);
        RateWork rw = gson.fromJson(response, RateWork.class);
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d("TEST", "Error: " + error.getMessage());
    }
}

Log of the response

D/TEST: {"userName":"test@gmail.com","ratedOn":"Sat Dec 09 14:10:49 GMT+05:30 2017","rating":3}

I get an exception at this line -> com.google.gson.JsonSyntaxException

RateWork rw = gson.fromJson(response, RateWork.class);

Please help fix the error.

Body:
Use this to create your Gson Object

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

refer this for more detail


问:
How to send data from express backend to ejs front end?
I am trying out a Tutorials website and in that some of my pages need to send tutorials object, video object, user object depending on which route they landed. So, is it necessary to send null object even if I don't need them on the front end? I am extracting these backend objects in script tag and assign it to window object for use in angular client.

Here are some sample codes.

```<code>// layout.ejs   common to all front end views
<script>
window.user = <%- typeof user !== 'undefined'? JSON.stringify(user) : null %>
</script>
</code>```

Backend sends this type of code:

```<code>res.render('/partials/index', {
    title: 'Title'
});
</code>```

But when I don't send user as null, it throws ReferenceError: user not defined. Why is it so? I am checking in the script tag if it is undefined, I am using null. Is it wrong?

If we need to explicitly send null from backend, then it seems awkward to send null everytime even though I don't need it. What is right way to do it?

答:
It is because the ternary operator checks both parts (including the one with user) even it is not evaluated because the condition is false.

You either have to include this:

```<code>let user = user || null;
</code>```

Or send an explicit null in the render.

Body:
I am trying out a Tutorials website and in that some of my pages need to send tutorials object, video object, user object depending on which route they landed. So, is it necessary to send null object even if I don't need them on the front end? I am extracting these backend objects in script tag and assign it to window object for use in angular client.

Here are some sample codes.

// layout.ejs   common to all front end views

Backend sends this type of code:

res.render('/partials/index', {
    title: 'Title'
});

But when I don't send user as null, it throws ReferenceError: user not defined. Why is it so? I am checking in the script tag if it is undefined, I am using null. Is it wrong?

If we need to explicitly send null from backend, then it seems awkward to send null everytime even though I don't need it. What is right way to do it?

Body:
It is because the ternary operator checks both parts (including the one with user) even it is not evaluated because the condition is false.

You either have to include this:

let user = user || null;

Or send an explicit null in the render.


问:
Sitecore 8.2 Performance issue / crash
Right so after upgrading to Sitecore 8.2 from 8.1 with split environment i.e CD and CMS. I'm seeing few performance issues, The CMS works fine but the number of threads is around 200 in local! whereas CD just freezes by just consuming all the memory just after starting the site, there no error shown in the log as well.

Any idea what might be wrong ?

答:
We had a similar issue where the CPU usage was spiking but could not find any error in sitecore log files.Also the web traffic was normal as observed from the IIS logs. This is how we resolved the issue.

In IIS user interface and in the application pool where the site is hosted,please check the currently running IIS worker Processes.Here we can see that each request is in different part of ASP.NET pipeline and currently executing HTTP modules.

Now please check whether any requests are getting stuck at any stage.If there are multiple requests coming from the same URL are getting stuck then it means that some module in that URL is getting hung up or going into an infinite loop.Now we can investigate the modules used in this URL and find the actual issue.

Title: Sitecore 8.2 Performance issue / crash