问:
Is there a way you can produce an output like this in T-SQL
I have a column which I translate the values using a case statements and I get numbers like this below. There are multiple columns I need to produce the result like this and this is just one column.

How do you produce the output  as a whole like this below.
The 12 is the total numbers counting from top to bottom
49 is the Average.
4.08 is the division 49/12.
1 is how many 1's are there in the output list above. As you can see there is only one 1 in the output above
8.33% is the division and percentage comes from 1/12 * 100
and so on. Is there a way to produce this output below?

```<code>drop table test111
create table test111
(
Q1 nvarchar(max)
);

INSERT INTO TEST111(Q1)
VALUES('Strongly Agree')
,('Agree')
,('Disagree')
,('Strongly Disagree')
,('Strongly Agree')
,('Agree')
,('Disagree')
,('Neutral');

SELECT
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS 'Test Q1'
FROM test111
</code>```

答:
I must say, this is one of the strangest T-SQL requirements I've seen, and is really best left to the presentation layer.

It is possible using GROUPING SETS though. We can use it to get an extra rollup row that aggregates the whole table.

Once you have the rollup, you need to unpivot the totalled row (identified by GROUPING() = 1) to get your final result. We can do this using CROSS APPLY.

This is impossible without a row-identifier. I have added ROW_NUMBER, but any primary or unique key will do.

WITH YourTable AS (
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rn,
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS TestQ1
FROM test111
),
RolledUp AS (
    SELECT
      rn,
      TestQ1,
      grouping = GROUPING(TestQ1),
      count = COUNT(*),
      sum = SUM(TestQ1),
      avg = AVG(TestQ1 * 1.0),
      one = COUNT(CASE WHEN TestQ1 = 1 THEN 1 END),
      onePct = COUNT(CASE WHEN TestQ1 = 1 THEN 1 END) * 1.0 / COUNT(*)
    FROM YourTable
    GROUP BY GROUPING SETS(
        (rn, TestQ1),
        ()
    )
)
SELECT v.TestQ1
FROM RolledUp r
CROSS APPLY (
    SELECT r.TestQ1, 0 AS ordering
    WHERE r.grouping = 0
    UNION ALL
    SELECT v.value, v.ordering
    FROM (VALUES
        (NULL    , 1),
        (r.count , 2),
        (r.sum   , 3),
        (r.avg   , 4),
        (r.one   , 5),
        (r.onePct, 6)
    ) v(value, ordering)
    WHERE r.grouping = 1
) v
ORDER BY
  v.ordering,
  r.rn;
```

db<>fiddle

Body:
I have a column which I translate the values using a case statements and I get numbers like this below. There are multiple columns I need to produce the result like this and this is just one column.

How do you produce the output  as a whole like this below.
The 12 is the total numbers counting from top to bottom
49 is the Average.
4.08 is the division 49/12.
1 is how many 1's are there in the output list above. As you can see there is only one 1 in the output above
8.33% is the division and percentage comes from 1/12 * 100
and so on. Is there a way to produce this output below?

drop table test111
create table test111
(
Q1 nvarchar(max)
);

INSERT INTO TEST111(Q1)
VALUES('Strongly Agree')
,('Agree')
,('Disagree')
,('Strongly Disagree')
,('Strongly Agree')
,('Agree')
,('Disagree')
,('Neutral');

SELECT
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS 'Test Q1'
FROM test111

Body:
I must say, this is one of the strangest T-SQL requirements I've seen, and is really best left to the presentation layer.

It is possible using GROUPING SETS though. We can use it to get an extra rollup row that aggregates the whole table.

Once you have the rollup, you need to unpivot the totalled row (identified by GROUPING() = 1) to get your final result. We can do this using CROSS APPLY.

This is impossible without a row-identifier. I have added ROW_NUMBER, but any primary or unique key will do.

WITH YourTable AS (
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rn,
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS TestQ1
FROM test111
),
RolledUp AS (
    SELECT
      rn,
      TestQ1,
      grouping = GROUPING(TestQ1),
      count = COUNT(*),
      sum = SUM(TestQ1),
      avg = AVG(TestQ1 * 1.0),
      one = COUNT(CASE WHEN TestQ1 = 1 THEN 1 END),
      onePct = COUNT(CASE WHEN TestQ1 = 1 THEN 1 END) * 1.0 / COUNT(*)
    FROM YourTable
    GROUP BY GROUPING SETS(
        (rn, TestQ1),
        ()
    )
)
SELECT v.TestQ1
FROM RolledUp r
CROSS APPLY (
    SELECT r.TestQ1, 0 AS ordering
    WHERE r.grouping = 0
    UNION ALL
    SELECT v.value, v.ordering
    FROM (VALUES
        (NULL    , 1),
        (r.count , 2),
        (r.sum   , 3),
        (r.avg   , 4),
        (r.one   , 5),
        (r.onePct, 6)
    ) v(value, ordering)
    WHERE r.grouping = 1
) v
ORDER BY
  v.ordering,
  r.rn;

db<>fiddle


来源: stackexchange

问:
Possible to Specify a Parameter For AWS Athena Query?
I did some research and haven't yet found if this is possible, but does anyone know if you can specify a parameter for an AWS Athena Query?

For example, I want my query to be able to filter WHERE merchant_id = {merchant_id}. Is it possible to specify this so that I could use the same query for every merchant I want? And if so, where would I pass in the input to the Athena query?

答:
The accepted answer is not correct anymore. The new v2 query engine for Athena allows for "prepared statements".

prepare my_statement from select * from some_table where variable_to_change = ?

Then, you can execute the prepared statement by passing in a live value like:

execute my_statement using 3

This would execute the above select statement with variable_to_change=3.

https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Typescript complex mapped types that extract generic
Similar to TypeScript Mapped Types: Get element type of array, I have a type, say:

```<code>type A = {
   Item1: Promise<string>,
   Item2: Promise<number>,
   Item3: number
}
</code>```

I'd like to extract the following type from it:

```<code>type A' = {
   Item1: string,
   Item2: number,
   Item3: number
}
</code>```

Note the added complexity of one of the fields NOT being a Promise.

Is this even possible or am I just reaching the limits of typescripts abilities to infer types? I tried fiddling around with mapped types and Record types but I just couldn't figure it out.

UPDATE:

Say I want to do the same with function calls instead:

```<code>type A = {
  Item1: (string, number) => Promise<string>,
  Item2: () => Promise<number>,
  Item3: () => number
}
</code>```

And the desired type is:

```<code>type A' = {
  Item1: (string, number) => string,
  Item2: () => number,
  Item3: () => number
}
</code>```

I thought this would be similar enough to the first case I state but function return values don't seem as straight forward as I would have hoped.

答:
It has gotten easier nowadays with TypeScript 4.5's Awaited utility type:

```<code>type A = {
  Item1: Promise<string>;
  Item2: Promise<number>;
  Item3: number;
  Item4: (arg0: string, arg1: number) => Promise<string>;
  Item5: () => Promise<number>;
  Item6: () => number;
};

type AwaitValues<T> = {
  [K in keyof T]: T[K] extends (...args: infer P) => infer R
    ? (...args: P) => Awaited<R>
    : Awaited<T[K]>;
};

type A2 = AwaitValues<A>;
</code>```

And by hovering A2 we can see its type to be:

```<code>/*
type A2 = {
    Item1: string;
    Item2: number;
    Item3: number;
    Item4: (arg0: string, arg1: number) => string;
    Item5: () => number;
    Item6: () => number;
}
*/
</code>```

Body:
Similar to TypeScript Mapped Types: Get element type of array, I have a type, say:

type A = {
   Item1: Promise<string>,
   Item2: Promise<number>,
   Item3: number
}

I'd like to extract the following type from it:

type A' = {
   Item1: string,
   Item2: number,
   Item3: number
}

Note the added complexity of one of the fields NOT being a Promise.

Is this even possible or am I just reaching the limits of typescripts abilities to infer types? I tried fiddling around with mapped types and Record types but I just couldn't figure it out.

UPDATE:

Say I want to do the same with function calls instead:

type A = {
  Item1: (string, number) => Promise<string>,
  Item2: () => Promise<number>,
  Item3: () => number
}

And the desired type is:

type A' = {
  Item1: (string, number) => string,
  Item2: () => number,
  Item3: () => number
}

I thought this would be similar enough to the first case I state but function return values don't seem as straight forward as I would have hoped.

Body:
It has gotten easier nowadays with TypeScript 4.5's Awaited utility type:

type A = {
  Item1: Promise<string>;
  Item2: Promise<number>;
  Item3: number;
  Item4: (arg0: string, arg1: number) => Promise<string>;
  Item5: () => Promise<number>;
  Item6: () => number;
};

type AwaitValues<T> = {
  [K in keyof T]: T[K] extends (...args: infer P) => infer R
    ? (...args: P) => Awaited<R>
    : Awaited<T[K]>;
};

type A2 = AwaitValues<A>;

And by hovering A2 we can see its type to be:

/*
type A2 = {
    Item1: string;
    Item2: number;
    Item3: number;
    Item4: (arg0: string, arg1: number) => string;
    Item5: () => number;
    Item6: () => number;
}
*/


问:
Code can't reverse the string. It prins empty
```<code>#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}
</code>```

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

```<code>Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;
</code>```

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

```<code>f[i] = x[y-(1+i)];
f[y] = '\0';
</code>```

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

答:
to use the same logic as you have you need

```<code>string f = x;
</code>```

or

```<code>string f(y,' ');
</code>```

to allocate f large enough to hold the resulting string

Body:
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

f[i] = x[y-(1+i)];
f[y] = '\0';

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

Body:
to use the same logic as you have you need

string f = x;

or

string f(y,' ');

to allocate f large enough to hold the resulting string


问:
Selecting row from a bootstrap react Table
i have to display the Data coming from Async Function. and that works very well. (see the Image)
the Table is am starting Empty. but the Data will be displed after the Await.

So the Problem i cant find any Propertie to get the selected row from the Table. is there a method how to do that ??

thank youu

enter image description here

my code :

```<code>import React from 'react';
import {Button,Table,Tab, Tabs} from 'react-bootstrap'
import ReactDOM from "react-dom";

import './index.css'

import App from "./App";
import { createElement } from 'react';

export default class SettingsView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
          List: [],
          MasterChecked: true,
          SelectedList: [],
        };
      }

   // Select/ UnSelect Table rows
  onMasterCheck(e) {
    let tempList = this.state.List;
    // Check/ UnCheck All Items
    tempList.map((user) => (user.selected = e.target.checked));

    //Update State
    this.setState({
      MasterChecked: e.target.checked,
      List: tempList,
      SelectedList: this.state.List.filter((e) => e.selected),
    });
  }

  btnClicked = async () => {
        // Use IPC API to query Electron's main thread and run this method
        const result = await window.api.getNetworkInterfaces()
        console.log(result)

        var table = document.createElement('tbody');
       // var checkbox = document.createElement("input");

        var rowNumber = 0;
        for (const [key, value] of Object.entries(result)) {
            var entryNumber = 0;
            value.forEach(entry => {
                var row = table.insertRow();
                var cell_rowNumber = row.insertCell(0);
                cell_rowNumber.innerHTML = rowNumber++
                var cell_adapterName = row.insertCell(1);
                cell_adapterName.innerHTML = key;
                var cell_family = row.insertCell(2);
                cell_family.innerHTML = entry.family;
                var cell_address = row.insertCell(3);
                cell_address.innerHTML = entry.address;

            })
        }

        var tbody = document.getElementById("networkInterfacesTable").getElementsByTagName("tbody")[0];

        tbody.parentNode.replaceChild(table, tbody);

        this.setState({
            networkInterfaces: 'updated'
        })

    }
    onItemCheck(e) {
        console.log(e);
      }

    render(){
        return (

            <div>
                <h5 className='h1_style'>General Settings</h5>
                <Tabs defaultActiveKey="profile" id="uncontrolled-tab-example" className="mb-3">
                <Tab eventKey="online" title="General">
                <div className='settingInhalt' >
                   <h5 className='h5style' >Language Selection</h5>
                   <div>
                       <div  style={{marginTop:'3%'}}><label style={{marginLeft:'1%',marginBottom:'2%'}}>Language</label><select style={{marginLeft:'20%', width:'30%'}} name='Select Language'  > <option value="">English</option></select>
                       </div>
                   </div>
                </div>
                </Tab>
                <Tab  eventKey="offline" title="Network Adapter">
                <div className='settingInhalt' >
                <Button onClick={this.btnClicked}> Scan Network</Button>
                <Table id="networkInterfacesTable" responsive striped bordered hover>
                        <thead>
                            <tr>
                                <th></th>
                                <th>Adapter Name</th>
                                <th>Description</th>
                                <th>IP Address</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </Table>

                </div>
                </Tab>
                <Tab eventKey="compare" title="GSDML">

                </Tab>
                </Tabs>

            </div>

        );
    }

}

</code>```

答:
Problem resolved. if any one have the same probleme, he can simply use Datagrid from @MUI react.

It will be necessary to implement the useState from react, to refresh the Datagrid view.

the Solution is :

```<code>import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { render } from 'react-dom';

const columns = [
  { field: 'id', headerName: 'ID', width: 90 },
  {
    field: 'firstName',
    headerName: 'First name',
    width: 150,
    editable: true,
  },
  {
    field: 'lastName',
    headerName: 'Last name',
    width: 150,
    editable: true,
  },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    width: 110,
    editable: true,
  },
  {
    field: 'fullName',
    headerName: 'Full name',
    description: 'This column has a value getter and is not sortable.',
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.row.firstName || ''} ${params.row.lastName || ''}`,
  },
];

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },

];

const rowsss = [
  { id: 6, lastName: 'gggg', firstName: 'gggg', age: 40 },

];

class DataGridDemo extends  React.Component{

  constructor() {
    super();

    this.state = {
        list:rows
    };

}

change = async () => {
  // Use IPC API to query Electron's main thread and run this method
  const result = await window.api.getNetworkInterfaces()
  var rowNumber = [];
  for (const [key, value] of Object.entries(result)) {
      var entryNumber = 0;
      value.forEach(entry => {
          rowNumber=[{ id: entry.address, lastName: entry.address, firstName: entry.address, age: entry.address},];

      })
  }

  this.setState({
      list:rowNumber
  })

}

render(){
   return (
  <div style={{ height: 400, width: '100%' }}>
    <button onClick={this.change} >my button</button>
    <DataGrid
      rows={this.state.list}
      columns={columns}
      pageSize={5}
      rowsPerPageOptions={[5]}
      checkboxSelection
      disableSelectionOnClick
    />
  </div>
);

}

}
export default DataGridDemo;
</code>```

Body:
i have to display the Data coming from Async Function. and that works very well. (see the Image)
the Table is am starting Empty. but the Data will be displed after the Await.

So the Problem i cant find any Propertie to get the selected row from the Table. is there a method how to do that ??

thank youu

enter image description here

my code :

import React from 'react';
import {Button,Table,Tab, Tabs} from 'react-bootstrap'
import ReactDOM from "react-dom";

import './index.css'

import App from "./App";
import { createElement } from 'react';

export default class SettingsView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
          List: [],
          MasterChecked: true,
          SelectedList: [],
        };
      }

   // Select/ UnSelect Table rows
  onMasterCheck(e) {
    let tempList = this.state.List;
    // Check/ UnCheck All Items
    tempList.map((user) => (user.selected = e.target.checked));

    //Update State
    this.setState({
      MasterChecked: e.target.checked,
      List: tempList,
      SelectedList: this.state.List.filter((e) => e.selected),
    });
  }

  btnClicked = async () => {
        // Use IPC API to query Electron's main thread and run this method
        const result = await window.api.getNetworkInterfaces()
        console.log(result)

        var table = document.createElement('tbody');
       // var checkbox = document.createElement("input");

        var rowNumber = 0;
        for (const [key, value] of Object.entries(result)) {
            var entryNumber = 0;
            value.forEach(entry => {
                var row = table.insertRow();
                var cell_rowNumber = row.insertCell(0);
                cell_rowNumber.innerHTML = rowNumber++
                var cell_adapterName = row.insertCell(1);
                cell_adapterName.innerHTML = key;
                var cell_family = row.insertCell(2);
                cell_family.innerHTML = entry.family;
                var cell_address = row.insertCell(3);
                cell_address.innerHTML = entry.address;

            })
        }

        var tbody = document.getElementById("networkInterfacesTable").getElementsByTagName("tbody")[0];

        tbody.parentNode.replaceChild(table, tbody);

        this.setState({
            networkInterfaces: 'updated'
        })

    }
    onItemCheck(e) {
        console.log(e);
      }

    render(){
        return (

General Settings

                <Tabs defaultActiveKey="profile" id="uncontrolled-tab-example" className="mb-3">
                <Tab eventKey="online" title="General">

Language Selection

Language<select style={{marginLeft:'20%', width:'30%'}} name='Select Language'  > <option value="">English</option></select>

                </Tab>
                <Tab  eventKey="offline" title="Network Adapter">

                <Button onClick={this.btnClicked}> Scan Network</Button>

                                Adapter Name
                                Description
                                IP Address

                </Tab>
                <Tab eventKey="compare" title="GSDML">

                </Tab>
                </Tabs>

        );
    }

}

Body:
Problem resolved. if any one have the same probleme, he can simply use Datagrid from @MUI react.

It will be necessary to implement the useState from react, to refresh the Datagrid view.

the Solution is :

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { render } from 'react-dom';

const columns = [
  { field: 'id', headerName: 'ID', width: 90 },
  {
    field: 'firstName',
    headerName: 'First name',
    width: 150,
    editable: true,
  },
  {
    field: 'lastName',
    headerName: 'Last name',
    width: 150,
    editable: true,
  },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    width: 110,
    editable: true,
  },
  {
    field: 'fullName',
    headerName: 'Full name',
    description: 'This column has a value getter and is not sortable.',
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.row.firstName || ''} ${params.row.lastName || ''}`,
  },
];

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },

];

const rowsss = [
  { id: 6, lastName: 'gggg', firstName: 'gggg', age: 40 },

];

class DataGridDemo extends  React.Component{

  constructor() {
    super();

    this.state = {
        list:rows
    };

}

change = async () => {
  // Use IPC API to query Electron's main thread and run this method
  const result = await window.api.getNetworkInterfaces()
  var rowNumber = [];
  for (const [key, value] of Object.entries(result)) {
      var entryNumber = 0;
      value.forEach(entry => {
          rowNumber=[{ id: entry.address, lastName: entry.address, firstName: entry.address, age: entry.address},];

      })
  }

  this.setState({
      list:rowNumber
  })

}

render(){
   return (
  <div style={{ height: 400, width: '100%' }}>
    <button onClick={this.change} >my button</button>
    <DataGrid
      rows={this.state.list}
      columns={columns}
      pageSize={5}
      rowsPerPageOptions={[5]}
      checkboxSelection
      disableSelectionOnClick
    />
  </div>
);

}

}
export default DataGridDemo;


问:
I cannot scrape anything with BeautifulSoup
Im using BeautifulSoup to scrape some web contents.

Im learning with this example code,but I always get a "None" response.

Code:

```<code>import urllib2
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html').read())

post = soup.find('div', attrs={'id': 'topmenucontainer'})

print post
</code>```

Any idea what Im doing wrong ?

Thanks!!

答:
I don't think you are doing anything wrong.

It is the second script tag that is confusing BeautifulSoup. The tag looks like this:

```<code><script type='text/javascript'>
<!--//--><![CDATA[//><!--
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage)
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters))
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
       var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
       var imgTitle = (myImage.title) ?
                     "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
       var imgStyle = "display:inline-block;" + myImage.style.cssText
       var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width
                  + "px; height:" + myImage.height
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
       myImage.outerHTML = strNewHTML
    }
}
//--><!]]>
</script>
</code>```

but BeatifulSoup seems to think it is still in a comment or something and includes the rest of the file as content of the script tag.

Try:

```<code>print str(soup.findAll('script')[1])[:2000]
</code>```

and you'll see what I mean.

If you remove the CDATA then you should find the page parses correctly:

```<code>soup = BeautifulSoup(
    urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html')
    .read()
    .replace('<![CDATA[', '').replace('<!]]>', ''))
</code>```

Body:
Im using BeautifulSoup to scrape some web contents.

Im learning with this example code,but I always get a "None" response.

Code:

import urllib2
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html').read())

post = soup.find('div', attrs={'id': 'topmenucontainer'})

print post

Any idea what Im doing wrong ?

Thanks!!

Body:
I don't think you are doing anything wrong.

It is the second script tag that is confusing BeautifulSoup. The tag looks like this:

<script type='text/javascript'>
<!--//--><![CDATA[//><!--
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage)
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters))
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
       var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
       var imgTitle = (myImage.title) ?
                     "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
       var imgStyle = "display:inline-block;" + myImage.style.cssText
       var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width
                  + "px; height:" + myImage.height
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
       myImage.outerHTML = strNewHTML
    }
}
//--><!]]>
</script>

but BeatifulSoup seems to think it is still in a comment or something and includes the rest of the file as content of the script tag.

Try:

print str(soup.findAll('script')[1])[:2000]

and you'll see what I mean.

If you remove the CDATA then you should find the page parses correctly:

soup = BeautifulSoup(
    urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html')
    .read()
    .replace('<![CDATA[', '').replace('<!]]>', ''))


问:
Unit conversion with Bash
I'm writing a bash script that converts units from a very specific input.

I started out doing simple read and echo statements and was able to get it to read a very specific input derived from declared integers and numbers but I'm having trouble getting it to work with if statements.

Here is my simple code so far:

```<code>#!/bin/bash

declare -i n
in=inches
ft=feet

read number in "as" feet
if [ ]; then
    echo "$n $in = $[n/12] $ft"
fi
</code>```

What I want to do now is to create if/else statements to flow according to a number of conditionals dependent on the user input. So I want the user to type something like "24 inches as feet" or "50 yards as inches" and execute its respective output. Right now, I don't really know what to put into the if statements without getting an error like "command not found".

Any help would be appreciated. Thank you.

答:
!/bin/bash

echo "enter a number to be converted"

read number

feet=$(($number*12))

inches=$(($number/12))

```<code>echo "feet conversion to inches="$feet

echo "inches conversion to feet="$inches
</code>```

fi

Title: Unit conversion with Bash

Body:
I'm writing a bash script that converts units from a very specific input.

I started out doing simple read and echo statements and was able to get it to read a very specific input derived from declared integers and numbers but I'm having trouble getting it to work with if statements.

Here is my simple code so far:

#!/bin/bash

declare -i n
in=inches
ft=feet

read number in "as" feet
if [ ]; then
    echo "$n $in = $[n/12] $ft"
fi

What I want to do now is to create if/else statements to flow according to a number of conditionals dependent on the user input. So I want the user to type something like "24 inches as feet" or "50 yards as inches" and execute its respective output. Right now, I don't really know what to put into the if statements without getting an error like "command not found".

Any help would be appreciated. Thank you.

Body:
!/bin/bash

echo "enter a number to be converted"

read number

feet=$(($number*12))

inches=$(($number/12))

echo "feet conversion to inches="$feet

echo "inches conversion to feet="$inches

fi


问:
Errors while building Signed Android App Bundle file. Execution failed for task ':app:signReleaseBundle' > 'other' has different root
I'm trying to generate Signed Android App Bundle to publish it on Google Play but I'm getting error in the process. The following error occurs when I try to Generate Signed Android App Bundle.

This error doesn't happen if I try to build Signed APK. This only occurs in case of Android App Bundle.

Note: Error occurs after I updated my android studio 3.6.3 to version 4.0 and Gradle build to 6.1.1.

There is a solution here :
Generate Signed Bundle: Errors while building Bundle file. 'other' has different root

I tried that solution too of keeping the keystore path and release destination path same but with no luck again and again.

Any help will be much appreciated. Please help with all possible answers.

```<code>Executing tasks: [:app:bundleRelease] in project C:\Users\apoor\AndroidStudioProjects\SAID

> Task :app:preBuild UP-TO-DATE
> Task :app:preReleaseBuild UP-TO-DATE
> Task :app:compileReleaseRenderscript NO-SOURCE
> Task :app:generateReleaseResValues UP-TO-DATE
> Task :app:generateReleaseResources UP-TO-DATE
> Task :app:mergeReleaseResources UP-TO-DATE
> Task :app:createReleaseCompatibleScreenManifests UP-TO-DATE
> Task :app:extractDeepLinksRelease UP-TO-DATE
> Task :app:processReleaseManifest UP-TO-DATE
> Task :app:checkReleaseDuplicateClasses UP-TO-DATE
> Task :app:generateReleaseBuildConfig UP-TO-DATE
> Task :app:javaPreCompileRelease UP-TO-DATE
> Task :app:compileReleaseAidl NO-SOURCE
> Task :app:processReleaseResources
> Task :app:bundleReleaseResources
> Task :app:compileReleaseJavaWithJavac UP-TO-DATE
> Task :app:dexBuilderRelease UP-TO-DATE
> Task :app:desugarReleaseFileDependencies UP-TO-DATE
> Task :app:mergeExtDexRelease UP-TO-DATE
> Task :app:mergeDexRelease UP-TO-DATE
> Task :app:mergeReleaseShaders UP-TO-DATE
> Task :app:compileReleaseShaders NO-SOURCE
> Task :app:generateReleaseAssets UP-TO-DATE
> Task :app:mergeReleaseAssets UP-TO-DATE
> Task :app:processReleaseJavaRes NO-SOURCE
> Task :app:mergeReleaseJavaResource UP-TO-DATE
> Task :app:mergeReleaseJniLibFolders UP-TO-DATE
> Task :app:mergeReleaseNativeLibs UP-TO-DATE
> Task :app:stripReleaseDebugSymbols NO-SOURCE
> Task :app:buildReleasePreBundle
> Task :app:collectReleaseDependencies UP-TO-DATE
> Task :app:configureReleaseDependencies UP-TO-DATE
> Task :app:parseReleaseIntegrityConfig UP-TO-DATE
> Task :app:validateSigningRelease UP-TO-DATE
> Task :app:packageReleaseBundle
> Task :app:signReleaseBundle FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:signReleaseBundle'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > 'other' has different root

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
27 actionable tasks: 5 executed, 22 up-to-date
</code>```

Here is my app level build.gradle file :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.application.said"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        resConfig "en"

        bundle {
            language {
                enableSplit = false
            }
            density {
                enableSplit = true
            }
            abi {
                enableSplit = true
            }
        }

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Google Material Design Library
    implementation 'com.google.android.material:material:1.2.0-beta01'

    //Android Jetpack Navigation
    def nav_version = "2.3.0-beta01"
    implementation "androidx.navigation:navigation-fragment:$nav_version"
    implementation "androidx.navigation:navigation-ui:$nav_version"

    //Third Party Libraries
    implementation 'com.shreyaspatil:MaterialDialog:2.1'
    implementation 'com.airbnb.android:lottie:3.4.0'
    implementation 'com.github.hajiyevelnur92:intentanimation:1.0'
    implementation "com.github.skydoves:powermenu:2.1.3"
}
</code>```

答: In my case I had missed to copy over the key.properties file from inside root/android when I migrated the project.

Body:
I'm trying to generate Signed Android App Bundle to publish it on Google Play but I'm getting error in the process. The following error occurs when I try to Generate Signed Android App Bundle.

This error doesn't happen if I try to build Signed APK. This only occurs in case of Android App Bundle.

Note: Error occurs after I updated my android studio 3.6.3 to version 4.0 and Gradle build to 6.1.1.

There is a solution here :
Generate Signed Bundle: Errors while building Bundle file. 'other' has different root

I tried that solution too of keeping the keystore path and release destination path same but with no luck again and again.

Any help will be much appreciated. Please help with all possible answers.

Executing tasks: [:app:bundleRelease] in project C:\Users\apoor\AndroidStudioProjects\SAID

> Task :app:preBuild UP-TO-DATE
> Task :app:preReleaseBuild UP-TO-DATE
> Task :app:compileReleaseRenderscript NO-SOURCE
> Task :app:generateReleaseResValues UP-TO-DATE
> Task :app:generateReleaseResources UP-TO-DATE
> Task :app:mergeReleaseResources UP-TO-DATE
> Task :app:createReleaseCompatibleScreenManifests UP-TO-DATE
> Task :app:extractDeepLinksRelease UP-TO-DATE
> Task :app:processReleaseManifest UP-TO-DATE
> Task :app:checkReleaseDuplicateClasses UP-TO-DATE
> Task :app:generateReleaseBuildConfig UP-TO-DATE
> Task :app:javaPreCompileRelease UP-TO-DATE
> Task :app:compileReleaseAidl NO-SOURCE
> Task :app:processReleaseResources
> Task :app:bundleReleaseResources
> Task :app:compileReleaseJavaWithJavac UP-TO-DATE
> Task :app:dexBuilderRelease UP-TO-DATE
> Task :app:desugarReleaseFileDependencies UP-TO-DATE
> Task :app:mergeExtDexRelease UP-TO-DATE
> Task :app:mergeDexRelease UP-TO-DATE
> Task :app:mergeReleaseShaders UP-TO-DATE
> Task :app:compileReleaseShaders NO-SOURCE
> Task :app:generateReleaseAssets UP-TO-DATE
> Task :app:mergeReleaseAssets UP-TO-DATE
> Task :app:processReleaseJavaRes NO-SOURCE
> Task :app:mergeReleaseJavaResource UP-TO-DATE
> Task :app:mergeReleaseJniLibFolders UP-TO-DATE
> Task :app:mergeReleaseNativeLibs UP-TO-DATE
> Task :app:stripReleaseDebugSymbols NO-SOURCE
> Task :app:buildReleasePreBundle
> Task :app:collectReleaseDependencies UP-TO-DATE
> Task :app:configureReleaseDependencies UP-TO-DATE
> Task :app:parseReleaseIntegrityConfig UP-TO-DATE
> Task :app:validateSigningRelease UP-TO-DATE
> Task :app:packageReleaseBundle
> Task :app:signReleaseBundle FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:signReleaseBundle'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > 'other' has different root

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
27 actionable tasks: 5 executed, 22 up-to-date

Here is my app level build.gradle file :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.application.said"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        resConfig "en"

        bundle {
            language {
                enableSplit = false
            }
            density {
                enableSplit = true
            }
            abi {
                enableSplit = true
            }
        }

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Google Material Design Library
    implementation 'com.google.android.material:material:1.2.0-beta01'

    //Android Jetpack Navigation
    def nav_version = "2.3.0-beta01"
    implementation "androidx.navigation:navigation-fragment:$nav_version"
    implementation "androidx.navigation:navigation-ui:$nav_version"

    //Third Party Libraries
    implementation 'com.shreyaspatil:MaterialDialog:2.1'
    implementation 'com.airbnb.android:lottie:3.4.0'
    implementation 'com.github.hajiyevelnur92:intentanimation:1.0'
    implementation "com.github.skydoves:powermenu:2.1.3"
}


问:
How to fix "Expected to return a value in arrow function" with reactjs?
I have two function in my react-app components

```<code>componentDidMount() {
        if(Object.keys(this.props.praticiens).length>0)
            Object.keys(this.props.praticiens).map((praticien) => {
                if(this.props.praticiens[praticien].identifiant_user === getUrlParams(window.location.hash).identifiant_user)
                    this.setState({
                        praticien:this.props.praticiens[praticien].id_user
                    })
            })
    }

    handleChangePraticien = (praticien) => {
        this.setState({ praticien }, () => {
            Object.keys(this.props.praticiens).map((praticien) => {
                if(this.state.praticien === this.props.praticiens[praticien].id_user)
                    this.props.selectPraticienFunction(this.props.praticiens[praticien].identifiant_user);
            })
        })
    }
</code>```

When I run it, I get:

```<code>Line 26:64:  Expected to return a value in arrow function  array-callback-return
  Line 36:64:  Expected to return a value in arrow function  array-callback-return
</code>```

Such as the Line 26 is beginning Object.keys(this.props.praticiens).map((praticien) => { on componentDidMount and Line 36 is the same line on the handleChangePraticien function

How can I fix it ?

答:
If you need to return an array, but also place conditionals in the loop so that some items may not be returned you can combine .forEach with .push like this:

```<code>class Profiles extends Component {
  profilesArray() {
    let profiles_array = [];

    this.props.profiles.forEach((profile) => {
      // some condition
      if (profile.id !== this.props.whatever) {
        profiles_array.push(
          <ContentCard key={profile.profile_id}>
            <p>My Content</p>
          </ContentCard>
        );
      }
    });

    return profiles_array;
  }
  render() {
    return (
      <>
        <h1>Profiles</h1>
        {this.profilesArray()}
      </>
    );
  }
}
</code>```

Body:
I have two function in my react-app components

componentDidMount() {
        if(Object.keys(this.props.praticiens).length>0)
            Object.keys(this.props.praticiens).map((praticien) => {
                if(this.props.praticiens[praticien].identifiant_user === getUrlParams(window.location.hash).identifiant_user)
                    this.setState({
                        praticien:this.props.praticiens[praticien].id_user
                    })
            })
    }

    handleChangePraticien = (praticien) => {
        this.setState({ praticien }, () => {
            Object.keys(this.props.praticiens).map((praticien) => {
                if(this.state.praticien === this.props.praticiens[praticien].id_user)
                    this.props.selectPraticienFunction(this.props.praticiens[praticien].identifiant_user);
            })
        })
    }

When I run it, I get:

Line 26:64:  Expected to return a value in arrow function  array-callback-return
  Line 36:64:  Expected to return a value in arrow function  array-callback-return

Such as the Line 26 is beginning Object.keys(this.props.praticiens).map((praticien) => { on componentDidMount and Line 36 is the same line on the handleChangePraticien function

How can I fix it ?

Body:
If you need to return an array, but also place conditionals in the loop so that some items may not be returned you can combine .forEach with .push like this:

class Profiles extends Component {
  profilesArray() {
    let profiles_array = [];

    this.props.profiles.forEach((profile) => {
      // some condition
      if (profile.id !== this.props.whatever) {
        profiles_array.push(
          <ContentCard key={profile.profile_id}>
            <p>My Content</p>
          </ContentCard>
        );
      }
    });

    return profiles_array;
  }
  render() {
    return (
      <>
        <h1>Profiles</h1>
        {this.profilesArray()}
      </>
    );
  }
}


问:
LU Factorization for MATLAB
How do you write MATLAB code for LU factorization when U is the unit matrix instead of L. The upper triangular matrix will have the diagonal of 1s instead of the lower triangular matrix.</p>

答:
Here's one way to do this. If M is your matrix,

```<code>[P,Q] = lu(M');
L = Q'; U = P';
</code>```

Alternatively, assuming that M has an LU decomposition, we could do the following:

```<code>[L,U,P,Q,D] = lu(M);
L = L*P'*D*Q';
</code>```

This should yield a lower triangular L and upper triangular U where U has 1's on the diagonal whenever M has an LU decomposition.

Title: LU Factorization for MATLAB

Body:
Here's one way to do this. If M is your matrix,

[P,Q] = lu(M');
L = Q'; U = P';

Alternatively, assuming that M has an LU decomposition, we could do the following:

[L,U,P,Q,D] = lu(M);
L = L*P'*D*Q';

This should yield a lower triangular L and upper triangular U where U has 1's on the diagonal whenever M has an LU decomposition.


问:
In typescript, how can I safely render an anchor tag in a string as a react component?
In my react application, I am getting data from a database and displaying it on the webpage. One of the data, docs.description is a string like this "Click this link Example".

Currently everything I have tried is just printing out the entire string or just not working. I want to display the text on the site with the links interpreted and displayed as links should be, like: Click this link Example

Here is the section of code if it helps

```<code>export const DocContainer: FC<{docs: AssetDocs}> = ({docs}) => {
  return (
    <div className={styles.docContainer}>
      <Text h2 style={{color:"#26ff91"}}>Docs</Text>
      {docs && docs.description}
    </div>
  );
}
</code>```

Any help would be greatly appreciated! Please let me know if you need more details.

答:
There is actually 2 way to do this

The first is the useRef hook which will give you a reference of an HTML element (in your case it would be the parent div) which you can use as if you were in plain JS.

TL;DR  you can access the innerHTML prop

```<code>const ref = useRef();

return <div ref={ref}>
    // stuff goes here
</div>
</code>```

Or you can use the dangerouslySetInnerHTML React prop

```<code>return <div dangerouslySetInnerHTML={{ __html: "YOUR_HTML_STRING" }}></div>
</code>```

This should be sanitized tho before you actually use it, because you can get any kind of injection attack.

Personally I haven't used it, but I found this package which would do the job and it's moderately popular.

Body:
In my react application, I am getting data from a database and displaying it on the webpage. One of the data, docs.description is a string like this "Click this link Example".

Currently everything I have tried is just printing out the entire string or just not working. I want to display the text on the site with the links interpreted and displayed as links should be, like: Click this link Example

Here is the section of code if it helps

export const DocContainer: FC<{docs: AssetDocs}> = ({docs}) => {
  return (

      <Text h2 style={{color:"#26ff91"}}>Docs</Text>
      {docs && docs.description}

  );
}

Any help would be greatly appreciated! Please let me know if you need more details.

Body:
There is actually 2 way to do this

The first is the useRef hook which will give you a reference of an HTML element (in your case it would be the parent div) which you can use as if you were in plain JS.

TL;DR  you can access the innerHTML prop

const ref = useRef();

return <div ref={ref}>
    // stuff goes here
</div>

Or you can use the dangerouslySetInnerHTML React prop

return <div dangerouslySetInnerHTML={{ __html: "YOUR_HTML_STRING" }}></div>

This should be sanitized tho before you actually use it, because you can get any kind of injection attack.

Personally I haven't used it, but I found this package which would do the job and it's moderately popular.


问:
Sequentially take a window of rows from array (python)
I have an array of size nxm and want to take the first 10 rows and perform calculations, then take the next 10 rows perform calculations, etc. But this is hard coded, how can I make a loop?

Code Attempted:

```<code>import numpy as np
total = []
x= np.random.random((100,4))
a = np.average(x[:10])
total.append(a)
a = np.average(x[10:20])
total.append(a)
a = np.average(x[20:30])
....
</code>```

Goal:

```<code>for *this array*:
# to something
# append value
# go back and get next 10 values
</code>```

答:
```<code>import numpy as np
x = np.random.random((100,4))
a = 10
b = 100//a
c = 4
</code>```

You want the array of average numbers of the first 10 * 4 part, the second 10 * 4 part,..., right?

reshape function can be really useful here.

```<code>x_splited = x.reshape((-1, a*c))
total = x_splited.mean(axis=1)
</code>```

This is the answer you need. The reshape function let the first a*c elements in the original matrix become the first row of the new matrix. Then, mean(axis=1) help you get the average of the first row.

Also, you could try something like this:

```<code> x_splited = x.reshape((-1, a, c))
</code>```

You can do something more complicated than this question with it.

Just a tip: in python, it is prefered to avoid using loop because it is slow.

Second tip: if you are still not proficient in using loop in Python, you are encouraged to spend some time to practice it.

Body:
I have an array of size nxm and want to take the first 10 rows and perform calculations, then take the next 10 rows perform calculations, etc. But this is hard coded, how can I make a loop?

Code Attempted:

import numpy as np
total = []
x= np.random.random((100,4))
a = np.average(x[:10])
total.append(a)
a = np.average(x[10:20])
total.append(a)
a = np.average(x[20:30])
....

Goal:

for *this array*:
# to something
# append value
# go back and get next 10 values

Body:
import numpy as np
x = np.random.random((100,4))
a = 10
b = 100//a
c = 4

You want the array of average numbers of the first 10 * 4 part, the second 10 * 4 part,..., right?

reshape function can be really useful here.

x_splited = x.reshape((-1, a*c))
total = x_splited.mean(axis=1)

This is the answer you need. The reshape function let the first a*c elements in the original matrix become the first row of the new matrix. Then, mean(axis=1) help you get the average of the first row.

Also, you could try something like this:

 x_splited = x.reshape((-1, a, c))

You can do something more complicated than this question with it.

Just a tip: in python, it is prefered to avoid using loop because it is slow.

Second tip: if you are still not proficient in using loop in Python, you are encouraged to spend some time to practice it.


问:
Referencing HTML Form Elements in cloned table rows
First of all, thanks in advance to all those who contribute to this post.  I am trying to understand two things in the JS code below: 1) why must I check for an "undefined" element in a table row object when there is only one row, if second and third row objects can be referenced with the [x] index value... is there a simpler way to do this? 2) how do i appropriately clear field values on clone rows (in the addRow() function. What I have works, but not sure if it's the right way to do clear values).

Fiddle: https://jsfiddle.net/arperez/n6azm28k/7/

Here's the full script ("myTable" is within a FORM element named "myForm" inside the BODY tag):

```<code>function addRow() {
    var tblBody = document.getElementById("myTable").tBodies[0];
    var lastrow = tblBody.rows.length;
    var newNode = tblBody.rows[0].cloneNode(true);
    tblBody.appendChild(newNode);

    //Clear copied values from cloned row.
    document.myForm.txtQty[lastrow].value = "";  //This works, but is this the right way to clear the textbox value of the cloned row?
}

function calcTotals() {

    var qty = 0;
    var totalqty = 0;
    var rows = document.getElementById("myTable").tBodies[0].rows.length - 1;

    for (i=0; i<=rows; i++) {

        var element = document.myForm.txtQty[i];
        if (element === undefined) {  //If I don't do this check I get an error when there is only one row existing in the table and I try referencing it with [0]. Not sure why?
            qty = document.myForm.txtQty.value;  //This works, but why does txtQty[0] not work? Is this the right way to refer to the first element/row?
        } else {
            qty = document.myForm.txtQty[i].value;
        }
        totalqty = totalqty + Number(qty);
    }

    //Display total quantities calculated
    alert("Total = " + totalqty);
}

<table id="myTable">
    <thead>
         <th>Quantity</th>
    </thead>
    <tbody>
       <tr>
         <td><input type="number" id="txtQty" name="txtQty"></td>
       </tr>
   </tbody>
</table>
<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>
</code>```

答:
I'll give a brief description highlighting this example and the rest will have references. No #ids were needed only [name] although #id wouldn't be a problem, unless they were cloned.

There are two event handlers, one for click events (manageData(e) and one for change events (switchRow(e)), both are bound to the form.

```<code>   const UI = document.forms.UI;
   UI.onclick = manageData;
   UI.onchange = switchRow;
</code>```

There are two normal functions which are called from manageData(e):

```<code>    addRow();
    sum(array);
</code>```

manageData(e) delegates the click event to only specific tags and ignores the rest. It determines what the user clicked by using event.target property. It also references the form with e.currentTarget as the tag listening for click events. With the addition of the .elements property, you can access all form controls within the form. Moreover, you can reference a specific group that shares the same [name] attribute. The form interface also allows access to form controls individually by #id or [name] as well.

```<code>   /* Event Object */
   .target // what the user clicked, changed, etc
   .currentTarget // the element (aka tag) that listens for event
   event handler // term for the function that's bound to listener
   /* HTMLForms
   <form id='UI'>
   <input id='A0' name='A'>
   <input id='B0' name='A'>
   */
   cont UI = document.forms.UI // ref form
   cont io = UI.elements // ref all of form fields
   cont input1 = io.A0 // ref first input
   cont allInputs = [...io.A] // ref all [name='A'] as an array
</code>```

References

Events

Event Delegation

HTMLFormElement

const addRow = () => {
  const table = document.querySelector('table').tBodies[0];
  const copy = table.rows[0].cloneNode(true);
  const inp = copy.querySelector('input');
  inp.value = '';
  copy.querySelectorAll('td')[2].innerHTML = `<button name='rem' type='button'>Remove Row</button>`;
  table.appendChild(copy);
  inp.focus();
};

const sum = array => {
  return array.map(inp => +inp.value).reduce((sum, cur) => sum + cur);
};

const manageData = e => {
  const io = e.currentTarget.elements;
  const btn = e.target;

  if (btn.matches('button')) {
    switch (btn.name) {
      case 'add':
        addRow();
        break;
      case 'calc':
        let X = [...io.x];
        io.total.value = sum(X);
        break;
      case 'rem':
        btn.closest('tr').remove();
        break;
      default:
        break;
    }
  }
};

const switchRow = e => {
  const sel = e.target;
  if (sel.name === 'y') {
    let inp = sel.parentElement.previousElementSibling.firstElementChild;
    if (sel.value === '0') {
      inp.disabled = false;
      inp.name = 'x';
    } else {
      inp.disabled = true;
      inp.name = '_';
    }
  }
};

const UI = document.forms.UI;
UI.onclick = manageData;
UI.onchange = switchRow;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id='UI'>
  <table>
    <tbody>
      <tr>
        <td><input name='x' type='number'></td>
        <td>
          <select name='y'>
            <option value='0'>Enabled</option>
            <option value='1'>Disabled</option>
          </select>
        </td>
        <td></td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td><button name='add' type='button'>Add Row</button>
        </td>
        <td><button name='calc' type='button'>Total</button></td>
        <td><input name='total' readonly></td>
      </tr>
    </tfoot>
  </table>
</form></code>```

Body:
First of all, thanks in advance to all those who contribute to this post.  I am trying to understand two things in the JS code below: 1) why must I check for an "undefined" element in a table row object when there is only one row, if second and third row objects can be referenced with the [x] index value... is there a simpler way to do this? 2) how do i appropriately clear field values on clone rows (in the addRow() function. What I have works, but not sure if it's the right way to do clear values).

Fiddle: https://jsfiddle.net/arperez/n6azm28k/7/

Here's the full script ("myTable" is within a FORM element named "myForm" inside the BODY tag):

function addRow() {
    var tblBody = document.getElementById("myTable").tBodies[0];
    var lastrow = tblBody.rows.length;
    var newNode = tblBody.rows[0].cloneNode(true);
    tblBody.appendChild(newNode);

    //Clear copied values from cloned row.
    document.myForm.txtQty[lastrow].value = "";  //This works, but is this the right way to clear the textbox value of the cloned row?
}

function calcTotals() {

    var qty = 0;
    var totalqty = 0;
    var rows = document.getElementById("myTable").tBodies[0].rows.length - 1;

    for (i=0; i<=rows; i++) {

        var element = document.myForm.txtQty[i];
        if (element === undefined) {  //If I don't do this check I get an error when there is only one row existing in the table and I try referencing it with [0]. Not sure why?
            qty = document.myForm.txtQty.value;  //This works, but why does txtQty[0] not work? Is this the right way to refer to the first element/row?
        } else {
            qty = document.myForm.txtQty[i].value;
        }
        totalqty = totalqty + Number(qty);
    }

    //Display total quantities calculated
    alert("Total = " + totalqty);
}

         Quantity

         <input type="number" id="txtQty" name="txtQty">

<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>

Body:
I'll give a brief description highlighting this example and the rest will have references. No #ids were needed only [name] although #id wouldn't be a problem, unless they were cloned.

There are two event handlers, one for click events (manageData(e) and one for change events (switchRow(e)), both are bound to the form.

   const UI = document.forms.UI;
   UI.onclick = manageData;
   UI.onchange = switchRow;

There are two normal functions which are called from manageData(e):

    addRow();
    sum(array);

manageData(e) delegates the click event to only specific tags and ignores the rest. It determines what the user clicked by using event.target property. It also references the form with e.currentTarget as the tag listening for click events. With the addition of the .elements property, you can access all form controls within the form. Moreover, you can reference a specific group that shares the same [name] attribute. The form interface also allows access to form controls individually by #id or [name] as well.

   /* Event Object */
   .target // what the user clicked, changed, etc
   .currentTarget // the element (aka tag) that listens for event
   event handler // term for the function that's bound to listener
   /* HTMLForms
   <form id='UI'>
   <input id='A0' name='A'>
   <input id='B0' name='A'>
   */
   cont UI = document.forms.UI // ref form
   cont io = UI.elements // ref all of form fields
   cont input1 = io.A0 // ref first input
   cont allInputs = [...io.A] // ref all [name='A'] as an array

References

Events

Event Delegation

HTMLFormElement

const addRow = () => {
  const table = document.querySelector('table').tBodies[0];
  const copy = table.rows[0].cloneNode(true);
  const inp = copy.querySelector('input');
  inp.value = '';
  copy.querySelectorAll('td')[2].innerHTML = `<button name='rem' type='button'>Remove Row</button>`;
  table.appendChild(copy);
  inp.focus();
};

const sum = array => {
  return array.map(inp => +inp.value).reduce((sum, cur) => sum + cur);
};

const manageData = e => {
  const io = e.currentTarget.elements;
  const btn = e.target;

  if (btn.matches('button')) {
    switch (btn.name) {
      case 'add':
        addRow();
        break;
      case 'calc':
        let X = [...io.x];
        io.total.value = sum(X);
        break;
      case 'rem':
        btn.closest('tr').remove();
        break;
      default:
        break;
    }
  }
};

const switchRow = e => {
  const sel = e.target;
  if (sel.name === 'y') {
    let inp = sel.parentElement.previousElementSibling.firstElementChild;
    if (sel.value === '0') {
      inp.disabled = false;
      inp.name = 'x';
    } else {
      inp.disabled = true;
      inp.name = '_';
    }
  }
};

const UI = document.forms.UI;
UI.onclick = manageData;
UI.onchange = switchRow;

<form id='UI'>
  <table>
    <tbody>
      <tr>
        <td><input name='x' type='number'></td>
        <td>
          <select name='y'>
            <option value='0'>Enabled</option>
            <option value='1'>Disabled</option>
          </select>
        </td>
        <td></td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td><button name='add' type='button'>Add Row</button>
        </td>
        <td><button name='calc' type='button'>Total</button></td>
        <td><input name='total' readonly></td>
      </tr>
    </tfoot>
  </table>
</form>


问:
Python Serial Read Timer
So Im reading a serial device that sends data every couple of seconds, I have my timer running on the screen and the goal is that every time it updates the serial read it restarts the timer to zero.. This allows me to visually see if Ive lost contact with the device.  Ive spent alot of time searching to no avail.  Not real good with python so any help would be appreciated.</p>
```<code>from tkinter import *
from serial import Serial
import time
from serial.threaded import ReaderThread, Protocol
import threading
import tkinter as tk

#Input ED Number
ed_num = 0
def tkinter_input(prompt=""):
    global ed_num
    root = tk.Tk()
    root.wm_attributes('-fullscreen',1)
    root.configure(background='black')
    tk.Label(root, font=('Ariel', 100), foreground='Green',
                    background='Black', text=prompt).pack()
    entry = tk.Entry(root, font=('Ariel', 100),justify='center', foreground='Black',
                    background='white')
    entry.focus()
    entry.pack()
    result = None
    def callback(event):
        nonlocal result
        result = entry.get()
        root.destroy()
    entry.bind("<Return>", callback)
    root.mainloop()
    return result
result = tkinter_input("Scan Dosimeter")
ed_num = result
print(ed_num)

#Start Loop
root = Tk()

#Sets Main Window
root.wm_attributes('-fullscreen',1)
root.configure(background='black')

'''Shuts Down App will need to remove'''
button_quit = Button(root, text = 'QUIT', command = root.destroy).pack(anchor=NE)

#Container Frame
mainframe= Frame(root, bd=4, bg='Black')
mainframe.pack(anchor=CENTER, expand=True, fill=BOTH, padx=(20,20), pady=(20,20))
mainframe.grid_columnconfigure(0, weight=1)
mainframe.grid_rowconfigure(0, weight=1)
mainframe.grid_rowconfigure(1, weight=1)
mainframe.grid_rowconfigure(2, weight=1)

#ID Label
ed_id_label = Label(mainframe,
                    font=('Ariel', 50), foreground='Green',
                    background='Black', anchor='w')
ed_id_label.grid(row=0, column=0, sticky='ew', padx=(100,100), pady=(100,100))

#Dose Label
doselabel = Label(mainframe,
                  font=('Ariel', 130), foreground='Green',
                  background='Black', anchor='w')
doselabel.grid(row=1, column=0, sticky='ew', padx=(100,100), pady=(100,100))

# Rate Label
ratelabel = Label(mainframe,
                  font=('Ariel', 130), foreground='Green',
                  background='Black', anchor='w')
ratelabel.grid(row=2, column=0, sticky='ew', padx=(100,100), pady=(100,100))

#Timer Label
timelabel = Label(mainframe,
                  font=('Ariel', 20), foreground='Green',
                  background='Black', anchor='w')
timelabel.grid(row=3, column=0, sticky='se')

#Data Timer
seconds = 0
def countup(seconds):
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    root.after(1000, countup, seconds)

#Serial Reader Thread
class SerialReaderProtocolRaw(Protocol):

    def data_received(self, data):
        """Called with snippets received from the serial port"""
        updateLabelData(data)

def updateLabelData(data):
    data = data.decode("utf-8")
    if data[0:6] == ed_num:
        ed_id_label['text']='Ed id:   ' +data[0:6]
        doselabel['text']='Dose:   ' + data[11:14]+'.'+data[14:15]
        if data[21:22] == '0':
            ratelabel['text']='Rate:    ' + data[18:19]
        if data[21:22] == '1':
            ratelabel['text']='Rate:    ' + data[18:20]
        if data[21:22] == '2':
            ratelabel['text']='Rate:    ' + data[18:21]
        if data[21:22] == '3':
            ratelabel['text']='Rate:    ' + data[18:22]
        if data[6:7] =='1':
            doselabel.config(bg= "red")
        if data[6:7] =='2':
            ratelabel.config(bg= "red")
        root.update_idletasks()

# Initiate serial port
serial_port = Serial('COM3', baudrate = 57600)

# Initiate ReaderThread
reader = ReaderThread(serial_port, SerialReaderProtocolRaw)
# Initiate Counter Thread
countupthread = threading.Thread(target=countup, args = (seconds,))

# Start reader/counter
countupthread.start()
reader.start()
# Join Threads
countupthread.join()

root.after(1, countup, seconds)
root.mainloop()
</code>```

答:
There are at least two solutions I can think of off the top of my head: cancel and restart the counter, or make seconds global.

Stop and restart the counter

When you schedule something with after, it returns an identifier. You can pass this identifier to after_cancel to prevent that function from running.  Since you're not using classes, you can use a global variable to track this identifier.

Example:

```<code>def countup(seconds):
    global after_id
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    after_id = root.after(1000, countup, seconds)
</code>```

Then, whenever you need to reset the timer you can use the following two lines to cancel and restart countup:

```<code>root.after_cancel(after_id)
countup(0)
</code>```

Make seconds global

Instead of passing seconds to the countup function, have it use a global variable. You can then just reset this variable whenever you want.

```<code>seconds = 0
def countup():
    global seconds
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    after_id = root.after(1000, countup, seconds)
</code>```

With that, whenever you want to reset the counter you simply need to reset seconds:

```<code>global seconds
seconds = 0
</code>```

Title: Python Serial Read Timer

Body:
So Im reading a serial device that sends data every couple of seconds, I have my timer running on the screen and the goal is that every time it updates the serial read it restarts the timer to zero.. This allows me to visually see if Ive lost contact with the device.  Ive spent alot of time searching to no avail.  Not real good with python so any help would be appreciated.

from tkinter import *
from serial import Serial
import time
from serial.threaded import ReaderThread, Protocol
import threading
import tkinter as tk

#Input ED Number
ed_num = 0
def tkinter_input(prompt=""):
    global ed_num
    root = tk.Tk()
    root.wm_attributes('-fullscreen',1)
    root.configure(background='black')
    tk.Label(root, font=('Ariel', 100), foreground='Green',
                    background='Black', text=prompt).pack()
    entry = tk.Entry(root, font=('Ariel', 100),justify='center', foreground='Black',
                    background='white')
    entry.focus()
    entry.pack()
    result = None
    def callback(event):
        nonlocal result
        result = entry.get()
        root.destroy()
    entry.bind("<Return>", callback)
    root.mainloop()
    return result
result = tkinter_input("Scan Dosimeter")
ed_num = result
print(ed_num)

#Start Loop
root = Tk()

#Sets Main Window
root.wm_attributes('-fullscreen',1)
root.configure(background='black')

'''Shuts Down App will need to remove'''
button_quit = Button(root, text = 'QUIT', command = root.destroy).pack(anchor=NE)

#Container Frame
mainframe= Frame(root, bd=4, bg='Black')
mainframe.pack(anchor=CENTER, expand=True, fill=BOTH, padx=(20,20), pady=(20,20))
mainframe.grid_columnconfigure(0, weight=1)
mainframe.grid_rowconfigure(0, weight=1)
mainframe.grid_rowconfigure(1, weight=1)
mainframe.grid_rowconfigure(2, weight=1)

#ID Label
ed_id_label = Label(mainframe,
                    font=('Ariel', 50), foreground='Green',
                    background='Black', anchor='w')
ed_id_label.grid(row=0, column=0, sticky='ew', padx=(100,100), pady=(100,100))

#Dose Label
doselabel = Label(mainframe,
                  font=('Ariel', 130), foreground='Green',
                  background='Black', anchor='w')
doselabel.grid(row=1, column=0, sticky='ew', padx=(100,100), pady=(100,100))

# Rate Label
ratelabel = Label(mainframe,
                  font=('Ariel', 130), foreground='Green',
                  background='Black', anchor='w')
ratelabel.grid(row=2, column=0, sticky='ew', padx=(100,100), pady=(100,100))

#Timer Label
timelabel = Label(mainframe,
                  font=('Ariel', 20), foreground='Green',
                  background='Black', anchor='w')
timelabel.grid(row=3, column=0, sticky='se')

#Data Timer
seconds = 0
def countup(seconds):
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    root.after(1000, countup, seconds)

#Serial Reader Thread
class SerialReaderProtocolRaw(Protocol):

    def data_received(self, data):
        """Called with snippets received from the serial port"""
        updateLabelData(data)

def updateLabelData(data):
    data = data.decode("utf-8")
    if data[0:6] == ed_num:
        ed_id_label['text']='Ed id:   ' +data[0:6]
        doselabel['text']='Dose:   ' + data[11:14]+'.'+data[14:15]
        if data[21:22] == '0':
            ratelabel['text']='Rate:    ' + data[18:19]
        if data[21:22] == '1':
            ratelabel['text']='Rate:    ' + data[18:20]
        if data[21:22] == '2':
            ratelabel['text']='Rate:    ' + data[18:21]
        if data[21:22] == '3':
            ratelabel['text']='Rate:    ' + data[18:22]
        if data[6:7] =='1':
            doselabel.config(bg= "red")
        if data[6:7] =='2':
            ratelabel.config(bg= "red")
        root.update_idletasks()

# Initiate serial port
serial_port = Serial('COM3', baudrate = 57600)

# Initiate ReaderThread
reader = ReaderThread(serial_port, SerialReaderProtocolRaw)
# Initiate Counter Thread
countupthread = threading.Thread(target=countup, args = (seconds,))

# Start reader/counter
countupthread.start()
reader.start()
# Join Threads
countupthread.join()

root.after(1, countup, seconds)
root.mainloop()

Body:
There are at least two solutions I can think of off the top of my head: cancel and restart the counter, or make seconds global.

Stop and restart the counter

When you schedule something with after, it returns an identifier. You can pass this identifier to after_cancel to prevent that function from running.  Since you're not using classes, you can use a global variable to track this identifier.

Example:

def countup(seconds):
    global after_id
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    after_id = root.after(1000, countup, seconds)

Then, whenever you need to reset the timer you can use the following two lines to cancel and restart countup:

root.after_cancel(after_id)
countup(0)

Make seconds global

Instead of passing seconds to the countup function, have it use a global variable. You can then just reset this variable whenever you want.

seconds = 0
def countup():
    global seconds
    seconds += 1
    timelabel['text'] = str(seconds)+"s"
    after_id = root.after(1000, countup, seconds)

With that, whenever you want to reset the counter you simply need to reset seconds:

global seconds
seconds = 0


问:
sin function returning numbers outside of range [-1, 1]
I am working in Haskell and have had an error where, for really large floats z, sin(z) returns some value outside of the range [-1, 1].

I'm learning Haskell for the first time, so I have had very little luck debugging and the program just crashes when sin(z) does return a value outside of the above range as sin(z) is an input into another function that only accepts values inside the range [-1, 1].

Additionally, I don't have access to the other function, I only can send in a value, but it keeps crashing when sin(z) returns a number either greater than 1 or less than -1.

Is there any way to figure out why sin(z) is doing this?

答:
The sin :: Double -> Double function returns a number strictly between -1 and 1 for all finite inputs, no matter how large.  In particular, for the largest representable finite positive double, it returns a value that's roughly 0.005:

```<code>> sin (1.7976931348623157E+308 :: Double)
4.961954789184062e-3
</code>```

and for the largest representable finite negative double, it returns a value that's the negative of that:

```<code>> sin (-1.7976931348623157E+308 :: Double)
-4.961954789184062e-3
</code>```

What's undoubtedly happening is that your input to sin has exceeded the finite range of Double.  For example, the following double isn't actually representable as a finite double and is "rounded" to infinity:

```<code>> 1.7976931348623159E+308 :: Double
Infinity
</code>```

If you feed such an infinite value to sin, you get NaN:

```<code>> sin (1.7976931348623159E+308 :: Double)
NaN
</code>```

which will undoubtedly cause problems when fed to a function expecting finite numbers between -1 and 1.  This can be "fixed" with min:

```<code>> min (sin (1.7976931348623159E+308 :: Double)) 1
1.0
</code>```

but this fix is largely useless because you have a much bigger problem going on.

For numbers this large, the precision of a Double is on the order of plus or minus 1e292.  That is, two "adjacent" representable finite doubles of this size are about 1e292 apart and the sin of two such numbers might as well be random numbers between -1 and 1, completely unrelated to any calculation you're trying to complete.  Whatever you're trying to do with these numbers can't possibly be working as you intend.

Body:
The sin :: Double -> Double function returns a number strictly between -1 and 1 for all finite inputs, no matter how large.  In particular, for the largest representable finite positive double, it returns a value that's roughly 0.005:

> sin (1.7976931348623157E+308 :: Double)
4.961954789184062e-3

and for the largest representable finite negative double, it returns a value that's the negative of that:

> sin (-1.7976931348623157E+308 :: Double)
-4.961954789184062e-3

What's undoubtedly happening is that your input to sin has exceeded the finite range of Double.  For example, the following double isn't actually representable as a finite double and is "rounded" to infinity:

> 1.7976931348623159E+308 :: Double
Infinity

If you feed such an infinite value to sin, you get NaN:

> sin (1.7976931348623159E+308 :: Double)
NaN

which will undoubtedly cause problems when fed to a function expecting finite numbers between -1 and 1.  This can be "fixed" with min:

> min (sin (1.7976931348623159E+308 :: Double)) 1
1.0

but this fix is largely useless because you have a much bigger problem going on.

For numbers this large, the precision of a Double is on the order of plus or minus 1e292.  That is, two "adjacent" representable finite doubles of this size are about 1e292 apart and the sin of two such numbers might as well be random numbers between -1 and 1, completely unrelated to any calculation you're trying to complete.  Whatever you're trying to do with these numbers can't possibly be working as you intend.


问:
I can't seem to override a function using template.php
I'm trying to alter the comment links in my Drupal output, and I think I have found the function I want to influence, which is function comment_node_view($node, $view_mode).

It is in the Comment module. The problem is I can't seem to effect it, when I try to override it by putting it in my Template.php file and add my theme_ to the function name? In my template.php it looks like this now:

```<code>function themename_comment_node_view($node, $view_mode)
</code>```

if I take off the themename_ it causes an error saying I can't redeclare it.  I can copy the comment module and edit it directly but I thought this was how I theme something?

答:
The name spacing is 'hook_node_view' so you need to replace 'comment' (the name spacing used by the comment module) with your theme name:

```<code>function mytheme_node_view($node, $view_node)
</code>```

Hooks:

http://api.drupal.org/api/drupal/includes--module.inc/group/hooks/7

hook_node_view:

http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_view/7

Hope that helps :)

Body:
I'm trying to alter the comment links in my Drupal output, and I think I have found the function I want to influence, which is function comment_node_view($node, $view_mode).

It is in the Comment module. The problem is I can't seem to effect it, when I try to override it by putting it in my Template.php file and add my theme_ to the function name? In my template.php it looks like this now:

function themename_comment_node_view($node, $view_mode)

if I take off the themename_ it causes an error saying I can't redeclare it.  I can copy the comment module and edit it directly but I thought this was how I theme something?

Body:
The name spacing is 'hook_node_view' so you need to replace 'comment' (the name spacing used by the comment module) with your theme name:

function mytheme_node_view($node, $view_node)

Hooks:

http://api.drupal.org/api/drupal/includes--module.inc/group/hooks/7

hook_node_view:

http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_view/7

Hope that helps :)


问:
Kotlinx datetime missing 0 in date
Using kotlinx datetime i'm expecting this "11/02/22" when using this code

```<code>val date = "2022-02-11T07:00:00.000000Z".toInstant().toLocalDateTime(TimeZone.currentSystemDefault()).date
val newDate = "${date.dayOfMonth}/${date.monthNumber}/${date.year.toString().substring(2,4)}"
</code>```

However, this returns

```<code>11/2/22
</code>```

Is there a way to get the '0' back in the month?

答:
You could do it by using DateTimeFormatter

Like below

```<code>val newDate = date.format(DateTimeFormatter.ofPattern("dd/MM/yy"))
</code>```

Title: Kotlinx datetime missing 0 in date

Body:
Using kotlinx datetime i'm expecting this "11/02/22" when using this code

val date = "2022-02-11T07:00:00.000000Z".toInstant().toLocalDateTime(TimeZone.currentSystemDefault()).date
val newDate = "${date.dayOfMonth}/${date.monthNumber}/${date.year.toString().substring(2,4)}"

However, this returns

11/2/22

Is there a way to get the '0' back in the month?

Body:
You could do it by using DateTimeFormatter

Like below

val newDate = date.format(DateTimeFormatter.ofPattern("dd/MM/yy"))


问:
Cannot access <Button> with useRef()
I'm trying to access my buttons element with useRef in react. But I don't know why when I click on one button it always returns me the last element.

Here is my code

```<code>const selectPage = (value) => {
      dispatch(Action.changePage(value));
      console.log(ref.current);
   };

   const returnButton = (value) => {
      return (
         <button
            onClick={() => {
               selectPage(value);
            }}
            ref={ref}
         >
            <GiBeerStein />
         </button>
      );
   };

return (
    {returnButton(1)}
    {returnButton(2)}
    {returnButton(3)}
)
</code>```

Any idea why? Thank you.

答:
You shouldn't manually change the dom to add a classname. React will have no idea that you did so, and so it cannot take your change into account when it decides what future updates it needs to perform. In some cases, this may result in unexpected behavior, with react changing things you don't want to be changed, or vice versa.

Instead, you should use state. If you want exactly one button to be active at a time, then the state can be a number which is the index of the button that's active:

```<code>const [activeIndex, setActiveIndex] = useState(-1);

const selectPage = (value) => {
  dispatch(Action.changePage(value));
  setActiveIndex(value - 1);
};

const buttons = [];
for (let i = 0; i < 3; i++) {
  buttons.push(
    <button
      onClick={() => {
        selectPage(i + 1);
      }}
      className={activeIndex === i ? "active" : undefined}
    >
      <GiBeerStein />
    </button>
  );
}

return <>{buttons}</>;
</code>```

If instead you need to support multiple buttons being active, you can make the index an array of booleans:

```<code>
const [active, setActive] = useState([false, false, false]);

const selectPage = (value) => {
  setActiveIndex(prev => {
    const next = [...prev];
    next[value - 1] = !next[value - 1];
    return next;
  });
};

// ...
className={active[i] ? "active" : undefined}
</code>```

Title: Cannot access <Button> with useRef()

Body:
I'm trying to access my buttons element with useRef in react. But I don't know why when I click on one button it always returns me the last element.

Here is my code

const selectPage = (value) => {
      dispatch(Action.changePage(value));
      console.log(ref.current);
   };

   const returnButton = (value) => {
      return (
         <button
            onClick={() => {
               selectPage(value);
            }}
            ref={ref}
         >
            <GiBeerStein />
         </button>
      );
   };

return (
    {returnButton(1)}
    {returnButton(2)}
    {returnButton(3)}
)

Any idea why? Thank you.

Body:
You shouldn't manually change the dom to add a classname. React will have no idea that you did so, and so it cannot take your change into account when it decides what future updates it needs to perform. In some cases, this may result in unexpected behavior, with react changing things you don't want to be changed, or vice versa.

Instead, you should use state. If you want exactly one button to be active at a time, then the state can be a number which is the index of the button that's active:

const [activeIndex, setActiveIndex] = useState(-1);

const selectPage = (value) => {
  dispatch(Action.changePage(value));
  setActiveIndex(value - 1);
};

const buttons = [];
for (let i = 0; i < 3; i++) {
  buttons.push(
    <button
      onClick={() => {
        selectPage(i + 1);
      }}
      className={activeIndex === i ? "active" : undefined}
    >
      <GiBeerStein />
    </button>
  );
}

return <>{buttons}</>;

If instead you need to support multiple buttons being active, you can make the index an array of booleans:

const [active, setActive] = useState([false, false, false]);

const selectPage = (value) => {
  setActiveIndex(prev => {
    const next = [...prev];
    next[value - 1] = !next[value - 1];
    return next;
  });
};

// ...
className={active[i] ? "active" : undefined}


问:
How can I make this dropdown in react native?
Here is the default structure for dropdown

This is when you click the dropdown

I'm new to react native and I was wondering how can I make this kind of structure.
If anyone can help, thanks a lot.

答:
I think you'll have a little more success if you call this component an "accordion" in your searching. "Dropdown" sort of suggests a picker component to me.

I searched for "React Native accordion" and found this medium post that seems relevant. I might start there.


问:
Tabbed Content Tabs
I'm using this method from W3schools for tabbed content and it's working well except for one minor detail that is overlooked in their example.  When the tab is closed by clicking on the X in the content, the tab remains in the active presentation, a darker color in this instance.  I want the tabs to revert to their original appearance when the X is clicked (i.e. the lighter color).  I contacted W3schools to point out their example is missing this feature but did not hear back.  Can someone enlighten me on the code needed to achieve this?

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}</code>```

Tabs

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  &times

London

London is the capital city of England.

  &times

Paris

Paris is the capital of France.

  &times

Tokyo

Tokyo is the capital of Japan.

```

答:
Removing active class for tabLinks will do..

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

function closeCity(evt){
  let tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  evt.target.parentElement.style.display="none";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}</code>```

Tabs

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  &times

London

London is the capital city of England.

  &times

Paris

Paris is the capital of France.

  &times

Tokyo

Tokyo is the capital of Japan.

```

Title: Tabbed Content Tabs

Body:
I'm using this method from W3schools for tabbed content and it's working well except for one minor detail that is overlooked in their example.  When the tab is closed by clicking on the X in the content, the tab remains in the active presentation, a darker color in this instance.  I want the tabs to revert to their original appearance when the X is clicked (i.e. the lighter color).  I contacted W3schools to point out their example is missing this feature but did not hear back.  Can someone enlighten me on the code needed to achieve this?

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}

Tabs

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  &times

London

London is the capital city of England.

  &times

Paris

Paris is the capital of France.

  &times

Tokyo

Tokyo is the capital of Japan.

Body:
Removing active class for tabLinks will do..

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

function closeCity(evt){
  let tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  evt.target.parentElement.style.display="none";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}

<h2>Tabs</h2>
<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <span onclick="closeCity(event)" class="topright">&times</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <span onclick="closeCity(event)" class="topright">&times</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <span onclick="closeCity(event)" class="topright">&times</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>


问:
Store the integrity of a table's records
I had a question that I couldn't solve/answer, to exemplify I'll give a use case. I have an ORDER_ITEMS table that is related to the ORDER table and a PRODUCT(ID, PRODUCT_NAME) table that is related to ORDER_ITENS. As the sales system is fed, I have a history of orders and their products sold, let's say I change the PRODUCT_NAME, all products sold prior to the change will have their name changed as a result of the reference between the ORDER_ITEMS table with PRODUCT. Is there a pattern where I could store the integrity of the PRODUCT_NAME without affecting the orders placed before the product name change?</p>

答:
Such a join in a relational database looks up the current value.

If you need a history of that foreign field at the time of the child’s creation, make a copy. Add a column on the child table into which you copy the value of interest from the parent.

You likely will also want to capture the moment of this creation-and-copying by adding yet another column on the child table, of a type akin to the SQL standard type TIMESTAMP WITH TIME ZONE.

An alternative is to add an intermediate table, a child table to the parent with a pair of TIMESTAMP WITH TIME ZONE  columns that track when the sibling columns‘ values are in effect. Each time you modify the product’s name, you create a new row in this “in-effect” table. Each order item would link to a row in this “in-effect” table, with the more general product table being a grandparent to the order item.


问:
Best way of reading in a Mongo output as JSON without manual preprocessing
MongoDB outputs an array of documents as-is, by just pasting document after document, which means I end up with a JSON array that is missing both the wrapping brackets as well as the commas between objects. Usually, I manually preprocess those output files to make them valid JSON. However, my current output is over 500MB big, which means that I cannot open it in Notepad++.

What would be the smartest way to load and process such a huge document? Even if I somehow managed to make it valid JSON, could I perhaps somehow "stream" it object by object, so that I don't have it take up half a gig of memory? Is there a library for that?

Thanks

答: Notepad++ cannot open big files , use textpad , ultraedit ,vim ot others  to be able to open big files ( those editor use windowing tricks so they don't ocupy all your OS RAM for editing or viewing ...)</p>